@buildanagent/harness 0.1.0-alpha.28 → 0.1.0-alpha.30
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 +152 -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/addresses.d.ts +11 -0
- package/dist/credentials/addresses.js +41 -2
- package/dist/credentials/addresses.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 +14 -7
- package/dist/errors.js +13 -6
- 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/escalation-table.d.ts +38 -0
- package/dist/sandbox/escalation-table.js +95 -0
- package/dist/sandbox/escalation-table.js.map +1 -0
- package/dist/sandbox/escalation.d.ts +191 -0
- package/dist/sandbox/escalation.js +370 -0
- package/dist/sandbox/escalation.js.map +1 -0
- 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 +9 -4
- package/dist/sandbox/index.js +8 -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/sandbox/widen.d.ts +10 -0
- package/dist/sandbox/widen.js +150 -0
- package/dist/sandbox/widen.js.map +1 -0
- package/dist/session/approvals.d.ts +30 -1
- package/dist/session/approvals.js +12 -4
- package/dist/session/approvals.js.map +1 -1
- package/dist/session/code-call.d.ts +15 -1
- package/dist/session/code-call.js +2 -1
- package/dist/session/code-call.js.map +1 -1
- package/dist/session/escalation-log.d.ts +65 -0
- package/dist/session/escalation-log.js +84 -0
- package/dist/session/escalation-log.js.map +1 -0
- package/dist/session/rebuild.js +12 -3
- package/dist/session/rebuild.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 +52 -0
- package/package.json +5 -5
package/dist/sandbox/index.d.ts
CHANGED
|
@@ -1,8 +1,13 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* `@buildanagent/harness/sandbox`: the sandbox interface, the unsafe `none` backend
|
|
3
|
-
*
|
|
2
|
+
* `@buildanagent/harness/sandbox`: the sandbox interface, the unsafe `none` backend, `spawnEnv()`, the policy read-back and
|
|
3
|
+
* capability helpers, and `escalation()`, the host's state machine for a denied command. The `srt` and Docker backends
|
|
4
|
+
* have their own subpaths. `fakeSandbox()` and the conformance suite are in `./testing`.
|
|
4
5
|
*/
|
|
5
|
-
export {
|
|
6
|
+
export { ESCALATION_TOOL, type EscalationRecord } from "../session/escalation-log.js";
|
|
7
|
+
export { SandboxDeniedError, SandboxPolicyMismatchError, SandboxUnavailableError, SandboxUnsupportedError, } from "./errors.js";
|
|
8
|
+
export { type EscalationMachine, type EscalationOptions, type EscalationResolveOptions, type EscalationResult, type EscalationRule, type EscalationRun, escalation, type PendingEscalation, } from "./escalation.js";
|
|
9
|
+
export { ESCALATION_EVENTS, ESCALATION_STATES, ESCALATION_TRANSITIONS, type EscalationEvent, type EscalationState, type EscalationTransition, nextEscalationState, } from "./escalation-table.js";
|
|
6
10
|
export { NONE_SANDBOX_WARNING, type NoneSandboxOptions, noneSandbox } from "./none.js";
|
|
11
|
+
export { confirmPolicy, hasCapability, pauseSandbox, policyDifference, resumeSandbox, snapshotSandbox, stopsFor, } from "./policy.js";
|
|
7
12
|
export { spawnEnv } from "./spawn-env.js";
|
|
8
|
-
export type { ApprovalPolicy, ExecOptions, ExecResult, Sandbox, SandboxClient, SandboxDenial, SandboxPolicy, SandboxStop, SandboxTier, WorkspaceManifest, } from "./types.js";
|
|
13
|
+
export type { ApprovalPolicy, ExecOptions, ExecResult, Sandbox, SandboxCapability, SandboxClient, SandboxDenial, SandboxPolicy, SandboxStop, SandboxTier, WorkspaceManifest, } from "./types.js";
|
package/dist/sandbox/index.js
CHANGED
|
@@ -1,8 +1,13 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* `@buildanagent/harness/sandbox`: the sandbox interface, the unsafe `none` backend
|
|
3
|
-
*
|
|
2
|
+
* `@buildanagent/harness/sandbox`: the sandbox interface, the unsafe `none` backend, `spawnEnv()`, the policy read-back and
|
|
3
|
+
* capability helpers, and `escalation()`, the host's state machine for a denied command. The `srt` and Docker backends
|
|
4
|
+
* have their own subpaths. `fakeSandbox()` and the conformance suite are in `./testing`.
|
|
4
5
|
*/
|
|
5
|
-
export {
|
|
6
|
+
export { ESCALATION_TOOL } from "../session/escalation-log.js";
|
|
7
|
+
export { SandboxDeniedError, SandboxPolicyMismatchError, SandboxUnavailableError, SandboxUnsupportedError, } from "./errors.js";
|
|
8
|
+
export { escalation, } from "./escalation.js";
|
|
9
|
+
export { ESCALATION_EVENTS, ESCALATION_STATES, ESCALATION_TRANSITIONS, nextEscalationState, } from "./escalation-table.js";
|
|
6
10
|
export { NONE_SANDBOX_WARNING, noneSandbox } from "./none.js";
|
|
11
|
+
export { confirmPolicy, hasCapability, pauseSandbox, policyDifference, resumeSandbox, snapshotSandbox, stopsFor, } from "./policy.js";
|
|
7
12
|
export { spawnEnv } from "./spawn-env.js";
|
|
8
13
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/sandbox/index.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/sandbox/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,eAAe,EAAyB,MAAM,8BAA8B,CAAC;AACtF,OAAO,EACL,kBAAkB,EAClB,0BAA0B,EAC1B,uBAAuB,EACvB,uBAAuB,GACxB,MAAM,aAAa,CAAC;AACrB,OAAO,EAOL,UAAU,GAEX,MAAM,iBAAiB,CAAC;AACzB,OAAO,EACL,iBAAiB,EACjB,iBAAiB,EACjB,sBAAsB,EAItB,mBAAmB,GACpB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,oBAAoB,EAA2B,WAAW,EAAE,MAAM,WAAW,CAAC;AACvF,OAAO,EACL,aAAa,EACb,aAAa,EACb,YAAY,EACZ,gBAAgB,EAChB,aAAa,EACb,eAAe,EACf,QAAQ,GACT,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC","sourcesContent":["/**\n * `@buildanagent/harness/sandbox`: the sandbox interface, the unsafe `none` backend, `spawnEnv()`, the policy read-back and\n * capability helpers, and `escalation()`, the host's state machine for a denied command. The `srt` and Docker backends\n * have their own subpaths. `fakeSandbox()` and the conformance suite are in `./testing`.\n */\n\nexport { ESCALATION_TOOL, type EscalationRecord } from \"../session/escalation-log.js\";\nexport {\n SandboxDeniedError,\n SandboxPolicyMismatchError,\n SandboxUnavailableError,\n SandboxUnsupportedError,\n} from \"./errors.js\";\nexport {\n type EscalationMachine,\n type EscalationOptions,\n type EscalationResolveOptions,\n type EscalationResult,\n type EscalationRule,\n type EscalationRun,\n escalation,\n type PendingEscalation,\n} from \"./escalation.js\";\nexport {\n ESCALATION_EVENTS,\n ESCALATION_STATES,\n ESCALATION_TRANSITIONS,\n type EscalationEvent,\n type EscalationState,\n type EscalationTransition,\n nextEscalationState,\n} from \"./escalation-table.js\";\nexport { NONE_SANDBOX_WARNING, type NoneSandboxOptions, noneSandbox } from \"./none.js\";\nexport {\n confirmPolicy,\n hasCapability,\n pauseSandbox,\n policyDifference,\n resumeSandbox,\n snapshotSandbox,\n stopsFor,\n} from \"./policy.js\";\nexport { spawnEnv } from \"./spawn-env.js\";\nexport type {\n ApprovalPolicy,\n ExecOptions,\n ExecResult,\n Sandbox,\n SandboxCapability,\n SandboxClient,\n SandboxDenial,\n SandboxPolicy,\n SandboxStop,\n SandboxTier,\n WorkspaceManifest,\n} from \"./types.js\";\n"]}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type { Sandbox, SandboxCapability, SandboxClient, SandboxPolicy, SandboxStop, SandboxTier } from "./types.js";
|
|
2
|
+
/**
|
|
3
|
+
* The method by which `resumeSandbox()` sets the stops of a sandbox whose `stops` is a getter, such as a backend
|
|
4
|
+
* sandbox's, so that a later `confirm()` still updates what the getter reads. It is internal to the package.
|
|
5
|
+
*/
|
|
6
|
+
export declare const APPLY_STOPS: unique symbol;
|
|
7
|
+
/**
|
|
8
|
+
* The stops a backend of `tier` delivers under `policy`. A `none` tier stops nothing. Any other tier stops `mistakes`
|
|
9
|
+
* unless a root is `/`, and `exfiltration` unless the allowlist holds an entry that opens every host (`*`, `0.0.0.0/0`
|
|
10
|
+
* or `::/0`). Only a `microvm` stops a `hostile_process`, because every other tier shares a kernel with the host or
|
|
11
|
+
* relies on one that runs in user space.
|
|
12
|
+
*/
|
|
13
|
+
export declare function stopsFor(tier: SandboxTier, policy: SandboxPolicy): SandboxStop[];
|
|
14
|
+
/**
|
|
15
|
+
* The first field in which `applied` differs from `requested`, or `undefined` when they hold the same entries. The
|
|
16
|
+
* fields are compared as sets in the order `readRoots`, `writeRoots`, `network.allow`, `network.deny`, and a field
|
|
17
|
+
* that isn't a list of strings differs. Paths and hosts compare as written, so a backend reads back in the request's
|
|
18
|
+
* spelling.
|
|
19
|
+
*/
|
|
20
|
+
export declare function policyDifference(requested: SandboxPolicy, applied: SandboxPolicy): string | undefined;
|
|
21
|
+
/** The options of `confirmPolicy()`. */
|
|
22
|
+
interface ConfirmOptions {
|
|
23
|
+
/** Whether a mismatch disposes the sandbox before it is thrown. Defaults to `true`. */
|
|
24
|
+
readonly dispose?: boolean;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Reads back the policy `sandbox` applied and compares it with `requested`. It resolves with the stops the applied
|
|
28
|
+
* policy delivers, and it throws `SandboxPolicyMismatchError` when a field differs, when the client claims a stop that
|
|
29
|
+
* the applied policy doesn't deliver (`stops`, with the cause in the message), or when a client that claims a stop has
|
|
30
|
+
* no read-back or its read-back fails (`readBack`, or the read-back's own field when it threw a mismatch). A client
|
|
31
|
+
* that claims no stop needs no read-back. It disposes the sandbox before it throws, unless `options.dispose` is
|
|
32
|
+
* `false`, which leaves the sandbox to the caller.
|
|
33
|
+
*/
|
|
34
|
+
export declare function confirmPolicy(client: SandboxClient, sandbox: Sandbox, requested: SandboxPolicy, options?: ConfirmOptions): Promise<readonly SandboxStop[]>;
|
|
35
|
+
/** Whether `client` lists `capability`. A client that lists none has none. */
|
|
36
|
+
export declare function hasCapability(client: SandboxClient, capability: SandboxCapability): boolean;
|
|
37
|
+
/**
|
|
38
|
+
* Reattaches to a sandbox by its id, or starts one from a snapshot's id, then confirms its policy as `provision()`
|
|
39
|
+
* does and sets the sandbox's `stops` to what the confirmed policy delivers. It throws `SandboxUnsupportedError` when
|
|
40
|
+
* the client doesn't list `resume` or has no `resume()`, and `SandboxPolicyMismatchError` when the resumed sandbox's
|
|
41
|
+
* policy differs from `policy`. A mismatch does not dispose the sandbox, which may be a paused one worth keeping: the
|
|
42
|
+
* caller decides whether to dispose it, and must not run anything in it under the requested policy.
|
|
43
|
+
*/
|
|
44
|
+
export declare function resumeSandbox(client: SandboxClient, id: string, policy: SandboxPolicy): Promise<Sandbox>;
|
|
45
|
+
/** Snapshots `sandbox` and resolves with the id `resumeSandbox()` takes, or throws `SandboxUnsupportedError`. */
|
|
46
|
+
export declare function snapshotSandbox(client: SandboxClient, sandbox: Sandbox): Promise<string>;
|
|
47
|
+
/** Pauses `sandbox` until `resumeSandbox()` with its `id`, or throws `SandboxUnsupportedError`. */
|
|
48
|
+
export declare function pauseSandbox(client: SandboxClient, sandbox: Sandbox): Promise<void>;
|
|
49
|
+
export {};
|
|
@@ -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,YA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K,EAAE,UAAU,EAAE,IAAI,EAAE,YAAY,EAAE,IAAI,EAAE,CAAC,CAAC;IAC7G,IAAI,CAAC,GAAG,IAAI,CAAC,WAAW,CAAC,OAAO,CAAC,KAAK,IAAI,EAAE,EAAE,KAAK,CAAC,EAAE,CAAC;QACrD,MAAM,IAAI,0BAA0B,CAAC,OAAO,EAAE,EAAE,MAAM,EAAE,0CAA0C,EAAE,CAAC,CAAC;IACxG,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC;AAED,iHAAiH;AACjH,MAAM,CAAC,KAAK,UAAU,eAAe,CAAC,MAAqB,EAAE,OAAgB;IAC3E,IAAI,CAAC,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;AA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AC;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, ...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,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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) {
|