@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
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a sandbox's applied policy delivers, and the checks around it: `stopsFor()` computes the stops from a tier and a
|
|
3
|
+
* policy, `policyDifference()` compares two policies field by field, and `confirmPolicy()` reads a provisioned
|
|
4
|
+
* sandbox's policy back and throws when it differs from the request. The capability helpers refuse a resume, snapshot
|
|
5
|
+
* or pause that the backend doesn't list. It is portable: it imports no Node module.
|
|
6
|
+
*/
|
|
7
|
+
import { SandboxPolicyMismatchError, SandboxUnsupportedError } from "./errors.js";
|
|
8
|
+
/**
|
|
9
|
+
* The method by which `resumeSandbox()` sets the stops of a sandbox whose `stops` is a getter, such as a backend
|
|
10
|
+
* sandbox's, so that a later `confirm()` still updates what the getter reads. It is internal to the package.
|
|
11
|
+
*/
|
|
12
|
+
export const APPLY_STOPS = Symbol("applyStops");
|
|
13
|
+
// Allowlist entries a hosted provider reads as "every host", so a policy holding one leaves egress open.
|
|
14
|
+
const OPEN_EGRESS = new Set(["*", "0.0.0.0/0", "::/0"]);
|
|
15
|
+
/** Whether a root is the whole file system, however many slashes it is written with. */
|
|
16
|
+
const isWholeDisk = (root) => /^\/+$/.test(root);
|
|
17
|
+
/**
|
|
18
|
+
* The stops a backend of `tier` delivers under `policy`. A `none` tier stops nothing. Any other tier stops `mistakes`
|
|
19
|
+
* unless a root is `/`, and `exfiltration` unless the allowlist holds an entry that opens every host (`*`, `0.0.0.0/0`
|
|
20
|
+
* or `::/0`). Only a `microvm` stops a `hostile_process`, because every other tier shares a kernel with the host or
|
|
21
|
+
* relies on one that runs in user space.
|
|
22
|
+
*/
|
|
23
|
+
export function stopsFor(tier, policy) {
|
|
24
|
+
if (tier === "none")
|
|
25
|
+
return [];
|
|
26
|
+
const stops = [];
|
|
27
|
+
if (![...policy.readRoots, ...policy.writeRoots].some(isWholeDisk))
|
|
28
|
+
stops.push("mistakes");
|
|
29
|
+
if (!policy.network.allow.some((entry) => OPEN_EGRESS.has(entry.trim())))
|
|
30
|
+
stops.push("exfiltration");
|
|
31
|
+
if (tier === "microvm")
|
|
32
|
+
stops.push("hostile_process");
|
|
33
|
+
return stops;
|
|
34
|
+
}
|
|
35
|
+
/** Whether `value` is a list of strings, which is the only shape a policy's lists may have. */
|
|
36
|
+
const isStringList = (value) => Array.isArray(value) && value.every((item) => typeof item === "string");
|
|
37
|
+
/** Whether two lists hold the same entries, ignoring order and repeats. */
|
|
38
|
+
function sameEntries(left, right) {
|
|
39
|
+
const a = new Set(left);
|
|
40
|
+
const b = new Set(right);
|
|
41
|
+
return a.size === b.size && [...a].every((entry) => b.has(entry));
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* The first field in which `applied` differs from `requested`, or `undefined` when they hold the same entries. The
|
|
45
|
+
* fields are compared as sets in the order `readRoots`, `writeRoots`, `network.allow`, `network.deny`, and a field
|
|
46
|
+
* that isn't a list of strings differs. Paths and hosts compare as written, so a backend reads back in the request's
|
|
47
|
+
* spelling.
|
|
48
|
+
*/
|
|
49
|
+
export function policyDifference(requested, applied) {
|
|
50
|
+
const network = applied.network;
|
|
51
|
+
const fields = [
|
|
52
|
+
["readRoots", requested.readRoots, applied.readRoots],
|
|
53
|
+
["writeRoots", requested.writeRoots, applied.writeRoots],
|
|
54
|
+
["network.allow", requested.network.allow, network?.allow],
|
|
55
|
+
["network.deny", requested.network.deny, network?.deny],
|
|
56
|
+
];
|
|
57
|
+
for (const [field, wanted, got] of fields) {
|
|
58
|
+
if (!isStringList(got) || !sameEntries(wanted, got))
|
|
59
|
+
return field;
|
|
60
|
+
}
|
|
61
|
+
return undefined;
|
|
62
|
+
}
|
|
63
|
+
// Why the applied policy can't deliver each stop, in words that hold no path or host from either policy.
|
|
64
|
+
const UNDELIVERED = {
|
|
65
|
+
mistakes: "the policy reads or writes the whole disk, so the sandbox cannot stop mistakes",
|
|
66
|
+
exfiltration: "the policy allows all hosts, so the sandbox cannot stop exfiltration",
|
|
67
|
+
hostile_process: "this tier shares a kernel with the host, so the sandbox cannot stop a hostile process",
|
|
68
|
+
};
|
|
69
|
+
/**
|
|
70
|
+
* Reads back the policy `sandbox` applied and compares it with `requested`. It resolves with the stops the applied
|
|
71
|
+
* policy delivers, and it throws `SandboxPolicyMismatchError` when a field differs, when the client claims a stop that
|
|
72
|
+
* the applied policy doesn't deliver (`stops`, with the cause in the message), or when a client that claims a stop has
|
|
73
|
+
* no read-back or its read-back fails (`readBack`, or the read-back's own field when it threw a mismatch). A client
|
|
74
|
+
* that claims no stop needs no read-back. It disposes the sandbox before it throws, unless `options.dispose` is
|
|
75
|
+
* `false`, which leaves the sandbox to the caller.
|
|
76
|
+
*/
|
|
77
|
+
export async function confirmPolicy(client, sandbox, requested, options = {}) {
|
|
78
|
+
const refuse = async (field, more) => {
|
|
79
|
+
if (options.dispose !== false)
|
|
80
|
+
await sandbox.dispose().catch(() => undefined);
|
|
81
|
+
throw new SandboxPolicyMismatchError(field, more);
|
|
82
|
+
};
|
|
83
|
+
if (typeof sandbox.readBack !== "function") {
|
|
84
|
+
if (client.stops.length === 0)
|
|
85
|
+
return [];
|
|
86
|
+
return refuse("readBack");
|
|
87
|
+
}
|
|
88
|
+
let applied;
|
|
89
|
+
try {
|
|
90
|
+
applied = await sandbox.readBack();
|
|
91
|
+
}
|
|
92
|
+
catch (error) {
|
|
93
|
+
// A read-back that found the mismatch itself, such as a settings file with another write root, names its field.
|
|
94
|
+
return refuse(error instanceof SandboxPolicyMismatchError ? error.field : "readBack", { cause: error });
|
|
95
|
+
}
|
|
96
|
+
const field = policyDifference(requested, applied);
|
|
97
|
+
if (field !== undefined)
|
|
98
|
+
return refuse(field);
|
|
99
|
+
const delivered = stopsFor(client.tier, applied);
|
|
100
|
+
const missing = client.stops.filter((stop) => !delivered.includes(stop));
|
|
101
|
+
if (missing.length > 0) {
|
|
102
|
+
return refuse("stops", { reason: [...new Set(missing)].map((stop) => UNDELIVERED[stop]).join("; ") });
|
|
103
|
+
}
|
|
104
|
+
return delivered;
|
|
105
|
+
}
|
|
106
|
+
/** Whether `client` lists `capability`. A client that lists none has none. */
|
|
107
|
+
export function hasCapability(client, capability) {
|
|
108
|
+
return Array.isArray(client.capabilities) && client.capabilities.includes(capability);
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Reattaches to a sandbox by its id, or starts one from a snapshot's id, then confirms its policy as `provision()`
|
|
112
|
+
* does and sets the sandbox's `stops` to what the confirmed policy delivers. It throws `SandboxUnsupportedError` when
|
|
113
|
+
* the client doesn't list `resume` or has no `resume()`, and `SandboxPolicyMismatchError` when the resumed sandbox's
|
|
114
|
+
* policy differs from `policy`. A mismatch does not dispose the sandbox, which may be a paused one worth keeping: the
|
|
115
|
+
* caller decides whether to dispose it, and must not run anything in it under the requested policy.
|
|
116
|
+
*/
|
|
117
|
+
export async function resumeSandbox(client, id, policy) {
|
|
118
|
+
if (!hasCapability(client, "resume") || typeof client.resume !== "function") {
|
|
119
|
+
throw new SandboxUnsupportedError("resume", client.tier);
|
|
120
|
+
}
|
|
121
|
+
const sandbox = await client.resume(id, policy);
|
|
122
|
+
const stops = await confirmPolicy(client, sandbox, policy, { dispose: false });
|
|
123
|
+
const apply = sandbox[APPLY_STOPS];
|
|
124
|
+
if (typeof apply === "function") {
|
|
125
|
+
// An own `stops` would shadow the getter, so a later confirm() could no longer change what the sandbox reports.
|
|
126
|
+
apply.call(sandbox, stops);
|
|
127
|
+
return sandbox;
|
|
128
|
+
}
|
|
129
|
+
const set = Reflect.defineProperty(sandbox, "stops", { value: stops, enumerable: true, configurable: true });
|
|
130
|
+
if (!set && !sameEntries(sandbox.stops ?? [], stops)) {
|
|
131
|
+
throw new SandboxPolicyMismatchError("stops", { reason: "the resumed sandbox's stops can't be set" });
|
|
132
|
+
}
|
|
133
|
+
return sandbox;
|
|
134
|
+
}
|
|
135
|
+
/** Snapshots `sandbox` and resolves with the id `resumeSandbox()` takes, or throws `SandboxUnsupportedError`. */
|
|
136
|
+
export async function snapshotSandbox(client, sandbox) {
|
|
137
|
+
if (!hasCapability(client, "snapshot") || typeof sandbox.snapshot !== "function") {
|
|
138
|
+
throw new SandboxUnsupportedError("snapshot", client.tier);
|
|
139
|
+
}
|
|
140
|
+
return sandbox.snapshot();
|
|
141
|
+
}
|
|
142
|
+
/** Pauses `sandbox` until `resumeSandbox()` with its `id`, or throws `SandboxUnsupportedError`. */
|
|
143
|
+
export async function pauseSandbox(client, sandbox) {
|
|
144
|
+
if (!hasCapability(client, "pause") || typeof sandbox.pause !== "function") {
|
|
145
|
+
throw new SandboxUnsupportedError("pause", client.tier);
|
|
146
|
+
}
|
|
147
|
+
await sandbox.pause();
|
|
148
|
+
}
|
|
149
|
+
//# sourceMappingURL=policy.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"policy.js","sourceRoot":"","sources":["../../src/sandbox/policy.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,0BAA0B,EAAE,uBAAuB,EAAE,MAAM,aAAa,CAAC;AAGlF;;;GAGG;AACH,MAAM,CAAC,MAAM,WAAW,GAAkB,MAAM,CAAC,YAAY,CAAC,CAAC;AAE/D,yGAAyG;AACzG,MAAM,WAAW,GAAG,IAAI,GAAG,CAAC,CAAC,GAAG,EAAE,WAAW,EAAE,MAAM,CAAC,CAAC,CAAC;AAExD,wFAAwF;AACxF,MAAM,WAAW,GAAG,CAAC,IAAY,EAAW,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAElE;;;;;GAKG;AACH,MAAM,UAAU,QAAQ,CAAC,IAAiB,EAAE,MAAqB;IAC/D,IAAI,IAAI,KAAK,MAAM;QAAE,OAAO,EAAE,CAAC;IAC/B,MAAM,KAAK,GAAkB,EAAE,CAAC;IAChC,IA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,aAAa,CAAC,MAAM,EAAE,UAAU,CAAC,IAAI,OAAO,OAAO,CAAC,QAAQ,KAAK,UAAU,EAAE,CAAC;QACjF,MAAM,IAAI,uBAAuB,CAAC,UAAU,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC;IAC7D,CAAC;IACD,OAAO,OAAO,CAAC,QAAQ,EAAE,CAAC;AAC5B,CAAC;AAED,mGAAmG;AACnG,MAAM,CAAC,KAAK,UAAU,YAAY,CAAC,MAAqB,EAAE,OAAgB;IACxE,IAAI,CAAC,aAAa,CAAC,MAAM,EAAE,OAAO,CAAC,IAAI,OAAO,OAAO,CAAC,KAAK,KAAK,UAAU,EAAE,CAAC;QAC3E,MAAM,IAAI,uBAAuB,CAAC,OAAO,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC;IAC1D,CAAC;IACD,MAAM,OAAO,CAAC,KAAK,EAAE,CAAC;AACxB,CAAC","sourcesContent":["/**\n * What a sandbox's applied policy delivers, and the checks around it: `stopsFor()` computes the stops from a tier and a\n * policy, `policyDifference()` compares two policies field by field, and `confirmPolicy()` reads a provisioned\n * sandbox's policy back and throws when it differs from the request. The capability helpers refuse a resume, snapshot\n * or pause that the backend doesn't list. It is portable: it imports no Node module.\n */\nimport { SandboxPolicyMismatchError, SandboxUnsupportedError } from \"./errors.js\";\nimport type { Sandbox, SandboxCapability, SandboxClient, SandboxPolicy, SandboxStop, SandboxTier } from \"./types.js\";\n\n/**\n * The method by which `resumeSandbox()` sets the stops of a sandbox whose `stops` is a getter, such as a backend\n * sandbox's, so that a later `confirm()` still updates what the getter reads. It is internal to the package.\n */\nexport const APPLY_STOPS: unique symbol = Symbol(\"applyStops\");\n\n// Allowlist entries a hosted provider reads as \"every host\", so a policy holding one leaves egress open.\nconst OPEN_EGRESS = new Set([\"*\", \"0.0.0.0/0\", \"::/0\"]);\n\n/** Whether a root is the whole file system, however many slashes it is written with. */\nconst isWholeDisk = (root: string): boolean => /^\\/+$/.test(root);\n\n/**\n * The stops a backend of `tier` delivers under `policy`. A `none` tier stops nothing. Any other tier stops `mistakes`\n * unless a root is `/`, and `exfiltration` unless the allowlist holds an entry that opens every host (`*`, `0.0.0.0/0`\n * or `::/0`). Only a `microvm` stops a `hostile_process`, because every other tier shares a kernel with the host or\n * relies on one that runs in user space.\n */\nexport function stopsFor(tier: SandboxTier, policy: SandboxPolicy): SandboxStop[] {\n if (tier === \"none\") return [];\n const stops: SandboxStop[] = [];\n if (![...policy.readRoots, ...policy.writeRoots].some(isWholeDisk)) stops.push(\"mistakes\");\n if (!policy.network.allow.some((entry) => OPEN_EGRESS.has(entry.trim()))) stops.push(\"exfiltration\");\n if (tier === \"microvm\") stops.push(\"hostile_process\");\n return stops;\n}\n\n/** Whether `value` is a list of strings, which is the only shape a policy's lists may have. */\nconst isStringList = (value: unknown): value is readonly string[] =>\n Array.isArray(value) && value.every((item) => typeof item === \"string\");\n\n/** Whether two lists hold the same entries, ignoring order and repeats. */\nfunction sameEntries(left: readonly string[], right: readonly string[]): boolean {\n const a = new Set(left);\n const b = new Set(right);\n return a.size === b.size && [...a].every((entry) => b.has(entry));\n}\n\n/**\n * The first field in which `applied` differs from `requested`, or `undefined` when they hold the same entries. The\n * fields are compared as sets in the order `readRoots`, `writeRoots`, `network.allow`, `network.deny`, and a field\n * that isn't a list of strings differs. Paths and hosts compare as written, so a backend reads back in the request's\n * spelling.\n */\nexport function policyDifference(requested: SandboxPolicy, applied: SandboxPolicy): string | undefined {\n const network = (applied as { network?: unknown }).network as Partial<SandboxPolicy[\"network\"]> | undefined;\n const fields: [string, readonly string[], unknown][] = [\n [\"readRoots\", requested.readRoots, (applied as { readRoots?: unknown }).readRoots],\n [\"writeRoots\", requested.writeRoots, (applied as { writeRoots?: unknown }).writeRoots],\n [\"network.allow\", requested.network.allow, network?.allow],\n [\"network.deny\", requested.network.deny, network?.deny],\n ];\n for (const [field, wanted, got] of fields) {\n if (!isStringList(got) || !sameEntries(wanted, got)) return field;\n }\n return undefined;\n}\n\n// Why the applied policy can't deliver each stop, in words that hold no path or host from either policy.\nconst UNDELIVERED: Record<SandboxStop, string> = {\n mistakes: \"the policy reads or writes the whole disk, so the sandbox cannot stop mistakes\",\n exfiltration: \"the policy allows all hosts, so the sandbox cannot stop exfiltration\",\n hostile_process: \"this tier shares a kernel with the host, so the sandbox cannot stop a hostile process\",\n};\n\n/** The options of `confirmPolicy()`. */\ninterface ConfirmOptions {\n /** Whether a mismatch disposes the sandbox before it is thrown. Defaults to `true`. */\n readonly dispose?: boolean;\n}\n\n/**\n * Reads back the policy `sandbox` applied and compares it with `requested`. It resolves with the stops the applied\n * policy delivers, and it throws `SandboxPolicyMismatchError` when a field differs, when the client claims a stop that\n * the applied policy doesn't deliver (`stops`, with the cause in the message), or when a client that claims a stop has\n * no read-back or its read-back fails (`readBack`, or the read-back's own field when it threw a mismatch). A client\n * that claims no stop needs no read-back. It disposes the sandbox before it throws, unless `options.dispose` is\n * `false`, which leaves the sandbox to the caller.\n */\nexport async function confirmPolicy(\n client: SandboxClient,\n sandbox: Sandbox,\n requested: SandboxPolicy,\n options: ConfirmOptions = {},\n): Promise<readonly SandboxStop[]> {\n const refuse = async (field: string, more?: { cause?: unknown; reason?: string }): Promise<never> => {\n if (options.dispose !== false) await sandbox.dispose().catch(() => undefined);\n throw new SandboxPolicyMismatchError(field, more);\n };\n if (typeof sandbox.readBack !== \"function\") {\n if (client.stops.length === 0) return [];\n return refuse(\"readBack\");\n }\n let applied: SandboxPolicy;\n try {\n applied = await sandbox.readBack();\n } catch (error) {\n // A read-back that found the mismatch itself, such as a settings file with another write root, names its field.\n return refuse(error instanceof SandboxPolicyMismatchError ? error.field : \"readBack\", { cause: error });\n }\n const field = policyDifference(requested, applied);\n if (field !== undefined) return refuse(field);\n const delivered = stopsFor(client.tier, applied);\n const missing = client.stops.filter((stop) => !delivered.includes(stop));\n if (missing.length > 0) {\n return refuse(\"stops\", { reason: [...new Set(missing)].map((stop) => UNDELIVERED[stop]).join(\"; \") });\n }\n return delivered;\n}\n\n/** Whether `client` lists `capability`. A client that lists none has none. */\nexport function hasCapability(client: SandboxClient, capability: SandboxCapability): boolean {\n return Array.isArray(client.capabilities) && client.capabilities.includes(capability);\n}\n\n/**\n * Reattaches to a sandbox by its id, or starts one from a snapshot's id, then confirms its policy as `provision()`\n * does and sets the sandbox's `stops` to what the confirmed policy delivers. It throws `SandboxUnsupportedError` when\n * the client doesn't list `resume` or has no `resume()`, and `SandboxPolicyMismatchError` when the resumed sandbox's\n * policy differs from `policy`. A mismatch does not dispose the sandbox, which may be a paused one worth keeping: the\n * caller decides whether to dispose it, and must not run anything in it under the requested policy.\n */\nexport async function resumeSandbox(client: SandboxClient, id: string, policy: SandboxPolicy): Promise<Sandbox> {\n if (!hasCapability(client, \"resume\") || typeof client.resume !== \"function\") {\n throw new SandboxUnsupportedError(\"resume\", client.tier);\n }\n const sandbox = await client.resume(id, policy);\n const stops = await confirmPolicy(client, sandbox, policy, { dispose: false });\n const apply = (sandbox as { [APPLY_STOPS]?: (stops: readonly SandboxStop[]) => void })[APPLY_STOPS];\n if (typeof apply === \"function\") {\n // An own `stops` would shadow the getter, so a later confirm() could no longer change what the sandbox reports.\n apply.call(sandbox, stops);\n return sandbox;\n }\n const set = Reflect.defineProperty(sandbox, \"stops\", { value: stops, enumerable: true, configurable: true });\n if (!set && !sameEntries(sandbox.stops ?? [], stops)) {\n throw new SandboxPolicyMismatchError(\"stops\", { reason: \"the resumed sandbox's stops can't be set\" });\n }\n return sandbox;\n}\n\n/** Snapshots `sandbox` and resolves with the id `resumeSandbox()` takes, or throws `SandboxUnsupportedError`. */\nexport async function snapshotSandbox(client: SandboxClient, sandbox: Sandbox): Promise<string> {\n if (!hasCapability(client, \"snapshot\") || typeof sandbox.snapshot !== \"function\") {\n throw new SandboxUnsupportedError(\"snapshot\", client.tier);\n }\n return sandbox.snapshot();\n}\n\n/** Pauses `sandbox` until `resumeSandbox()` with its `id`, or throws `SandboxUnsupportedError`. */\nexport async function pauseSandbox(client: SandboxClient, sandbox: Sandbox): Promise<void> {\n if (!hasCapability(client, \"pause\") || typeof sandbox.pause !== \"function\") {\n throw new SandboxUnsupportedError(\"pause\", client.tier);\n }\n await sandbox.pause();\n}\n"]}
|
package/dist/sandbox/process.js
CHANGED
|
@@ -218,7 +218,7 @@ export class ProcessRunner {
|
|
|
218
218
|
this.running.add(onDispose);
|
|
219
219
|
if (options.timeoutMs !== undefined) {
|
|
220
220
|
const note = `timed out after ${options.timeoutMs} ms\n`;
|
|
221
|
-
timer = setTimeout(() => void stop(() => resolve({ exitCode: TIMEOUT_EXIT_CODE, ...output(note) })), options.timeoutMs);
|
|
221
|
+
timer = setTimeout(() => void stop(() => resolve({ exitCode: TIMEOUT_EXIT_CODE, timedOut: true, ...output(note) })), options.timeoutMs);
|
|
222
222
|
}
|
|
223
223
|
child.on("error", (error) => {
|
|
224
224
|
done(() => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"process.js","sourceRoot":"","sources":["../../src/sandbox/process.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,uBAAuB,EAAE,MAAM,aAAa,CAAC;AAGtD,gEAAgE;AAChE,MAAM,iBAAiB,GAAG,GAAG,CAAC;AAC9B,2DAA2D;AAC3D,MAAM,mBAAmB,GAAG,GAAG,CAAC;AAChC,kFAAkF;AAClF,MAAM,gBAAgB,GAAG,GAAG,CAAC;AAC7B,MAAM,wBAAwB,GAAG,CAAC,GAAG,IAAI,GAAG,IAAI,CAAC;AACjD,+DAA+D;AAC/D,MAAM,YAAY,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;AACjC,0DAA0D;AAC1D,MAAM,gBAAgB,GAAG,MAAM,CAAC;AAWhC,iGAAiG;AACjG,MAAM,UAAU,WAAW,CAAC,OAAe;IACzC,IAAI,OAAO,OAAO,KAAK,WAAW,IAAI,OAAO,OAAO,CAAC,gBAAgB,KAA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;oBAChB,CAAC;gBACH,CAAC,CAAC,CAAC;YACL,CAAC,CAAC,CAAC;YACH,6FAA6F;YAC7F,KAAK,CAAC,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;YAClC,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QAC9B,CAAC,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["/**\n * The process handling that the Node-only sandbox backends share: checking a command's options, running it in its own\n * process group, capping its output, and ending the whole tree on a timeout, an abort or a dispose. It loads Node's\n * modules by `process.getBuiltinModule()` when it is used, so importing it costs a portable bundle nothing.\n */\nimport { HarnessError } from \"../errors.js\";\nimport { SandboxUnavailableError } from \"./errors.js\";\nimport type { ExecOptions, ExecResult } from \"./types.js\";\n\n// The exit code GNU `timeout` uses, which callers already know.\nconst TIMEOUT_EXIT_CODE = 124;\n// The exit code a shell gives for a program it can't find.\nconst NOT_FOUND_EXIT_CODE = 127;\n// A shell reports a command that a signal killed as 128 plus the signal's number.\nconst SIGNAL_EXIT_BASE = 128;\nconst DEFAULT_MAX_OUTPUT_BYTES = 8 * 1024 * 1024;\n// The longest delay a timer takes: a larger one fires at once.\nconst MAX_TIMER_MS = 2 ** 31 - 1;\n// The longest a stop waits for a backend's `onStop` hook.\nconst STOP_HOOK_MAX_MS = 15_000;\n\n/** The Node modules the backends use. */\nexport type NodeModules = {\n readonly cp: typeof import(\"node:child_process\");\n readonly fs: typeof import(\"node:fs/promises\");\n readonly os: typeof import(\"node:os\");\n readonly path: typeof import(\"node:path\");\n readonly url: typeof import(\"node:url\");\n};\n\n/** Node's modules, or a `SandboxUnavailableError` for `backend` on a runtime that lacks them. */\nexport function nodeModules(backend: string): NodeModules {\n if (typeof process === \"undefined\" || typeof process.getBuiltinModule !== \"function\") {\n throw new SandboxUnavailableError(\n backend,\n \"it runs commands through Node's child_process, which this runtime lacks\",\n );\n }\n return {\n cp: process.getBuiltinModule(\"node:child_process\"),\n fs: process.getBuiltinModule(\"node:fs/promises\"),\n os: process.getBuiltinModule(\"node:os\"),\n path: process.getBuiltinModule(\"node:path\"),\n url: process.getBuiltinModule(\"node:url\"),\n };\n}\n\n/** The length to keep of cut output, backing up over a UTF-8 character that the cut split. */\nfunction whole(chunks: readonly Uint8Array[], size: number): number {\n const last = chunks[chunks.length - 1];\n if (last === undefined) return 0;\n // Find the lead byte of the last character within the final three bytes, and drop it if its character is incomplete.\n for (let back = 1; back <= Math.min(3, last.length); back += 1) {\n const byte = last[last.length - back] as number;\n if ((byte & 0xc0) === 0x80) continue;\n const need = byte >= 0xf0 ? 4 : byte >= 0xe0 ? 3 : byte >= 0xc0 ? 2 : 1;\n return need > back ? size - back : size;\n }\n return size;\n}\n\n/** Throws unless the options are usable. */\nexport function checkOptions(options: ExecOptions): void {\n const { maxOutputBytes, timeoutMs } = options;\n if (maxOutputBytes !== undefined && !(Number.isInteger(maxOutputBytes) && maxOutputBytes >= 0)) {\n throw new HarnessError(\"invalid_sandbox_options\", \"maxOutputBytes must be a non-negative whole number\");\n }\n if (timeoutMs !== undefined && !(Number.isFinite(timeoutMs) && timeoutMs > 0 && timeoutMs <= MAX_TIMER_MS)) {\n throw new HarnessError(\"invalid_sandbox_options\", `timeoutMs must be a number from 1 to ${MAX_TIMER_MS}`);\n }\n}\n\n/** Throws unless the command is a non-empty list of strings. */\nexport function checkCommand(command: readonly string[]): void {\n if (!Array.isArray(command) || command.length === 0 || command.some((part) => typeof part !== \"string\")) {\n throw new HarnessError(\"invalid_sandbox_options\", \"a sandbox command is a non-empty list of strings\");\n }\n}\n\n/** Keeps the first `limit` bytes of a stream and drops the rest, but keeps reading so the child never blocks. */\nfunction capture(stream: NodeJS.ReadableStream, limit: number) {\n const chunks: Uint8Array[] = [];\n let size = 0;\n let truncated = false;\n stream.on(\"data\", (chunk: Uint8Array) => {\n const room = limit - size;\n if (chunk.length <= room) {\n chunks.push(chunk);\n size += chunk.length;\n } else {\n if (room > 0) chunks.push(chunk.subarray(0, room));\n size = limit;\n truncated = true;\n }\n });\n const joined = (): Uint8Array => {\n const all = new Uint8Array(size);\n let at = 0;\n for (const chunk of chunks) {\n all.set(chunk, at);\n at += chunk.length;\n }\n return all;\n };\n return {\n get truncated() {\n return truncated;\n },\n bytes: joined,\n text(): string {\n const all = joined();\n return new TextDecoder().decode(truncated ? all.subarray(0, whole(chunks, size)) : all);\n },\n };\n}\n\ntype Capture = ReturnType<typeof capture>;\n\n/** A process's captured output as the fields of a result, with `note` added to the end of standard error. */\nfunction outputOf(out: Capture, err: Capture, note: string) {\n return {\n stdout: out.text(),\n stdoutBytes: out.bytes(),\n stderr: `${err.text()}${note}`,\n ...(out.truncated || err.truncated ? { truncated: true } : {}),\n };\n}\n\n/** The result for a program that can't be started, as a shell reports it. */\nfunction notFound(program: string) {\n return {\n exitCode: NOT_FOUND_EXIT_CODE,\n stdout: \"\",\n stdoutBytes: new Uint8Array(),\n stderr: `command not found: ${program}\\n`,\n };\n}\n\n/** What one process is started with. */\nexport interface ProcessSpec {\n readonly program: string;\n readonly args: readonly string[];\n readonly cwd: string;\n readonly env: Readonly<Record<string, string>>;\n /** Bytes to write to the process's standard input before closing it. Without it, standard input is closed at once. */\n readonly input?: Uint8Array;\n /** Whether a program that can't be started is a result with exit code 127, as a shell gives, or a rejection. */\n readonly missingProgram: \"result\" | \"reject\";\n /**\n * How long a stopped process's group has to exit after a `SIGTERM`, which lets a program clean up, before a `SIGKILL`\n * ends what is left. Without it the group is killed at once.\n */\n readonly graceMs?: number;\n /**\n * Runs, and is awaited, when a timeout, an abort or `stopAll()` ends the process, before its group is killed. A\n * backend whose commands run outside the process's group, such as in a container, ends them here.\n */\n readonly onStop?: () => Promise<void>;\n}\n\n/** A finished process: the `ExecResult` fields, and the raw bytes of standard output. */\nexport type ProcessResult = Extract<ExecResult, { exitCode: number }> & { readonly stdoutBytes: Uint8Array };\n\n/** Runs processes, each in its own group, and ends them all on `stopAll()`. */\nexport class ProcessRunner {\n private readonly modules: NodeModules;\n // What stops each process still running, so `stopAll()` can end them.\n private readonly running = new Set<() => Promise<void>>();\n\n constructor(modules: NodeModules) {\n this.modules = modules;\n }\n\n /** Kills the process's whole group, or just the process where the platform has no groups. */\n private kill(child: import(\"node:child_process\").ChildProcess): void {\n const pid = child.pid;\n if (pid === undefined) return;\n try {\n if (process.platform === \"win32\") child.kill(\"SIGKILL\");\n else process.kill(-pid, \"SIGKILL\");\n } catch {\n // The group is already gone, so there is nothing left to kill.\n }\n }\n\n /** The exit code, and the signal's name when a signal killed the process. */\n private exit(code: number | null, signal: NodeJS.Signals | null): { exitCode: number; signal?: string } {\n if (signal === null) return { exitCode: code ?? 1 };\n return { exitCode: SIGNAL_EXIT_BASE + (this.modules.os.constants.signals[signal] ?? 0), signal };\n }\n\n /** Ends every process still running, each one's promise rejecting with `sandbox_disposed`, and waits until they have. */\n async stopAll(): Promise<void> {\n await Promise.all([...this.running].map((stop) => stop()));\n }\n\n /** Ends the process's group: at once, or with a `SIGTERM` first and a `SIGKILL` after `graceMs` for what is left. */\n private async end(\n child: import(\"node:child_process\").ChildProcess,\n graceMs: number,\n onStop?: () => Promise<void>,\n ): Promise<void> {\n // Runs beside the kill, and is waited for only so long, so a hook that hangs can't hold the call.\n const hook = onStop?.().catch(() => {});\n const running = child.exitCode === null && child.signalCode === null;\n if (graceMs > 0 && process.platform !== \"win32\" && child.pid !== undefined && running) {\n const exited = new Promise<void>((resolve) => child.once(\"exit\", () => resolve()));\n let timer: ReturnType<typeof setTimeout> | undefined;\n const expired = new Promise<void>((resolve) => {\n timer = setTimeout(resolve, graceMs);\n });\n try {\n process.kill(-child.pid, \"SIGTERM\");\n } catch {\n // The group is already gone.\n }\n await Promise.race([exited, expired]);\n clearTimeout(timer);\n }\n this.kill(child);\n if (hook !== undefined)\n await Promise.race([hook, new Promise<void>((resolve) => setTimeout(resolve, STOP_HOOK_MAX_MS).unref())]);\n }\n\n /**\n * Runs the process and resolves when it exits, its signal aborts it, its timeout passes (exit code 124) or `stopAll()`\n * runs. An abort rejects with the signal's reason, and `stopAll()` with `sandbox_disposed`.\n */\n run(spec: ProcessSpec, options: ExecOptions): Promise<ProcessResult> {\n const limit = options.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;\n return new Promise((resolve, reject) => {\n const child = this.modules.cp.spawn(spec.program, [...spec.args], {\n cwd: spec.cwd,\n env: { ...spec.env },\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n detached: true,\n });\n const out = capture(child.stdout, limit);\n const err = capture(child.stderr, limit);\n const output = (note = \"\") => outputOf(out, err, note);\n let settled = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const done = (settle: () => void) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n options.signal.removeEventListener(\"abort\", onAbort);\n this.running.delete(onDispose);\n settle();\n };\n // Ends the whole tree and stops waiting for the pipes, which a surviving grandchild would hold open.\n let stopping: Promise<void> | undefined;\n const stop = (settle: () => void): Promise<void> => {\n if (stopping !== undefined || settled) return stopping ?? Promise.resolve();\n stopping = this.end(child, spec.graceMs ?? 0, spec.onStop).then(() => {\n child.stdout.destroy();\n child.stderr.destroy();\n done(settle);\n });\n return stopping;\n };\n const onAbort = () => void stop(() => reject(options.signal.reason));\n const onDispose = () => stop(() => reject(new HarnessError(\"sandbox_disposed\", \"the sandbox was disposed\")));\n options.signal.addEventListener(\"abort\", onAbort, { once: true });\n this.running.add(onDispose);\n if (options.timeoutMs !== undefined) {\n const note = `timed out after ${options.timeoutMs} ms\\n`;\n timer = setTimeout(\n () => void stop(() => resolve({ exitCode: TIMEOUT_EXIT_CODE, ...output(note) })),\n options.timeoutMs,\n );\n }\n child.on(\"error\", (error: NodeJS.ErrnoException) => {\n done(() => {\n if (error.code === \"ENOENT\" && spec.missingProgram === \"result\") {\n resolve(notFound(spec.program));\n } else {\n reject(error);\n }\n });\n });\n child.on(\"close\", (code, signal) => {\n // A stop in progress settles the call itself, with the reason that began it.\n if (stopping !== undefined) return;\n // A failure while building the result must reject, not leave the promise pending.\n done(() => {\n try {\n resolve({ ...this.exit(code, signal), ...output() });\n } catch (error) {\n reject(error);\n }\n });\n });\n // A process that exits before it reads its input closes the pipe, which is no error of ours.\n child.stdin.on(\"error\", () => {});\n child.stdin.end(spec.input);\n });\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"process.js","sourceRoot":"","sources":["../../src/sandbox/process.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,uBAAuB,EAAE,MAAM,aAAa,CAAC;AAGtD,gEAAgE;AAChE,MAAM,iBAAiB,GAAG,GAAG,CAAC;AAC9B,2DAA2D;AAC3D,MAAM,mBAAmB,GAAG,GAAG,CAAC;AAChC,kFAAkF;AAClF,MAAM,gBAAgB,GAAG,GAAG,CAAC;AAC7B,MAAM,wBAAwB,GAAG,CAAC,GAAG,IAAI,GAAG,IAAI,CAAC;AACjD,+DAA+D;AAC/D,MAAM,YAAY,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;AACjC,0DAA0D;AAC1D,MAAM,gBAAgB,GAAG,MAAM,CAAC;AAWhC,iGAAiG;AACjG,MAAM,UAAU,WAAW,CAAC,OAAe;IACzC,IAAI,OAAO,OAAO,KAAK,WAAW,IAAI,OAAO,OAAO,CAAC,gBAAgB,KAAK,UAAU,EAAE,CAAC;QACrF,MAAM,IAAI,uBAAuB,CAC/B,OAAO,EACP,yEAAyE,CAC1E,CAAC;IACJ,CAAC;IACD,OAAO;QACL,EAAE,EAAE,OAAO,CAAC,gBAAgB,CAAC,oBAAoB,CAAC;QAClD,EAAE,EAAE,OAAO,CAAC,gBAAgB,CAAC,kBAAkB,CAAC;QAChD,EAAE,EAAE,OAAO,CAAC,gBAAgB,CAAC,SAAS,CAAC;QACvC,IAAI,EAAE,OAAO,CAAC,gBAAgB,CAAC,WAAW,CAAC;QAC3C,GAAG,E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Q,EAAE,IAAI,EAAE,GAAG,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,EAChG,OAAO,CAAC,SAAS,CAClB,CAAC;YACJ,CAAC;YACD,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,CAAC,KAA4B,EAAE,EAAE;gBACjD,IAAI,CAAC,GAAG,EAAE;oBACR,IAAI,KAAK,CAAC,IAAI,KAAK,QAAQ,IAAI,IAAI,CAAC,cAAc,KAAK,QAAQ,EAAE,CAAC;wBAChE,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC;oBAClC,CAAC;yBAAM,CAAC;wBACN,MAAM,CAAC,KAAK,CAAC,CAAC;oBAChB,CAAC;gBACH,CAAC,CAAC,CAAC;YACL,CAAC,CAAC,CAAC;YACH,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE;gBACjC,6EAA6E;gBAC7E,IAAI,QAAQ,KAAK,SAAS;oBAAE,OAAO;gBACnC,kFAAkF;gBAClF,IAAI,CAAC,GAAG,EAAE;oBACR,IAAI,CAAC;wBACH,OAAO,CAAC,EAAE,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,MAAM,CAAC,EAAE,GAAG,MAAM,EAAE,EAAE,CAAC,CAAC;oBACvD,CAAC;oBAAC,OAAO,KAAK,EAAE,CAAC;wBACf,MAAM,CAAC,KAAK,CAAC,CAAC;oBAChB,CAAC;gBACH,CAAC,CAAC,CAAC;YACL,CAAC,CAAC,CAAC;YACH,6FAA6F;YAC7F,KAAK,CAAC,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;YAClC,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QAC9B,CAAC,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["/**\n * The process handling that the Node-only sandbox backends share: checking a command's options, running it in its own\n * process group, capping its output, and ending the whole tree on a timeout, an abort or a dispose. It loads Node's\n * modules by `process.getBuiltinModule()` when it is used, so importing it costs a portable bundle nothing.\n */\nimport { HarnessError } from \"../errors.js\";\nimport { SandboxUnavailableError } from \"./errors.js\";\nimport type { ExecOptions, ExecResult } from \"./types.js\";\n\n// The exit code GNU `timeout` uses, which callers already know.\nconst TIMEOUT_EXIT_CODE = 124;\n// The exit code a shell gives for a program it can't find.\nconst NOT_FOUND_EXIT_CODE = 127;\n// A shell reports a command that a signal killed as 128 plus the signal's number.\nconst SIGNAL_EXIT_BASE = 128;\nconst DEFAULT_MAX_OUTPUT_BYTES = 8 * 1024 * 1024;\n// The longest delay a timer takes: a larger one fires at once.\nconst MAX_TIMER_MS = 2 ** 31 - 1;\n// The longest a stop waits for a backend's `onStop` hook.\nconst STOP_HOOK_MAX_MS = 15_000;\n\n/** The Node modules the backends use. */\nexport type NodeModules = {\n readonly cp: typeof import(\"node:child_process\");\n readonly fs: typeof import(\"node:fs/promises\");\n readonly os: typeof import(\"node:os\");\n readonly path: typeof import(\"node:path\");\n readonly url: typeof import(\"node:url\");\n};\n\n/** Node's modules, or a `SandboxUnavailableError` for `backend` on a runtime that lacks them. */\nexport function nodeModules(backend: string): NodeModules {\n if (typeof process === \"undefined\" || typeof process.getBuiltinModule !== \"function\") {\n throw new SandboxUnavailableError(\n backend,\n \"it runs commands through Node's child_process, which this runtime lacks\",\n );\n }\n return {\n cp: process.getBuiltinModule(\"node:child_process\"),\n fs: process.getBuiltinModule(\"node:fs/promises\"),\n os: process.getBuiltinModule(\"node:os\"),\n path: process.getBuiltinModule(\"node:path\"),\n url: process.getBuiltinModule(\"node:url\"),\n };\n}\n\n/** The length to keep of cut output, backing up over a UTF-8 character that the cut split. */\nfunction whole(chunks: readonly Uint8Array[], size: number): number {\n const last = chunks[chunks.length - 1];\n if (last === undefined) return 0;\n // Find the lead byte of the last character within the final three bytes, and drop it if its character is incomplete.\n for (let back = 1; back <= Math.min(3, last.length); back += 1) {\n const byte = last[last.length - back] as number;\n if ((byte & 0xc0) === 0x80) continue;\n const need = byte >= 0xf0 ? 4 : byte >= 0xe0 ? 3 : byte >= 0xc0 ? 2 : 1;\n return need > back ? size - back : size;\n }\n return size;\n}\n\n/** Throws unless the options are usable. */\nexport function checkOptions(options: ExecOptions): void {\n const { maxOutputBytes, timeoutMs } = options;\n if (maxOutputBytes !== undefined && !(Number.isInteger(maxOutputBytes) && maxOutputBytes >= 0)) {\n throw new HarnessError(\"invalid_sandbox_options\", \"maxOutputBytes must be a non-negative whole number\");\n }\n if (timeoutMs !== undefined && !(Number.isFinite(timeoutMs) && timeoutMs > 0 && timeoutMs <= MAX_TIMER_MS)) {\n throw new HarnessError(\"invalid_sandbox_options\", `timeoutMs must be a number from 1 to ${MAX_TIMER_MS}`);\n }\n}\n\n/** Throws unless the command is a non-empty list of strings. */\nexport function checkCommand(command: readonly string[]): void {\n if (!Array.isArray(command) || command.length === 0 || command.some((part) => typeof part !== \"string\")) {\n throw new HarnessError(\"invalid_sandbox_options\", \"a sandbox command is a non-empty list of strings\");\n }\n}\n\n/** Keeps the first `limit` bytes of a stream and drops the rest, but keeps reading so the child never blocks. */\nfunction capture(stream: NodeJS.ReadableStream, limit: number) {\n const chunks: Uint8Array[] = [];\n let size = 0;\n let truncated = false;\n stream.on(\"data\", (chunk: Uint8Array) => {\n const room = limit - size;\n if (chunk.length <= room) {\n chunks.push(chunk);\n size += chunk.length;\n } else {\n if (room > 0) chunks.push(chunk.subarray(0, room));\n size = limit;\n truncated = true;\n }\n });\n const joined = (): Uint8Array => {\n const all = new Uint8Array(size);\n let at = 0;\n for (const chunk of chunks) {\n all.set(chunk, at);\n at += chunk.length;\n }\n return all;\n };\n return {\n get truncated() {\n return truncated;\n },\n bytes: joined,\n text(): string {\n const all = joined();\n return new TextDecoder().decode(truncated ? all.subarray(0, whole(chunks, size)) : all);\n },\n };\n}\n\ntype Capture = ReturnType<typeof capture>;\n\n/** A process's captured output as the fields of a result, with `note` added to the end of standard error. */\nfunction outputOf(out: Capture, err: Capture, note: string) {\n return {\n stdout: out.text(),\n stdoutBytes: out.bytes(),\n stderr: `${err.text()}${note}`,\n ...(out.truncated || err.truncated ? { truncated: true } : {}),\n };\n}\n\n/** The result for a program that can't be started, as a shell reports it. */\nfunction notFound(program: string) {\n return {\n exitCode: NOT_FOUND_EXIT_CODE,\n stdout: \"\",\n stdoutBytes: new Uint8Array(),\n stderr: `command not found: ${program}\\n`,\n };\n}\n\n/** What one process is started with. */\nexport interface ProcessSpec {\n readonly program: string;\n readonly args: readonly string[];\n readonly cwd: string;\n readonly env: Readonly<Record<string, string>>;\n /** Bytes to write to the process's standard input before closing it. Without it, standard input is closed at once. */\n readonly input?: Uint8Array;\n /** Whether a program that can't be started is a result with exit code 127, as a shell gives, or a rejection. */\n readonly missingProgram: \"result\" | \"reject\";\n /**\n * How long a stopped process's group has to exit after a `SIGTERM`, which lets a program clean up, before a `SIGKILL`\n * ends what is left. Without it the group is killed at once.\n */\n readonly graceMs?: number;\n /**\n * Runs, and is awaited, when a timeout, an abort or `stopAll()` ends the process, before its group is killed. A\n * backend whose commands run outside the process's group, such as in a container, ends them here.\n */\n readonly onStop?: () => Promise<void>;\n}\n\n/** A finished process: the `ExecResult` fields, and the raw bytes of standard output. */\nexport type ProcessResult = Extract<ExecResult, { exitCode: number }> & { readonly stdoutBytes: Uint8Array };\n\n/** Runs processes, each in its own group, and ends them all on `stopAll()`. */\nexport class ProcessRunner {\n private readonly modules: NodeModules;\n // What stops each process still running, so `stopAll()` can end them.\n private readonly running = new Set<() => Promise<void>>();\n\n constructor(modules: NodeModules) {\n this.modules = modules;\n }\n\n /** Kills the process's whole group, or just the process where the platform has no groups. */\n private kill(child: import(\"node:child_process\").ChildProcess): void {\n const pid = child.pid;\n if (pid === undefined) return;\n try {\n if (process.platform === \"win32\") child.kill(\"SIGKILL\");\n else process.kill(-pid, \"SIGKILL\");\n } catch {\n // The group is already gone, so there is nothing left to kill.\n }\n }\n\n /** The exit code, and the signal's name when a signal killed the process. */\n private exit(code: number | null, signal: NodeJS.Signals | null): { exitCode: number; signal?: string } {\n if (signal === null) return { exitCode: code ?? 1 };\n return { exitCode: SIGNAL_EXIT_BASE + (this.modules.os.constants.signals[signal] ?? 0), signal };\n }\n\n /** Ends every process still running, each one's promise rejecting with `sandbox_disposed`, and waits until they have. */\n async stopAll(): Promise<void> {\n await Promise.all([...this.running].map((stop) => stop()));\n }\n\n /** Ends the process's group: at once, or with a `SIGTERM` first and a `SIGKILL` after `graceMs` for what is left. */\n private async end(\n child: import(\"node:child_process\").ChildProcess,\n graceMs: number,\n onStop?: () => Promise<void>,\n ): Promise<void> {\n // Runs beside the kill, and is waited for only so long, so a hook that hangs can't hold the call.\n const hook = onStop?.().catch(() => {});\n const running = child.exitCode === null && child.signalCode === null;\n if (graceMs > 0 && process.platform !== \"win32\" && child.pid !== undefined && running) {\n const exited = new Promise<void>((resolve) => child.once(\"exit\", () => resolve()));\n let timer: ReturnType<typeof setTimeout> | undefined;\n const expired = new Promise<void>((resolve) => {\n timer = setTimeout(resolve, graceMs);\n });\n try {\n process.kill(-child.pid, \"SIGTERM\");\n } catch {\n // The group is already gone.\n }\n await Promise.race([exited, expired]);\n clearTimeout(timer);\n }\n this.kill(child);\n if (hook !== undefined)\n await Promise.race([hook, new Promise<void>((resolve) => setTimeout(resolve, STOP_HOOK_MAX_MS).unref())]);\n }\n\n /**\n * Runs the process and resolves when it exits, its signal aborts it, its timeout passes (exit code 124) or `stopAll()`\n * runs. An abort rejects with the signal's reason, and `stopAll()` with `sandbox_disposed`.\n */\n run(spec: ProcessSpec, options: ExecOptions): Promise<ProcessResult> {\n const limit = options.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;\n return new Promise((resolve, reject) => {\n const child = this.modules.cp.spawn(spec.program, [...spec.args], {\n cwd: spec.cwd,\n env: { ...spec.env },\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n detached: true,\n });\n const out = capture(child.stdout, limit);\n const err = capture(child.stderr, limit);\n const output = (note = \"\") => outputOf(out, err, note);\n let settled = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const done = (settle: () => void) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n options.signal.removeEventListener(\"abort\", onAbort);\n this.running.delete(onDispose);\n settle();\n };\n // Ends the whole tree and stops waiting for the pipes, which a surviving grandchild would hold open.\n let stopping: Promise<void> | undefined;\n const stop = (settle: () => void): Promise<void> => {\n if (stopping !== undefined || settled) return stopping ?? Promise.resolve();\n stopping = this.end(child, spec.graceMs ?? 0, spec.onStop).then(() => {\n child.stdout.destroy();\n child.stderr.destroy();\n done(settle);\n });\n return stopping;\n };\n const onAbort = () => void stop(() => reject(options.signal.reason));\n const onDispose = () => stop(() => reject(new HarnessError(\"sandbox_disposed\", \"the sandbox was disposed\")));\n options.signal.addEventListener(\"abort\", onAbort, { once: true });\n this.running.add(onDispose);\n if (options.timeoutMs !== undefined) {\n const note = `timed out after ${options.timeoutMs} ms\\n`;\n timer = setTimeout(\n () => void stop(() => resolve({ exitCode: TIMEOUT_EXIT_CODE, timedOut: true, ...output(note) })),\n options.timeoutMs,\n );\n }\n child.on(\"error\", (error: NodeJS.ErrnoException) => {\n done(() => {\n if (error.code === \"ENOENT\" && spec.missingProgram === \"result\") {\n resolve(notFound(spec.program));\n } else {\n reject(error);\n }\n });\n });\n child.on(\"close\", (code, signal) => {\n // A stop in progress settles the call itself, with the reason that began it.\n if (stopping !== undefined) return;\n // A failure while building the result must reject, not leave the promise pending.\n done(() => {\n try {\n resolve({ ...this.exit(code, signal), ...output() });\n } catch (error) {\n reject(error);\n }\n });\n });\n // A process that exits before it reads its input closes the pipe, which is no error of ours.\n child.stdin.on(\"error\", () => {});\n child.stdin.end(spec.input);\n });\n }\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { SandboxClient } from "../types.js";
|
|
2
|
-
export type { SrtPathEntry, SrtSettings, SrtSettingsInput } from "./settings.js";
|
|
3
|
-
export { srtSettings } from "./settings.js";
|
|
2
|
+
export type { SrtPathEntry, SrtPolicyNames, SrtSettings, SrtSettingsInput } from "./settings.js";
|
|
3
|
+
export { srtPolicyFromSettings, srtSettings } from "./settings.js";
|
|
4
4
|
/** The options of `srtSandbox()`. */
|
|
5
5
|
export interface SrtSandboxOptions {
|
|
6
6
|
/**
|
|
@@ -31,5 +31,8 @@ export declare const SRT_ADDED_ENVIRONMENT: readonly string[];
|
|
|
31
31
|
* command that does nothing, so a host that can't confine a process throws `SandboxUnavailableError` and runs nothing.
|
|
32
32
|
* The policy's roots, `extraReadRoots` and `denyWrite` must be absolute folders other than `/`. Each command runs under
|
|
33
33
|
* its own `srt`, so a command sees the proxy variables `srt` adds to its environment, besides those it was given.
|
|
34
|
+
* Before it returns, `provision()` reads the settings file back from disk and throws `SandboxPolicyMismatchError` when
|
|
35
|
+
* the policy it applies differs from the one requested. The backend lists no capability: it can't resume, snapshot or
|
|
36
|
+
* pause.
|
|
34
37
|
*/
|
|
35
38
|
export declare function srtSandbox(options?: SrtSandboxOptions): SandboxClient;
|
|
@@ -13,10 +13,10 @@
|
|
|
13
13
|
import { HarnessError } from "../../errors.js";
|
|
14
14
|
import { BackendSandbox } from "../base.js";
|
|
15
15
|
import { SandboxUnavailableError } from "../errors.js";
|
|
16
|
-
import { absolutePath, checkPaths, existing, findOnPath, HostFiles, isProtectedPath, realOrSelf, workspaceRoot, } from "../host-files.js";
|
|
16
|
+
import { absolutePath, checkPaths, existing, findOnPath, HostFiles, isProtectedPath, realOrSelf, spellings, workspaceRoot, } from "../host-files.js";
|
|
17
17
|
import { nodeModules, ProcessRunner } from "../process.js";
|
|
18
|
-
import { srtSettings } from "./settings.js";
|
|
19
|
-
export { srtSettings } from "./settings.js";
|
|
18
|
+
import { srtPolicyFromSettings, srtSettings } from "./settings.js";
|
|
19
|
+
export { srtPolicyFromSettings, srtSettings } from "./settings.js";
|
|
20
20
|
/** The system folders a program needs to start. Each one that exists is readable, and nothing else outside the roots. */
|
|
21
21
|
export const SRT_SYSTEM_READ_ROOTS = [
|
|
22
22
|
"/usr",
|
|
@@ -162,6 +162,12 @@ class SrtSandbox extends BackendSandbox {
|
|
|
162
162
|
const { stdoutBytes: _bytes, ...result } = await this.runUnderSrt(command, prepared.cwd, options.env, options);
|
|
163
163
|
return result;
|
|
164
164
|
}
|
|
165
|
+
/** Reads the settings file `srt` is started with, as it is on disk now, and maps it back to a policy. */
|
|
166
|
+
async readBack() {
|
|
167
|
+
this.live();
|
|
168
|
+
const text = await this.state.modules.fs.readFile(this.state.settingsFile, "utf8");
|
|
169
|
+
return srtPolicyFromSettings(JSON.parse(text), this.state.names);
|
|
170
|
+
}
|
|
165
171
|
async shutDown() {
|
|
166
172
|
await this.runner.stopAll();
|
|
167
173
|
await this.state.modules.fs.rm(this.state.folder, { recursive: true, force: true });
|
|
@@ -181,24 +187,34 @@ async function planSandbox(modules, policy, options, command, runFolder) {
|
|
|
181
187
|
real(options.denyWrite ?? []),
|
|
182
188
|
real(command.readRoots),
|
|
183
189
|
]);
|
|
190
|
+
const systemReadRoots = await existing(modules, await real(SRT_SYSTEM_READ_ROOTS));
|
|
191
|
+
// Only the run folder: the settings file beside it holds a proxy address that a command must not read.
|
|
192
|
+
const helperReadRoots = [runFolder, ...helpers, ...extra];
|
|
184
193
|
const input = {
|
|
185
194
|
policy: { ...policy, readRoots, writeRoots },
|
|
186
|
-
systemReadRoots
|
|
187
|
-
|
|
188
|
-
helperReadRoots: [runFolder, ...helpers, ...extra],
|
|
195
|
+
systemReadRoots,
|
|
196
|
+
helperReadRoots,
|
|
189
197
|
denyWrite,
|
|
190
198
|
...(options.parentProxy === undefined ? {} : { parentProxy: options.parentProxy }),
|
|
191
199
|
};
|
|
192
|
-
|
|
200
|
+
const names = {
|
|
201
|
+
read: spellings(readRoots, policy.readRoots),
|
|
202
|
+
write: spellings(writeRoots, policy.writeRoots),
|
|
203
|
+
implicitReads: [...systemReadRoots, ...helperReadRoots],
|
|
204
|
+
};
|
|
205
|
+
return { settings: srtSettings(input), roots: { read: readRoots, write: writeRoots, denyWrite }, names };
|
|
193
206
|
}
|
|
194
207
|
/**
|
|
195
208
|
* Builds the `srt` backend. `provision()` checks the platform, the programs `srt` needs and `srt` itself, by running a
|
|
196
209
|
* command that does nothing, so a host that can't confine a process throws `SandboxUnavailableError` and runs nothing.
|
|
197
210
|
* The policy's roots, `extraReadRoots` and `denyWrite` must be absolute folders other than `/`. Each command runs under
|
|
198
211
|
* its own `srt`, so a command sees the proxy variables `srt` adds to its environment, besides those it was given.
|
|
212
|
+
* Before it returns, `provision()` reads the settings file back from disk and throws `SandboxPolicyMismatchError` when
|
|
213
|
+
* the policy it applies differs from the one requested. The backend lists no capability: it can't resume, snapshot or
|
|
214
|
+
* pause.
|
|
199
215
|
*/
|
|
200
216
|
export function srtSandbox(options = {}) {
|
|
201
|
-
|
|
217
|
+
const client = {
|
|
202
218
|
tier: "os",
|
|
203
219
|
stops: ["mistakes", "exfiltration"],
|
|
204
220
|
async provision(manifest, policy) {
|
|
@@ -227,8 +243,10 @@ export function srtSandbox(options = {}) {
|
|
|
227
243
|
runFolder,
|
|
228
244
|
settingsFile,
|
|
229
245
|
hostPath,
|
|
246
|
+
names: plan.names,
|
|
230
247
|
});
|
|
231
248
|
await probe(modules, sandbox, root);
|
|
249
|
+
await sandbox.confirm(client, policy);
|
|
232
250
|
const encoder = new TextEncoder();
|
|
233
251
|
for (const [path, data] of Object.entries(manifest.files ?? {})) {
|
|
234
252
|
await sandbox.writeFile(path, typeof data === "string" ? encoder.encode(data) : data);
|
|
@@ -241,6 +259,7 @@ export function srtSandbox(options = {}) {
|
|
|
241
259
|
}
|
|
242
260
|
},
|
|
243
261
|
};
|
|
262
|
+
return client;
|
|
244
263
|
}
|
|
245
264
|
/** Starts `srt` once with a command that does nothing, and throws `SandboxUnavailableError` when it can't. */
|
|
246
265
|
async function probe(modules, sandbox, root) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/sandbox/srt/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAC/C,OAAO,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAC5C,OAAO,EAAE,uBAAuB,EAAE,MAAM,cAAc,CAAC;AACvD,OAAO,EACL,YAAY,EACZ,UAAU,EACV,QAAQ,EACR,UAAU,EACV,SAAS,EACT,eAAe,EACf,UAAU,EACV,aAAa,GACd,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAoB,WAAW,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAE7E,OAAO,EAAyB,WAAW,EAAE,MAAM,eAAe,CAAC;AAGnE,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAkB5C,yHAAyH;AACzH,MAAM,CAAC,MAAM,qBAAqB,GAAsB;IACtD,MAAM;IACN,MAAM;IACN,OAAO;IACP,MAAM;IACN,QAAQ;IACR,QAAQ;IACR,SAAS;IACT,MAAM;CACP,CAAC;AAEF;;;GAGG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAsB;IACtD,WAAW;IACX,kCAAkC;IAClC,mCAAmC;IACnC,wBAAwB;IACxB,yBAAyB;IACzB,qBAAqB;IACrB,qBAAqB;IACrB,yBAAyB;IACzB,oBAAoB;IACpB,mBAAmB;IACnB,WAAW;IACX,uBAAuB;IACvB,iBAAiB;IACjB,YAAY;IACZ,aAAa;IACb,YAAY;IACZ,mBAAmB;IACnB,UAAU;IACV,aAAa;IACb,iBAAiB;IACjB,WAAW;IACX,WAAW;IACX,YAAY;IACZ,YAAY;IACZ,aAAa;IACb,UAAU;CACX,CAAC;AAEF,sEAAsE;AACtE,MAAM,iBAAiB,GAAG,CAAC,OAAO,EAAE,OAAO,CAAU,CAAC;AACtD,MAAM,gBAAgB,GAAG,MAAM,CAAC;AAChC,+FAA+F;AAC/F,MAAM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C,MAAM,MAAM,GAAG,MAAM,MAAM;SACxB,GAAG,CACF;QACE,OAAO,EAAE,OAAO,CAAC,OAAO;QACxB,IAAI,EAAE,OAAO,CAAC,YAAY,CAAC,CAAC,eAAe,CAAC,CAAC;QAC7C,GAAG,EAAE,IAAI;QACT,GAAG,EAAE,OAAO,CAAC,iBAAiB,EAAE;QAChC,cAAc,EAAE,QAAQ;QACxB,OAAO,EAAE,QAAQ;KAClB,EACD,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,EAAE,IAAI,eAAe,EAAE,CAAC,MAAM,EAAE,SAAS,EAAE,gBAAgB,EAAE,CAC/E;SACA,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;QACxB,MAAM,IAAI,uBAAuB,CAAC,KAAK,EAAE,yBAAyB,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;IACxF,CAAC,CAAC,CAAC;IACL,IAAI,MAAM,CAAC,QAAQ,KAAK,CAAC,EAAE,CAAC;QAC1B,MAAM,IAAI,uBAAuB,CAAC,KAAK,EAAE,+BAA+B,SAAS,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;IACtG,CAAC;AACH,CAAC","sourcesContent":["/**\n * `@buildanagent/harness/sandbox/srt`: the OS-tier backend. It runs each command under Anthropic's `srt` sandbox\n * runtime, which uses bubblewrap on Linux and starts a proxy that allows only the policy's hosts. It claims to stop\n * `mistakes` and `exfiltration`, never a `hostile_process`: the kernel is shared with the host, and `srt` is a\n * pre-1.0 beta (as of November 2026). Only Linux is supported, because it is the only platform this backend is tested\n * on. A backend that can't start throws `SandboxUnavailableError` and runs nothing. It is Node-only.\n *\n * The file calls run in the host, not under `srt`: two `srt` processes in one workspace can disturb each other, because\n * each makes and removes empty files there. A path outside the roots is refused by its real path, so a symlink that\n * leads out is refused too, and the opened file is checked again through `/proc`, so a path swapped for a link in\n * between is caught. A hostile process could still win that race, which is why no `hostile_process` stop is claimed.\n */\nimport { HarnessError } from \"../../errors.js\";\nimport { BackendSandbox } from \"../base.js\";\nimport { SandboxUnavailableError } from \"../errors.js\";\nimport {\n absolutePath,\n checkPaths,\n existing,\n findOnPath,\n HostFiles,\n isProtectedPath,\n realOrSelf,\n workspaceRoot,\n} from \"../host-files.js\";\nimport { type NodeModules, nodeModules, ProcessRunner } from \"../process.js\";\nimport type { ExecOptions, ExecResult, Sandbox, SandboxClient, SandboxPolicy, WorkspaceManifest } from \"../types.js\";\nimport { type SrtSettingsInput, srtSettings } from \"./settings.js\";\n\nexport type { SrtPathEntry, SrtSettings, SrtSettingsInput } from \"./settings.js\";\nexport { srtSettings } from \"./settings.js\";\n\n/** The options of `srtSandbox()`. */\nexport interface SrtSandboxOptions {\n /**\n * The `srt` executable. Without it the backend runs the `srt` that the installed `@anthropic-ai/sandbox-runtime`\n * package ships, with this process's Node. A binary from elsewhere must have its own install folder in\n * `extraReadRoots`, because `srt` reads its helper program from there inside the sandbox.\n */\n readonly binary?: string;\n /** Folders to read besides the policy's roots and the system's, such as the folder a toolchain is installed in. */\n readonly extraReadRoots?: readonly string[];\n /** Folders that stay read-only even inside a write root, such as the session's own log folder. */\n readonly denyWrite?: readonly string[];\n /** An upstream HTTP proxy that the allowed traffic goes through, for a host that sits behind one. */\n readonly parentProxy?: { readonly http?: string; readonly https?: string };\n}\n\n/** The system folders a program needs to start. Each one that exists is readable, and nothing else outside the roots. */\nexport const SRT_SYSTEM_READ_ROOTS: readonly string[] = [\n \"/usr\",\n \"/bin\",\n \"/sbin\",\n \"/lib\",\n \"/lib32\",\n \"/lib64\",\n \"/libx32\",\n \"/etc\",\n];\n\n/**\n * The variables `srt` 0.0.83 adds to a command's environment, which are its proxy settings and the few that go with\n * them. A command sees these besides the variables it was given, so a test that compares environments lists them.\n */\nexport const SRT_ADDED_ENVIRONMENT: readonly string[] = [\n \"ALL_PROXY\",\n \"CLAUDE_CODE_HOST_HTTP_PROXY_PORT\",\n \"CLAUDE_CODE_HOST_SOCKS_PROXY_PORT\",\n \"CLOUDSDK_PROXY_ADDRESS\",\n \"CLOUDSDK_PROXY_PASSWORD\",\n \"CLOUDSDK_PROXY_PORT\",\n \"CLOUDSDK_PROXY_TYPE\",\n \"CLOUDSDK_PROXY_USERNAME\",\n \"DOCKER_HTTPS_PROXY\",\n \"DOCKER_HTTP_PROXY\",\n \"FTP_PROXY\",\n \"GIT_CONFIG_PARAMETERS\",\n \"GIT_SSH_COMMAND\",\n \"GRPC_PROXY\",\n \"HTTPS_PROXY\",\n \"HTTP_PROXY\",\n \"JAVA_TOOL_OPTIONS\",\n \"NO_PROXY\",\n \"RSYNC_PROXY\",\n \"SANDBOX_RUNTIME\",\n \"all_proxy\",\n \"ftp_proxy\",\n \"grpc_proxy\",\n \"http_proxy\",\n \"https_proxy\",\n \"no_proxy\",\n];\n\n/** The programs `srt` runs on Linux, which it finds on the `PATH`. */\nconst REQUIRED_PROGRAMS = [\"bwrap\", \"socat\"] as const;\nconst PROBE_TIMEOUT_MS = 20_000;\n// How long `srt` has to clean up after a `SIGTERM` before the command's whole group is killed.\nconst GRACE_MS = 2000;\n\n/** The program and leading arguments that start `srt`. */\ninterface SrtCommand {\n readonly program: string;\n readonly args: readonly string[];\n /** The folders `srt` reads inside the sandbox, as absolute paths. */\n readonly readRoots: readonly string[];\n}\n\n/** How to start `srt`, or a `SandboxUnavailableError` when there is nothing to start. */\nasync function srtCommand(modules: NodeModules, binary: string | undefined): Promise<SrtCommand> {\n if (binary !== undefined) {\n // Resolved once against this process's folder, because it is started from the workspace.\n const program = modules.path.resolve(binary);\n try {\n await modules.fs.access(program, modules.fs.constants.X_OK);\n } catch (error) {\n throw new SandboxUnavailableError(\"srt\", `${binary} is not an executable file`, { cause: error });\n }\n return { program, args: [], readRoots: [] };\n }\n let cli: string;\n try {\n const url = import.meta.resolve(\"@anthropic-ai/sandbox-runtime/dist/cli.js\");\n cli = await modules.fs.realpath(modules.url.fileURLToPath(url));\n } catch (error) {\n throw new SandboxUnavailableError(\"srt\", \"the @anthropic-ai/sandbox-runtime package is not installed\", {\n cause: error,\n });\n }\n // `srt` runs its seccomp helper from the package's own folder, inside the sandbox.\n return { program: process.execPath, args: [cli], readRoots: [modules.path.resolve(cli, \"..\", \"..\", \"vendor\")] };\n}\n\n/** A `SandboxUnavailableError` unless this platform and host can run `srt`, looking for its programs on `hostPath`. */\nasync function checkHost(modules: NodeModules, hostPath: string): Promise<void> {\n if (process.platform !== \"linux\") {\n throw new SandboxUnavailableError(\n \"srt\",\n `only Linux is supported, because it is the only platform this backend is tested on, and this is ${process.platform}`,\n );\n }\n for (const program of REQUIRED_PROGRAMS) {\n if ((await findOnPath(modules, hostPath, program)) === undefined) {\n throw new SandboxUnavailableError(\"srt\", `${program} is not on the PATH, and srt needs it on Linux`);\n }\n }\n}\n\n// A variable name that `env` can set, which is every name a process can be given.\nconst VARIABLE_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n/** Everything a provisioned sandbox holds. */\ninterface SrtSandboxState {\n readonly modules: NodeModules;\n readonly command: SrtCommand;\n readonly root: string;\n readonly files: HostFiles;\n /** A private folder that holds the settings file and the run folder, and is removed on dispose. */\n readonly folder: string;\n /** The folder `srt` makes its proxy sockets in, and the only part of `folder` a command may read. */\n readonly runFolder: string;\n readonly settingsFile: string;\n /** The `PATH` that `srt` itself runs with, which finds `bwrap` and `socat`. */\n readonly hostPath: string;\n}\n\nclass SrtSandbox extends BackendSandbox {\n private readonly runner: ProcessRunner;\n private readonly state: SrtSandboxState;\n\n constructor(state: SrtSandboxState) {\n super(state);\n this.state = state;\n this.runner = new ProcessRunner(state.modules);\n }\n\n /** The program that starts `srt`. */\n get program(): string {\n return this.state.command.program;\n }\n\n /** The arguments that start `srt` with this sandbox's settings, then run `inner`. */\n srtArguments(inner: readonly string[]): string[] {\n return [...this.state.command.args, \"--settings\", this.state.settingsFile, \"--\", ...inner];\n }\n\n /** The environment `srt` itself runs with: where to find its programs, and where to make its sockets. Nothing else. */\n launchEnvironment(): Record<string, string> {\n return { PATH: this.state.hostPath, TMPDIR: this.state.runFolder };\n }\n\n /**\n * The command that runs inside `srt`. `env` sets the command's whole environment from `srt`'s own, so a variable that\n * makes a program load code, such as `NODE_OPTIONS`, never reaches `srt` or the programs it starts outside the\n * sandbox. The `--` ends `env`'s options, so a first word that starts with `-` is a program name.\n */\n private innerCommand(command: readonly string[], env: Readonly<Record<string, string>>): string[] {\n const unset: string[] = [];\n for (const name of [\"PATH\", \"TMPDIR\"]) {\n if (!(name in env)) unset.push(\"-u\", name);\n }\n const assignments: string[] = [];\n for (const [name, value] of Object.entries(env)) {\n if (!VARIABLE_NAME.test(name)) {\n throw new HarnessError(\"invalid_sandbox_options\", `${JSON.stringify(name)} is not a variable name`);\n }\n assignments.push(`${name}=${value}`);\n }\n return [\"/usr/bin/env\", ...unset, \"--\", ...assignments, ...command];\n }\n\n /** Runs `command` under `srt` in `cwd`, with `env` as its whole environment. */\n private runUnderSrt(\n command: readonly string[],\n cwd: string,\n env: Readonly<Record<string, string>>,\n options: ExecOptions,\n ) {\n return this.runner.run(\n {\n program: this.state.command.program,\n args: this.srtArguments(this.innerCommand(command, env)),\n cwd,\n env: this.launchEnvironment(),\n missingProgram: \"reject\",\n graceMs: GRACE_MS,\n },\n options,\n );\n }\n\n async exec(command: readonly string[], options: ExecOptions): Promise<ExecResult> {\n const prepared = await this.prepare(command, options);\n if (!(\"cwd\" in prepared)) return prepared;\n const { stdoutBytes: _bytes, ...result } = await this.runUnderSrt(command, prepared.cwd, options.env, options);\n return result;\n }\n\n protected async shutDown(): Promise<void> {\n await this.runner.stopAll();\n await this.state.modules.fs.rm(this.state.folder, { recursive: true, force: true });\n }\n}\n\n/** The first line of what `srt` printed, for the message of a failed start. */\nfunction firstLine(text: string): string {\n return text.trim().split(\"\\n\")[0] ?? \"no output\";\n}\n\n/** The settings and the real roots for one sandbox, with every path's symlinks resolved. */\nasync function planSandbox(\n modules: NodeModules,\n policy: SandboxPolicy,\n options: SrtSandboxOptions,\n command: SrtCommand,\n runFolder: string,\n) {\n const real = (paths: readonly string[]) => Promise.all(paths.map((path) => realOrSelf(modules, path)));\n const [readRoots, writeRoots, extra, denyWrite, helpers] = await Promise.all([\n real(policy.readRoots),\n real(policy.writeRoots),\n real(options.extraReadRoots ?? []),\n real(options.denyWrite ?? []),\n real(command.readRoots),\n ]);\n const input: SrtSettingsInput = {\n policy: { ...policy, readRoots, writeRoots },\n systemReadRoots: await existing(modules, await real(SRT_SYSTEM_READ_ROOTS)),\n // Only the run folder: the settings file beside it holds a proxy address that a command must not read.\n helperReadRoots: [runFolder, ...helpers, ...extra],\n denyWrite,\n ...(options.parentProxy === undefined ? {} : { parentProxy: options.parentProxy }),\n };\n return { settings: srtSettings(input), roots: { read: readRoots, write: writeRoots, denyWrite } };\n}\n\n/**\n * Builds the `srt` backend. `provision()` checks the platform, the programs `srt` needs and `srt` itself, by running a\n * command that does nothing, so a host that can't confine a process throws `SandboxUnavailableError` and runs nothing.\n * The policy's roots, `extraReadRoots` and `denyWrite` must be absolute folders other than `/`. Each command runs under\n * its own `srt`, so a command sees the proxy variables `srt` adds to its environment, besides those it was given.\n */\nexport function srtSandbox(options: SrtSandboxOptions = {}): SandboxClient {\n return {\n tier: \"os\",\n stops: [\"mistakes\", \"exfiltration\"],\n async provision(manifest: WorkspaceManifest, policy: SandboxPolicy): Promise<Sandbox> {\n const modules = nodeModules(\"srt\");\n const hostPath = absolutePath(modules, process.env.PATH);\n await checkHost(modules, hostPath);\n const root = await workspaceRoot(modules, manifest.root);\n checkPaths(modules, [...policy.readRoots, ...policy.writeRoots], \"a sandbox root\");\n checkPaths(modules, options.extraReadRoots ?? [], \"an extra read root\");\n checkPaths(modules, options.denyWrite ?? [], \"a denyWrite folder\");\n const command = await srtCommand(modules, options.binary);\n const folder = await modules.fs.mkdtemp(modules.path.join(modules.os.tmpdir(), \"harness-srt-\"));\n try {\n await modules.fs.chmod(folder, 0o700);\n const runFolder = modules.path.join(folder, \"run\");\n await modules.fs.mkdir(runFolder, { mode: 0o700 });\n const plan = await planSandbox(modules, policy, options, command, runFolder);\n const settingsFile = modules.path.join(folder, \"settings.json\");\n await modules.fs.writeFile(settingsFile, JSON.stringify(plan.settings), { mode: 0o600 });\n const sandbox = new SrtSandbox({\n modules,\n command,\n root,\n files: new HostFiles(modules, root, plan.roots, isProtectedPath),\n folder,\n runFolder,\n settingsFile,\n hostPath,\n });\n await probe(modules, sandbox, root);\n const encoder = new TextEncoder();\n for (const [path, data] of Object.entries(manifest.files ?? {})) {\n await sandbox.writeFile(path, typeof data === \"string\" ? encoder.encode(data) : data);\n }\n return sandbox;\n } catch (error) {\n await modules.fs.rm(folder, { recursive: true, force: true });\n throw error;\n }\n },\n };\n}\n\n/** Starts `srt` once with a command that does nothing, and throws `SandboxUnavailableError` when it can't. */\nasync function probe(modules: NodeModules, sandbox: SrtSandbox, root: string): Promise<void> {\n const runner = new ProcessRunner(modules);\n const result = await runner\n .run(\n {\n program: sandbox.program,\n args: sandbox.srtArguments([\"/usr/bin/true\"]),\n cwd: root,\n env: sandbox.launchEnvironment(),\n missingProgram: \"reject\",\n graceMs: GRACE_MS,\n },\n { env: {}, signal: new AbortController().signal, timeoutMs: PROBE_TIMEOUT_MS },\n )\n .catch((error: unknown) => {\n throw new SandboxUnavailableError(\"srt\", \"it could not be started\", { cause: error });\n });\n if (result.exitCode !== 0) {\n throw new SandboxUnavailableError(\"srt\", `it did not start a command: ${firstLine(result.stderr)}`);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/sandbox/srt/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAC/C,OAAO,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAC5C,OAAO,EAAE,uBAAuB,EAAE,MAAM,cAAc,CAAC;AACvD,OAAO,EACL,YAAY,EACZ,UAAU,EACV,QAAQ,EACR,UAAU,EACV,SAAS,EACT,eAA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AACH,CAAC","sourcesContent":["/**\n * `@buildanagent/harness/sandbox/srt`: the OS-tier backend. It runs each command under Anthropic's `srt` sandbox\n * runtime, which uses bubblewrap on Linux and starts a proxy that allows only the policy's hosts. It claims to stop\n * `mistakes` and `exfiltration`, never a `hostile_process`: the kernel is shared with the host, and `srt` is a\n * pre-1.0 beta (as of November 2026). Only Linux is supported, because it is the only platform this backend is tested\n * on. A backend that can't start throws `SandboxUnavailableError` and runs nothing. It is Node-only.\n *\n * The file calls run in the host, not under `srt`: two `srt` processes in one workspace can disturb each other, because\n * each makes and removes empty files there. A path outside the roots is refused by its real path, so a symlink that\n * leads out is refused too, and the opened file is checked again through `/proc`, so a path swapped for a link in\n * between is caught. A hostile process could still win that race, which is why no `hostile_process` stop is claimed.\n */\nimport { HarnessError } from \"../../errors.js\";\nimport { BackendSandbox } from \"../base.js\";\nimport { SandboxUnavailableError } from \"../errors.js\";\nimport {\n absolutePath,\n checkPaths,\n existing,\n findOnPath,\n HostFiles,\n isProtectedPath,\n realOrSelf,\n spellings,\n workspaceRoot,\n} from \"../host-files.js\";\nimport { type NodeModules, nodeModules, ProcessRunner } from \"../process.js\";\nimport type { ExecOptions, ExecResult, Sandbox, SandboxClient, SandboxPolicy, WorkspaceManifest } from \"../types.js\";\nimport { type SrtPolicyNames, type SrtSettingsInput, srtPolicyFromSettings, srtSettings } from \"./settings.js\";\n\nexport type { SrtPathEntry, SrtPolicyNames, SrtSettings, SrtSettingsInput } from \"./settings.js\";\nexport { srtPolicyFromSettings, srtSettings } from \"./settings.js\";\n\n/** The options of `srtSandbox()`. */\nexport interface SrtSandboxOptions {\n /**\n * The `srt` executable. Without it the backend runs the `srt` that the installed `@anthropic-ai/sandbox-runtime`\n * package ships, with this process's Node. A binary from elsewhere must have its own install folder in\n * `extraReadRoots`, because `srt` reads its helper program from there inside the sandbox.\n */\n readonly binary?: string;\n /** Folders to read besides the policy's roots and the system's, such as the folder a toolchain is installed in. */\n readonly extraReadRoots?: readonly string[];\n /** Folders that stay read-only even inside a write root, such as the session's own log folder. */\n readonly denyWrite?: readonly string[];\n /** An upstream HTTP proxy that the allowed traffic goes through, for a host that sits behind one. */\n readonly parentProxy?: { readonly http?: string; readonly https?: string };\n}\n\n/** The system folders a program needs to start. Each one that exists is readable, and nothing else outside the roots. */\nexport const SRT_SYSTEM_READ_ROOTS: readonly string[] = [\n \"/usr\",\n \"/bin\",\n \"/sbin\",\n \"/lib\",\n \"/lib32\",\n \"/lib64\",\n \"/libx32\",\n \"/etc\",\n];\n\n/**\n * The variables `srt` 0.0.83 adds to a command's environment, which are its proxy settings and the few that go with\n * them. A command sees these besides the variables it was given, so a test that compares environments lists them.\n */\nexport const SRT_ADDED_ENVIRONMENT: readonly string[] = [\n \"ALL_PROXY\",\n \"CLAUDE_CODE_HOST_HTTP_PROXY_PORT\",\n \"CLAUDE_CODE_HOST_SOCKS_PROXY_PORT\",\n \"CLOUDSDK_PROXY_ADDRESS\",\n \"CLOUDSDK_PROXY_PASSWORD\",\n \"CLOUDSDK_PROXY_PORT\",\n \"CLOUDSDK_PROXY_TYPE\",\n \"CLOUDSDK_PROXY_USERNAME\",\n \"DOCKER_HTTPS_PROXY\",\n \"DOCKER_HTTP_PROXY\",\n \"FTP_PROXY\",\n \"GIT_CONFIG_PARAMETERS\",\n \"GIT_SSH_COMMAND\",\n \"GRPC_PROXY\",\n \"HTTPS_PROXY\",\n \"HTTP_PROXY\",\n \"JAVA_TOOL_OPTIONS\",\n \"NO_PROXY\",\n \"RSYNC_PROXY\",\n \"SANDBOX_RUNTIME\",\n \"all_proxy\",\n \"ftp_proxy\",\n \"grpc_proxy\",\n \"http_proxy\",\n \"https_proxy\",\n \"no_proxy\",\n];\n\n/** The programs `srt` runs on Linux, which it finds on the `PATH`. */\nconst REQUIRED_PROGRAMS = [\"bwrap\", \"socat\"] as const;\nconst PROBE_TIMEOUT_MS = 20_000;\n// How long `srt` has to clean up after a `SIGTERM` before the command's whole group is killed.\nconst GRACE_MS = 2000;\n\n/** The program and leading arguments that start `srt`. */\ninterface SrtCommand {\n readonly program: string;\n readonly args: readonly string[];\n /** The folders `srt` reads inside the sandbox, as absolute paths. */\n readonly readRoots: readonly string[];\n}\n\n/** How to start `srt`, or a `SandboxUnavailableError` when there is nothing to start. */\nasync function srtCommand(modules: NodeModules, binary: string | undefined): Promise<SrtCommand> {\n if (binary !== undefined) {\n // Resolved once against this process's folder, because it is started from the workspace.\n const program = modules.path.resolve(binary);\n try {\n await modules.fs.access(program, modules.fs.constants.X_OK);\n } catch (error) {\n throw new SandboxUnavailableError(\"srt\", `${binary} is not an executable file`, { cause: error });\n }\n return { program, args: [], readRoots: [] };\n }\n let cli: string;\n try {\n const url = import.meta.resolve(\"@anthropic-ai/sandbox-runtime/dist/cli.js\");\n cli = await modules.fs.realpath(modules.url.fileURLToPath(url));\n } catch (error) {\n throw new SandboxUnavailableError(\"srt\", \"the @anthropic-ai/sandbox-runtime package is not installed\", {\n cause: error,\n });\n }\n // `srt` runs its seccomp helper from the package's own folder, inside the sandbox.\n return { program: process.execPath, args: [cli], readRoots: [modules.path.resolve(cli, \"..\", \"..\", \"vendor\")] };\n}\n\n/** A `SandboxUnavailableError` unless this platform and host can run `srt`, looking for its programs on `hostPath`. */\nasync function checkHost(modules: NodeModules, hostPath: string): Promise<void> {\n if (process.platform !== \"linux\") {\n throw new SandboxUnavailableError(\n \"srt\",\n `only Linux is supported, because it is the only platform this backend is tested on, and this is ${process.platform}`,\n );\n }\n for (const program of REQUIRED_PROGRAMS) {\n if ((await findOnPath(modules, hostPath, program)) === undefined) {\n throw new SandboxUnavailableError(\"srt\", `${program} is not on the PATH, and srt needs it on Linux`);\n }\n }\n}\n\n// A variable name that `env` can set, which is every name a process can be given.\nconst VARIABLE_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n/** Everything a provisioned sandbox holds. */\ninterface SrtSandboxState {\n readonly modules: NodeModules;\n readonly command: SrtCommand;\n readonly root: string;\n readonly files: HostFiles;\n /** A private folder that holds the settings file and the run folder, and is removed on dispose. */\n readonly folder: string;\n /** The folder `srt` makes its proxy sockets in, and the only part of `folder` a command may read. */\n readonly runFolder: string;\n readonly settingsFile: string;\n /** The `PATH` that `srt` itself runs with, which finds `bwrap` and `socat`. */\n readonly hostPath: string;\n /** How the settings file's real paths map back to the request's spelling, for the read-back. */\n readonly names: SrtPolicyNames;\n}\n\nclass SrtSandbox extends BackendSandbox {\n private readonly runner: ProcessRunner;\n private readonly state: SrtSandboxState;\n\n constructor(state: SrtSandboxState) {\n super(state);\n this.state = state;\n this.runner = new ProcessRunner(state.modules);\n }\n\n /** The program that starts `srt`. */\n get program(): string {\n return this.state.command.program;\n }\n\n /** The arguments that start `srt` with this sandbox's settings, then run `inner`. */\n srtArguments(inner: readonly string[]): string[] {\n return [...this.state.command.args, \"--settings\", this.state.settingsFile, \"--\", ...inner];\n }\n\n /** The environment `srt` itself runs with: where to find its programs, and where to make its sockets. Nothing else. */\n launchEnvironment(): Record<string, string> {\n return { PATH: this.state.hostPath, TMPDIR: this.state.runFolder };\n }\n\n /**\n * The command that runs inside `srt`. `env` sets the command's whole environment from `srt`'s own, so a variable that\n * makes a program load code, such as `NODE_OPTIONS`, never reaches `srt` or the programs it starts outside the\n * sandbox. The `--` ends `env`'s options, so a first word that starts with `-` is a program name.\n */\n private innerCommand(command: readonly string[], env: Readonly<Record<string, string>>): string[] {\n const unset: string[] = [];\n for (const name of [\"PATH\", \"TMPDIR\"]) {\n if (!(name in env)) unset.push(\"-u\", name);\n }\n const assignments: string[] = [];\n for (const [name, value] of Object.entries(env)) {\n if (!VARIABLE_NAME.test(name)) {\n throw new HarnessError(\"invalid_sandbox_options\", `${JSON.stringify(name)} is not a variable name`);\n }\n assignments.push(`${name}=${value}`);\n }\n return [\"/usr/bin/env\", ...unset, \"--\", ...assignments, ...command];\n }\n\n /** Runs `command` under `srt` in `cwd`, with `env` as its whole environment. */\n private runUnderSrt(\n command: readonly string[],\n cwd: string,\n env: Readonly<Record<string, string>>,\n options: ExecOptions,\n ) {\n return this.runner.run(\n {\n program: this.state.command.program,\n args: this.srtArguments(this.innerCommand(command, env)),\n cwd,\n env: this.launchEnvironment(),\n missingProgram: \"reject\",\n graceMs: GRACE_MS,\n },\n options,\n );\n }\n\n async exec(command: readonly string[], options: ExecOptions): Promise<ExecResult> {\n const prepared = await this.prepare(command, options);\n if (!(\"cwd\" in prepared)) return prepared;\n const { stdoutBytes: _bytes, ...result } = await this.runUnderSrt(command, prepared.cwd, options.env, options);\n return result;\n }\n\n /** Reads the settings file `srt` is started with, as it is on disk now, and maps it back to a policy. */\n async readBack(): Promise<SandboxPolicy> {\n this.live();\n const text = await this.state.modules.fs.readFile(this.state.settingsFile, \"utf8\");\n return srtPolicyFromSettings(JSON.parse(text) as unknown, this.state.names);\n }\n\n protected async shutDown(): Promise<void> {\n await this.runner.stopAll();\n await this.state.modules.fs.rm(this.state.folder, { recursive: true, force: true });\n }\n}\n\n/** The first line of what `srt` printed, for the message of a failed start. */\nfunction firstLine(text: string): string {\n return text.trim().split(\"\\n\")[0] ?? \"no output\";\n}\n\n/** The settings and the real roots for one sandbox, with every path's symlinks resolved. */\nasync function planSandbox(\n modules: NodeModules,\n policy: SandboxPolicy,\n options: SrtSandboxOptions,\n command: SrtCommand,\n runFolder: string,\n) {\n const real = (paths: readonly string[]) => Promise.all(paths.map((path) => realOrSelf(modules, path)));\n const [readRoots, writeRoots, extra, denyWrite, helpers] = await Promise.all([\n real(policy.readRoots),\n real(policy.writeRoots),\n real(options.extraReadRoots ?? []),\n real(options.denyWrite ?? []),\n real(command.readRoots),\n ]);\n const systemReadRoots = await existing(modules, await real(SRT_SYSTEM_READ_ROOTS));\n // Only the run folder: the settings file beside it holds a proxy address that a command must not read.\n const helperReadRoots = [runFolder, ...helpers, ...extra];\n const input: SrtSettingsInput = {\n policy: { ...policy, readRoots, writeRoots },\n systemReadRoots,\n helperReadRoots,\n denyWrite,\n ...(options.parentProxy === undefined ? {} : { parentProxy: options.parentProxy }),\n };\n const names: SrtPolicyNames = {\n read: spellings(readRoots, policy.readRoots),\n write: spellings(writeRoots, policy.writeRoots),\n implicitReads: [...systemReadRoots, ...helperReadRoots],\n };\n return { settings: srtSettings(input), roots: { read: readRoots, write: writeRoots, denyWrite }, names };\n}\n\n/**\n * Builds the `srt` backend. `provision()` checks the platform, the programs `srt` needs and `srt` itself, by running a\n * command that does nothing, so a host that can't confine a process throws `SandboxUnavailableError` and runs nothing.\n * The policy's roots, `extraReadRoots` and `denyWrite` must be absolute folders other than `/`. Each command runs under\n * its own `srt`, so a command sees the proxy variables `srt` adds to its environment, besides those it was given.\n * Before it returns, `provision()` reads the settings file back from disk and throws `SandboxPolicyMismatchError` when\n * the policy it applies differs from the one requested. The backend lists no capability: it can't resume, snapshot or\n * pause.\n */\nexport function srtSandbox(options: SrtSandboxOptions = {}): SandboxClient {\n const client: SandboxClient = {\n tier: \"os\",\n stops: [\"mistakes\", \"exfiltration\"],\n async provision(manifest: WorkspaceManifest, policy: SandboxPolicy): Promise<Sandbox> {\n const modules = nodeModules(\"srt\");\n const hostPath = absolutePath(modules, process.env.PATH);\n await checkHost(modules, hostPath);\n const root = await workspaceRoot(modules, manifest.root);\n checkPaths(modules, [...policy.readRoots, ...policy.writeRoots], \"a sandbox root\");\n checkPaths(modules, options.extraReadRoots ?? [], \"an extra read root\");\n checkPaths(modules, options.denyWrite ?? [], \"a denyWrite folder\");\n const command = await srtCommand(modules, options.binary);\n const folder = await modules.fs.mkdtemp(modules.path.join(modules.os.tmpdir(), \"harness-srt-\"));\n try {\n await modules.fs.chmod(folder, 0o700);\n const runFolder = modules.path.join(folder, \"run\");\n await modules.fs.mkdir(runFolder, { mode: 0o700 });\n const plan = await planSandbox(modules, policy, options, command, runFolder);\n const settingsFile = modules.path.join(folder, \"settings.json\");\n await modules.fs.writeFile(settingsFile, JSON.stringify(plan.settings), { mode: 0o600 });\n const sandbox = new SrtSandbox({\n modules,\n command,\n root,\n files: new HostFiles(modules, root, plan.roots, isProtectedPath),\n folder,\n runFolder,\n settingsFile,\n hostPath,\n names: plan.names,\n });\n await probe(modules, sandbox, root);\n await sandbox.confirm(client, policy);\n const encoder = new TextEncoder();\n for (const [path, data] of Object.entries(manifest.files ?? {})) {\n await sandbox.writeFile(path, typeof data === \"string\" ? encoder.encode(data) : data);\n }\n return sandbox;\n } catch (error) {\n await modules.fs.rm(folder, { recursive: true, force: true });\n throw error;\n }\n },\n };\n return client;\n}\n\n/** Starts `srt` once with a command that does nothing, and throws `SandboxUnavailableError` when it can't. */\nasync function probe(modules: NodeModules, sandbox: SrtSandbox, root: string): Promise<void> {\n const runner = new ProcessRunner(modules);\n const result = await runner\n .run(\n {\n program: sandbox.program,\n args: sandbox.srtArguments([\"/usr/bin/true\"]),\n cwd: root,\n env: sandbox.launchEnvironment(),\n missingProgram: \"reject\",\n graceMs: GRACE_MS,\n },\n { env: {}, signal: new AbortController().signal, timeoutMs: PROBE_TIMEOUT_MS },\n )\n .catch((error: unknown) => {\n throw new SandboxUnavailableError(\"srt\", \"it could not be started\", { cause: error });\n });\n if (result.exitCode !== 0) {\n throw new SandboxUnavailableError(\"srt\", `it did not start a command: ${firstLine(result.stderr)}`);\n }\n}\n"]}
|
|
@@ -1,8 +1,3 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* The `srt` settings file for a sandbox policy. It is a pure function of the policy, so a test can read the file a
|
|
3
|
-
* backend would write without starting `srt`. `srt` is a pre-1.0 beta whose settings format may change (as of
|
|
4
|
-
* November 2026), so this is the one place that knows the format.
|
|
5
|
-
*/
|
|
6
1
|
import type { SandboxPolicy } from "../types.js";
|
|
7
2
|
/** A path that `srt` must read as written. Without `literal`, `srt` reads a spelling such as `*.ts` as a pattern. */
|
|
8
3
|
export interface SrtPathEntry {
|
|
@@ -46,3 +41,20 @@ export interface SrtSettingsInput {
|
|
|
46
41
|
* policy's hosts. Each path is `literal`, so a folder named `*` is never read as a pattern.
|
|
47
42
|
*/
|
|
48
43
|
export declare function srtSettings(input: SrtSettingsInput): SrtSettings;
|
|
44
|
+
/** How a settings file's real paths map back to the spelling of the request, for `srtPolicyFromSettings()`. */
|
|
45
|
+
export interface SrtPolicyNames {
|
|
46
|
+
/** For each real read root, the request's spellings that resolved to it. */
|
|
47
|
+
readonly read: ReadonlyMap<string, readonly string[]>;
|
|
48
|
+
/** For each real write root, the request's spellings that resolved to it. */
|
|
49
|
+
readonly write: ReadonlyMap<string, readonly string[]>;
|
|
50
|
+
/** The readable folders the backend adds itself: the system's, `srt`'s own and the caller's extra read roots. */
|
|
51
|
+
readonly implicitReads: readonly string[];
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* The policy a settings file applies, in the spelling of the request. A write root maps back through `names.write`,
|
|
55
|
+
* and a readable folder through `names.read`. A folder the backend adds itself, and a write root, which is readable
|
|
56
|
+
* anyway, are left out, so any other folder in the file shows up as a read root the request didn't ask for. A file
|
|
57
|
+
* that doesn't deny every read first reads back as the read root `/`. A file that isn't in the shape `srtSettings()`
|
|
58
|
+
* writes throws `SandboxPolicyMismatchError`.
|
|
59
|
+
*/
|
|
60
|
+
export declare function srtPolicyFromSettings(settings: unknown, names: SrtPolicyNames): SandboxPolicy;
|