@niwa-labs/sandbox 0.0.0-stage → 0.0.0
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/LICENSE +21 -0
- package/README.md +21 -2
- package/package.json +15 -4
- package/src/access.ts +642 -0
- package/src/index.ts +68 -0
- package/src/launch.ts +403 -0
- package/src/nono.ts +349 -0
- package/src/paths.ts +31 -0
- package/src/profile.ts +140 -0
- package/src/profiles.ts +62 -0
- package/src/sandbox.ts +124 -0
- package/src/spawn.ts +147 -0
- package/src/spec.ts +60 -0
- package/src/srt.ts +187 -0
- package/test/access.test.ts +367 -0
- package/test/box-process.test.ts +327 -0
- package/test/launcher-env.test.ts +144 -0
- package/test/live.test.ts +259 -0
- package/test/manifest.test.ts +231 -0
- package/tsconfig.json +6 -0
package/src/access.ts
ADDED
|
@@ -0,0 +1,642 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How a box gets its access: profiles taken by name, paths asked for, and the plan they resolve to.
|
|
3
|
+
*
|
|
4
|
+
* A caller lists what its box should have: `"project"` (the working directory, writable),
|
|
5
|
+
* `"toolchains"` (the PATH, Homebrew and the catalog's programs, readable), a profile by its name,
|
|
6
|
+
* or a path (`{ read }`, `{ write }`) or a host (`{ net }`). `allow` adds to the host's default and
|
|
7
|
+
* `only` replaces it. The host's sandbox (`sandbox({ profiles })`) knows every profile: the catalog,
|
|
8
|
+
* the host's own, and the profile of each harness installation.
|
|
9
|
+
*
|
|
10
|
+
* The plan holds three things. The paths the box may use, each with where it came from, are
|
|
11
|
+
* guaranteed to be reachable. The closed paths are guaranteed not to be: every path a profile names
|
|
12
|
+
* is closed to every box that did not take that profile, and so is the closed list (the user's keys
|
|
13
|
+
* and niwa's own secrets) unless a path in it is asked for by name. The rest is the sandbox's own:
|
|
14
|
+
* srt reads everything else, nono nothing else. A sandbox that cannot hold the plan refuses it.
|
|
15
|
+
*
|
|
16
|
+
* Widening a box beyond the host's default takes a rule of the caller's grant: `box.use@<profile>`,
|
|
17
|
+
* `box.read@<path>`, `box.write@<path>`, `box.net@<host>`. The plan names the rules it needs; the
|
|
18
|
+
* caller holds them against the grant, since the sandbox knows nothing of grants.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import { closeSync, constants, existsSync, fstatSync, lstatSync, openSync, readSync, statSync } from "node:fs";
|
|
22
|
+
import { homedir } from "node:os";
|
|
23
|
+
import { basename, dirname, isAbsolute, join, resolve } from "node:path";
|
|
24
|
+
|
|
25
|
+
import { z } from "zod";
|
|
26
|
+
|
|
27
|
+
import { covers, homeExpanded, linkPlace, programPaths, realPlace, resolveProfile } from "./profile.ts";
|
|
28
|
+
import type { BoxProfile, ResolvedProfile } from "./profile.ts";
|
|
29
|
+
import { catalog } from "./profiles.ts";
|
|
30
|
+
import { BoxRefused } from "./sandbox.ts";
|
|
31
|
+
import type { BoxPolicy, BoxRefusal, Sandbox, SandboxManifest } from "./sandbox.ts";
|
|
32
|
+
import { EnvNameSchema, boxSpec } from "./spec.ts";
|
|
33
|
+
import type { BoxSpec } from "./spec.ts";
|
|
34
|
+
import type { BoxSandboxName } from "./launch.ts";
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* The names of the profiles a box may take. The catalog's are here; a host or a plugin that adds a
|
|
38
|
+
* profile adds its name by declaration merging, so a request is checked as it is written:
|
|
39
|
+
*
|
|
40
|
+
* ```ts
|
|
41
|
+
* declare module "@niwa-labs/sandbox" { interface BoxProfiles { pnpm: true } }
|
|
42
|
+
* ```
|
|
43
|
+
*/
|
|
44
|
+
export interface BoxProfiles {
|
|
45
|
+
git: true;
|
|
46
|
+
node: true;
|
|
47
|
+
bun: true;
|
|
48
|
+
npm: true;
|
|
49
|
+
cargo: true;
|
|
50
|
+
uv: true;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** The name of a profile a box may take. */
|
|
54
|
+
export type ProfileName = keyof BoxProfiles & string;
|
|
55
|
+
|
|
56
|
+
/** One thing a box asks for. */
|
|
57
|
+
export type AccessItem =
|
|
58
|
+
| "project"
|
|
59
|
+
| "toolchains"
|
|
60
|
+
| ProfileName
|
|
61
|
+
| { readonly read: string }
|
|
62
|
+
| { readonly write: string }
|
|
63
|
+
| { readonly net: string };
|
|
64
|
+
|
|
65
|
+
/** What a box asks for: `allow` adds to the host's default, `only` replaces it. */
|
|
66
|
+
export type BoxAccess =
|
|
67
|
+
| { readonly allow?: readonly AccessItem[]; readonly only?: undefined }
|
|
68
|
+
| { readonly only: readonly AccessItem[]; readonly allow?: undefined };
|
|
69
|
+
|
|
70
|
+
/** An item as it travels: a name is any text until the host's profiles have checked it. */
|
|
71
|
+
export const AccessItemSchema = z.union([
|
|
72
|
+
z.string().min(1),
|
|
73
|
+
z.strictObject({ read: z.string().min(1) }),
|
|
74
|
+
z.strictObject({ write: z.string().min(1) }),
|
|
75
|
+
z.strictObject({ net: z.string().regex(/^\S+$/, "a host must be non-empty and contain no whitespace") }),
|
|
76
|
+
]);
|
|
77
|
+
export type AccessItemInput = z.output<typeof AccessItemSchema>;
|
|
78
|
+
|
|
79
|
+
/** A request as it travels: `allow` or `only`, not both. */
|
|
80
|
+
export const BoxAccessSchema = z
|
|
81
|
+
.strictObject({ allow: z.array(AccessItemSchema).optional(), only: z.array(AccessItemSchema).optional() })
|
|
82
|
+
.refine((access) => access.allow === undefined || access.only === undefined, "a box takes allow or only, not both");
|
|
83
|
+
export type BoxAccessInput = z.output<typeof BoxAccessSchema>;
|
|
84
|
+
|
|
85
|
+
/** Where a path, a host or an item of a box came from. */
|
|
86
|
+
export type Origin = string;
|
|
87
|
+
|
|
88
|
+
export interface PathNeed {
|
|
89
|
+
readonly path: string;
|
|
90
|
+
readonly mode: "read" | "write";
|
|
91
|
+
readonly from: Origin;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export interface Skipped {
|
|
95
|
+
readonly place: string;
|
|
96
|
+
readonly from: Origin;
|
|
97
|
+
readonly why: string;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** A box resolved: what it may use, what it may not, what was left out and the rules it needs. */
|
|
101
|
+
export interface BoxPlan {
|
|
102
|
+
readonly cwd: string;
|
|
103
|
+
/** The request after the host's default: every item and whether the host or the call gave it. */
|
|
104
|
+
readonly request: { readonly mode: "allow" | "only"; readonly items: readonly { readonly item: AccessItemInput; readonly from: "host" | "call" }[] };
|
|
105
|
+
/** Guaranteed reachable. */
|
|
106
|
+
readonly paths: readonly PathNeed[];
|
|
107
|
+
readonly net: readonly { readonly host: string; readonly from: Origin }[];
|
|
108
|
+
/** Guaranteed closed. */
|
|
109
|
+
readonly closed: readonly { readonly path: string; readonly from: Origin }[];
|
|
110
|
+
readonly skipped: readonly Skipped[];
|
|
111
|
+
/** The rules of a grant the call's widening needs, one per item beyond the host's default. */
|
|
112
|
+
readonly rules: readonly string[];
|
|
113
|
+
/** What keeps the plan from being a box, whatever the sandbox. */
|
|
114
|
+
readonly refusals: readonly BoxRefusal[];
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** What a host's sandbox is made with. */
|
|
118
|
+
export interface SandboxOptions {
|
|
119
|
+
/** The sandbox boxes run in. Default: each module's own (sessions srt, proc nono). */
|
|
120
|
+
readonly adapter?: BoxSandboxName | Sandbox;
|
|
121
|
+
/** Profiles besides the catalog's, by name. A name of the catalog given again replaces it. */
|
|
122
|
+
readonly profiles?: { readonly [Name in ProfileName]?: BoxProfile } & Readonly<Record<string, BoxProfile>>;
|
|
123
|
+
/** Places closed to every box besides the built-in list, unless a box asks for one by name. */
|
|
124
|
+
readonly closed?: readonly string[];
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** What one box is resolved from. */
|
|
128
|
+
export interface PlanInput {
|
|
129
|
+
/** The working directory of the box, absolute. */
|
|
130
|
+
readonly cwd: string;
|
|
131
|
+
/** Active registration from the host Git registry, never from the box request. */
|
|
132
|
+
readonly worktree?: { readonly id: string; readonly path: string; readonly repo: string };
|
|
133
|
+
/** The host's default for this kind of box. */
|
|
134
|
+
readonly defaults: BoxAccess | BoxAccessInput;
|
|
135
|
+
/** What the call asked for. */
|
|
136
|
+
readonly request?: BoxAccess | BoxAccessInput | undefined;
|
|
137
|
+
/** The installation whose profile the box takes as its own, whatever the request says. */
|
|
138
|
+
readonly owner?: string;
|
|
139
|
+
/** Places the box writes whatever the request says, with where each came from. */
|
|
140
|
+
readonly writes?: readonly { readonly path: string; readonly from: Origin }[];
|
|
141
|
+
/** Places closed to the box besides the profiles' and the built-in list (niwa's own). */
|
|
142
|
+
readonly closed?: readonly { readonly path: string; readonly from: Origin }[];
|
|
143
|
+
/** Whether the box may reach a network at all. A box that may not refuses every host asked of it. */
|
|
144
|
+
readonly network: boolean;
|
|
145
|
+
/**
|
|
146
|
+
* Why `"project"` gives nothing, when it does not: a box whose working directory nobody chose
|
|
147
|
+
* (the host's own) is not given it to write. The item is kept as skipped, with this reason.
|
|
148
|
+
*/
|
|
149
|
+
readonly noProject?: string;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** A host's sandbox: its profiles, the closed list, and the plans of its boxes. */
|
|
153
|
+
export interface SandboxHost {
|
|
154
|
+
readonly adapter: BoxSandboxName | Sandbox | undefined;
|
|
155
|
+
/** The names of the profiles a box may ask for. */
|
|
156
|
+
names(): readonly string[];
|
|
157
|
+
/**
|
|
158
|
+
* Gives the profile of a harness installation. It is no name a box may ask for: the sessions of
|
|
159
|
+
* the installation take it, and every other box finds its paths closed.
|
|
160
|
+
*/
|
|
161
|
+
install(owner: string, profile: BoxProfile): void;
|
|
162
|
+
/** Resolves one box on this machine. */
|
|
163
|
+
plan(input: PlanInput): BoxPlan;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** Places that hold the user's keys: closed to every box unless it asks for one by name. */
|
|
167
|
+
export const ALWAYS_CLOSED: readonly string[] = ["~/.ssh", "~/.aws", "~/.gnupg", "~/Library/Keychains"];
|
|
168
|
+
|
|
169
|
+
const PROFILE_NAME = /^[a-z0-9][a-z0-9._-]*$/;
|
|
170
|
+
|
|
171
|
+
/** A place as a rule's target names it: `%` and the hex code for what a target cannot hold. */
|
|
172
|
+
export function placeTarget(path: string): string {
|
|
173
|
+
const escaped = (char: string): string =>
|
|
174
|
+
[...new TextEncoder().encode(char)].map((byte) => `%${byte.toString(16).toUpperCase().padStart(2, "0")}`).join("");
|
|
175
|
+
return path.replace(/[\s*@:{}%]/g, escaped);
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** The text of an item, as an error or a CLI writes it. */
|
|
179
|
+
export function itemText(item: AccessItemInput): string {
|
|
180
|
+
if (typeof item === "string") return item;
|
|
181
|
+
if ("read" in item) return `read:${item.read}`;
|
|
182
|
+
if ("write" in item) return `write:${item.write}`;
|
|
183
|
+
return `net:${item.net}`;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** An item from the text a command line gives: `read:<path>`, `write:<path>`, `net:<host>`, or a name. */
|
|
187
|
+
export function itemOf(text: string): AccessItemInput {
|
|
188
|
+
for (const mode of ["read", "write", "net"] as const) {
|
|
189
|
+
if (text.startsWith(`${mode}:`)) return { [mode]: text.slice(mode.length + 1) } as AccessItemInput;
|
|
190
|
+
}
|
|
191
|
+
return text;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** The directory Homebrew is installed in, where there is one. */
|
|
195
|
+
function homebrewPrefix(env: Readonly<Record<string, string | undefined>>): string[] {
|
|
196
|
+
const given = env["HOMEBREW_PREFIX"];
|
|
197
|
+
if (given !== undefined && isAbsolute(given)) return [given];
|
|
198
|
+
return ["/opt/homebrew"].filter((place) => existsSync(join(place, "bin", "brew")));
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** The place a path of a request names: from the working directory when relative, `~` expanded, links resolved. */
|
|
202
|
+
function placeOf(path: string, cwd: string, home: string): string {
|
|
203
|
+
const expanded = homeExpanded(path, home);
|
|
204
|
+
return realPlace(isAbsolute(expanded) ? expanded : resolve(cwd, expanded), home);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** Makes a host's sandbox: the catalog, the host's profiles, and the closed list. */
|
|
208
|
+
export function sandbox(options: SandboxOptions = {}): SandboxHost {
|
|
209
|
+
const profiles = new Map<string, BoxProfile>(Object.entries(catalog));
|
|
210
|
+
for (const [name, profile] of Object.entries(options.profiles ?? {})) {
|
|
211
|
+
if (!PROFILE_NAME.test(name)) throw new TypeError(`a profile name is lower-case letters, digits, ".", "_" and "-": ${JSON.stringify(name)}`);
|
|
212
|
+
if (profile !== undefined) profiles.set(name, profile);
|
|
213
|
+
}
|
|
214
|
+
const installations = new Map<string, BoxProfile>();
|
|
215
|
+
const extraClosed = options.closed ?? [];
|
|
216
|
+
|
|
217
|
+
return {
|
|
218
|
+
adapter: options.adapter,
|
|
219
|
+
names: () => [...profiles.keys()],
|
|
220
|
+
install(owner, profile) {
|
|
221
|
+
installations.set(owner, profile);
|
|
222
|
+
},
|
|
223
|
+
plan(input) {
|
|
224
|
+
return planBox(input, { profiles, catalog: new Set(Object.keys(catalog)), installations, closed: extraClosed });
|
|
225
|
+
},
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
interface Registry {
|
|
230
|
+
readonly profiles: ReadonlyMap<string, BoxProfile>;
|
|
231
|
+
/** The names of the catalog's profiles, whose read side the toolchains take. */
|
|
232
|
+
readonly catalog: ReadonlySet<string>;
|
|
233
|
+
readonly installations: ReadonlyMap<string, BoxProfile>;
|
|
234
|
+
readonly closed: readonly string[];
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** The items of a request with where each came from, after the host's default. */
|
|
238
|
+
function merged(defaults: BoxAccess | BoxAccessInput, request: BoxAccess | BoxAccessInput | undefined): BoxPlan["request"] {
|
|
239
|
+
const host = (defaults.allow ?? defaults.only ?? []).map((item) => ({ item: item as AccessItemInput, from: "host" as const }));
|
|
240
|
+
if (request?.only !== undefined) return { mode: "only", items: request.only.map((item) => ({ item: item as AccessItemInput, from: "call" as const })) };
|
|
241
|
+
return { mode: "allow", items: [...host, ...(request?.allow ?? []).map((item) => ({ item: item as AccessItemInput, from: "call" as const }))] };
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
function planBox(input: PlanInput, registry: Registry): BoxPlan {
|
|
245
|
+
const home = homedir();
|
|
246
|
+
const env = process.env;
|
|
247
|
+
// The places of the box are decided on real paths; the box itself runs where it was asked to.
|
|
248
|
+
const cwd = realPlace(input.cwd, home);
|
|
249
|
+
const given = resolve(homeExpanded(input.cwd, home));
|
|
250
|
+
const request = merged(input.defaults, input.request);
|
|
251
|
+
const refusals: BoxRefusal[] = [];
|
|
252
|
+
const skipped: Skipped[] = [];
|
|
253
|
+
const paths: PathNeed[] = [];
|
|
254
|
+
const net: { host: string; from: Origin }[] = [];
|
|
255
|
+
|
|
256
|
+
const resolved = new Map<string, ResolvedProfile>();
|
|
257
|
+
const profileOf = (name: string, profile: BoxProfile): ResolvedProfile => {
|
|
258
|
+
let found = resolved.get(name);
|
|
259
|
+
if (found === undefined) {
|
|
260
|
+
const given = resolveProfile(profile, name, { home, env });
|
|
261
|
+
// A program keeps the name it is found by: a link stays a link beside its target.
|
|
262
|
+
const place = (path: string) => (given.programs.includes(path) ? linkPlace(path, home) : realPlace(path, home));
|
|
263
|
+
found = {
|
|
264
|
+
read: [...new Set(given.read.map(place))],
|
|
265
|
+
write: [...new Set(given.write.map(place))],
|
|
266
|
+
net: given.net,
|
|
267
|
+
programs: [...new Set(given.programs.flatMap((path) => [place(path), path]))],
|
|
268
|
+
};
|
|
269
|
+
resolved.set(name, found);
|
|
270
|
+
}
|
|
271
|
+
return found;
|
|
272
|
+
};
|
|
273
|
+
|
|
274
|
+
// Every profile, resolved once: the ones taken give their paths, the others close theirs.
|
|
275
|
+
const known = registry.profiles;
|
|
276
|
+
const unknown = (name: string) => `${name} is no profile; the known ones are ${[...known.keys()].sort().join(", ")}, "project" and "toolchains"`;
|
|
277
|
+
const taken = new Set<string>();
|
|
278
|
+
for (const { item } of request.items) {
|
|
279
|
+
if (typeof item !== "string" || item === "project" || item === "toolchains") continue;
|
|
280
|
+
if (known.has(item)) taken.add(item);
|
|
281
|
+
else refusals.push({ code: "unknown-profile", message: unknown(item) });
|
|
282
|
+
}
|
|
283
|
+
const ownerOrigin = input.owner === undefined ? undefined : `harness:${input.owner}`;
|
|
284
|
+
const takenPaths: string[] = [];
|
|
285
|
+
const addProfile = (from: Origin, profile: ResolvedProfile) => {
|
|
286
|
+
for (const path of profile.read) paths.push({ path, mode: "read", from });
|
|
287
|
+
for (const path of profile.write) paths.push({ path, mode: "write", from });
|
|
288
|
+
for (const path of profile.programs) if (!profile.read.includes(path)) paths.push({ path, mode: "read", from });
|
|
289
|
+
for (const host of profile.net) {
|
|
290
|
+
if (input.network) net.push({ host, from });
|
|
291
|
+
else skipped.push({ place: host, from, why: "this box reaches no network" });
|
|
292
|
+
}
|
|
293
|
+
takenPaths.push(...profile.read, ...profile.write);
|
|
294
|
+
};
|
|
295
|
+
if (input.owner !== undefined && ownerOrigin !== undefined) {
|
|
296
|
+
const own = registry.installations.get(input.owner);
|
|
297
|
+
if (own !== undefined) addProfile(ownerOrigin, profileOf(ownerOrigin, own));
|
|
298
|
+
}
|
|
299
|
+
for (const name of taken) {
|
|
300
|
+
const profile = known.get(name);
|
|
301
|
+
if (profile !== undefined) addProfile(`profile:${name}`, profileOf(`profile:${name}`, profile));
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
// Closed: what every other profile names (but its programs), unless a profile taken names it too.
|
|
305
|
+
const closed: { path: string; from: Origin }[] = [];
|
|
306
|
+
const others: [string, BoxProfile][] = [
|
|
307
|
+
...[...known].filter(([name]) => !taken.has(name)).map(([name, profile]): [string, BoxProfile] => [`profile:${name}`, profile]),
|
|
308
|
+
...[...registry.installations].filter(([owner]) => owner !== input.owner).map(([owner, profile]): [string, BoxProfile] => [`harness:${owner}`, profile]),
|
|
309
|
+
];
|
|
310
|
+
// The toolchains take what each profile of the catalog reads (its program, its configuration), never
|
|
311
|
+
// what it writes: a tool runs, its caches and its credentials stay its own. A host's own profiles
|
|
312
|
+
// are not theirs to open: what one reads may be a token.
|
|
313
|
+
const withToolchains = request.items.some(({ item }) => item === "toolchains");
|
|
314
|
+
for (const [from, profile] of others) {
|
|
315
|
+
const of = profileOf(from, profile);
|
|
316
|
+
const read = withToolchains && from.startsWith("profile:") && registry.catalog.has(from.slice("profile:".length)) ? [] : of.read;
|
|
317
|
+
for (const path of [...read, ...of.write]) {
|
|
318
|
+
if (of.programs.includes(path)) continue;
|
|
319
|
+
if (takenPaths.some((mine) => covers(mine, path))) continue;
|
|
320
|
+
closed.push({ path, from });
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
// The closed list: open only where the box names a place in it, from the host's default or a call.
|
|
324
|
+
const explicitWrites = request.items.flatMap(({ item }) => typeof item === "object" && "write" in item ? [placeOf(item.write, cwd, home)] : []);
|
|
325
|
+
const explicit = request.items.flatMap(({ item }) =>
|
|
326
|
+
typeof item === "object" && !("net" in item) ? [placeOf("read" in item ? item.read : item.write, cwd, home)] : [],
|
|
327
|
+
);
|
|
328
|
+
const always = [
|
|
329
|
+
...[...ALWAYS_CLOSED, ...registry.closed].map((path) => ({ path: realPlace(path, home), from: "closed" })),
|
|
330
|
+
...(input.closed ?? []).map((one) => ({ path: realPlace(one.path, home), from: one.from })),
|
|
331
|
+
];
|
|
332
|
+
for (const one of always) {
|
|
333
|
+
if (explicit.includes(one.path)) continue;
|
|
334
|
+
closed.push(one);
|
|
335
|
+
}
|
|
336
|
+
const closedAt = (place: string) => closed.find((one) => covers(one.path, place));
|
|
337
|
+
|
|
338
|
+
// The items: what each gives, and whether the host's default already gave it.
|
|
339
|
+
const defaults = request.mode === "allow" ? request.items.filter((one) => one.from === "host") : merged(input.defaults, undefined).items;
|
|
340
|
+
const defaultPlaces = (mode: "read" | "write"): string[] =>
|
|
341
|
+
defaults.flatMap(({ item }) => {
|
|
342
|
+
if (item === "project") return [cwd];
|
|
343
|
+
if (typeof item === "string") {
|
|
344
|
+
const profile = known.get(item);
|
|
345
|
+
if (profile === undefined) return [];
|
|
346
|
+
const of = profileOf(`profile:${item}`, profile);
|
|
347
|
+
return mode === "read" ? [...of.read, ...of.write, ...of.programs] : [...of.write];
|
|
348
|
+
}
|
|
349
|
+
if ("net" in item) return [];
|
|
350
|
+
if ("write" in item) return [placeOf(item.write, cwd, home)];
|
|
351
|
+
return mode === "read" ? [placeOf(item.read, cwd, home)] : [];
|
|
352
|
+
});
|
|
353
|
+
const defaultNames = new Set(defaults.flatMap(({ item }) => (typeof item === "string" ? [item] : [])));
|
|
354
|
+
const defaultHosts = new Set(defaults.flatMap(({ item }) => (typeof item === "object" && "net" in item ? [item.net] : [])));
|
|
355
|
+
const rules: string[] = [];
|
|
356
|
+
const needs = (free: boolean, rule: string) => {
|
|
357
|
+
if (!free && !rules.includes(rule)) rules.push(rule);
|
|
358
|
+
};
|
|
359
|
+
|
|
360
|
+
for (const { item, from } of request.items) {
|
|
361
|
+
const fromCall = from === "call";
|
|
362
|
+
if (item === "project") {
|
|
363
|
+
if (input.noProject !== undefined) skipped.push({ place: cwd, from: "project", why: input.noProject });
|
|
364
|
+
else paths.push({ path: cwd, mode: "write", from: "project" });
|
|
365
|
+
if (fromCall) needs(defaultNames.has("project"), "box.use@project");
|
|
366
|
+
} else if (item === "toolchains") {
|
|
367
|
+
for (const [name, profile] of known) {
|
|
368
|
+
if (!registry.catalog.has(name)) continue;
|
|
369
|
+
const of = profileOf(`profile:${name}`, profile);
|
|
370
|
+
for (const path of of.read) if (!of.write.some((written) => covers(written, path))) paths.push({ path, mode: "read", from: "toolchains" });
|
|
371
|
+
}
|
|
372
|
+
for (const place of toolchains(env, home, [...known.keys()])) {
|
|
373
|
+
const inside = closedAt(place.path);
|
|
374
|
+
const holds = closed.find((one) => covers(place.path, one.path));
|
|
375
|
+
if (place.path === "/" || covers(place.path, home)) skipped.push({ place: place.path, from: "toolchains", why: "it holds the home directory" });
|
|
376
|
+
else if (inside !== undefined) skipped.push({ place: place.path, from: "toolchains", why: `it lies in ${inside.path}, which is closed` });
|
|
377
|
+
else if (holds !== undefined && !place.program) skipped.push({ place: place.path, from: "toolchains", why: `it holds ${holds.path}, which is closed` });
|
|
378
|
+
else paths.push({ path: place.path, mode: "read", from: "toolchains" });
|
|
379
|
+
}
|
|
380
|
+
if (fromCall) needs(defaultNames.has("toolchains"), "box.use@toolchains");
|
|
381
|
+
} else if (typeof item === "string") {
|
|
382
|
+
if (fromCall && known.has(item)) needs(defaultNames.has(item), `box.use@${item}`);
|
|
383
|
+
} else if ("net" in item) {
|
|
384
|
+
if (!input.network) {
|
|
385
|
+
refusals.push({ code: "no-network", message: `${item.net} cannot be reached: this box reaches no network` });
|
|
386
|
+
continue;
|
|
387
|
+
}
|
|
388
|
+
net.push({ host: item.net, from });
|
|
389
|
+
if (fromCall) needs(defaultHosts.has(item.net), `box.net@${item.net}`);
|
|
390
|
+
} else {
|
|
391
|
+
const mode = "write" in item ? "write" : "read";
|
|
392
|
+
const place = placeOf("write" in item ? item.write : item.read, cwd, home);
|
|
393
|
+
const inside = closedAt(place);
|
|
394
|
+
if (inside !== undefined && (inside.from.startsWith("profile:") || inside.from.startsWith("harness:"))) {
|
|
395
|
+
const owner = inside.from.slice(inside.from.indexOf(":") + 1);
|
|
396
|
+
const how = inside.from.startsWith("profile:") ? `take the profile ${owner}` : `only the sessions of ${owner} see it`;
|
|
397
|
+
refusals.push({ code: "closed", message: `${place} is a place of ${inside.from}: ${how}` });
|
|
398
|
+
continue;
|
|
399
|
+
}
|
|
400
|
+
paths.push({ path: place, mode, from });
|
|
401
|
+
// A place in the closed list is never the default's to give unless the default names it too.
|
|
402
|
+
const entry = always.find((one) => covers(one.path, place));
|
|
403
|
+
const given = defaultPlaces(mode).filter((one) => entry === undefined || covers(entry.path, one));
|
|
404
|
+
const free = given.some((one) => covers(one, place));
|
|
405
|
+
if (fromCall) needs(free, `box.${mode}@${placeTarget(place)}`);
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
for (const write of input.writes ?? []) paths.push({ path: realPlace(write.path, home), mode: "write", from: write.from });
|
|
409
|
+
if (paths.some((need) => need.mode === "write" && covers(need.path, cwd))) {
|
|
410
|
+
try {
|
|
411
|
+
for (const need of repositoryOf(cwd, input.worktree, paths)) {
|
|
412
|
+
if (!paths.some((one) => one.mode === "write" && covers(one.path, need.path))) paths.push(need);
|
|
413
|
+
}
|
|
414
|
+
} catch (error) {
|
|
415
|
+
if (!(error instanceof BoxRefused)) throw error;
|
|
416
|
+
refusals.push(...error.reasons);
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
for (const place of new Set([cwd, ...paths.map((one) => realPlace(one.path))])) {
|
|
421
|
+
const inside = closedAt(place);
|
|
422
|
+
if (inside) refusals.push({ code: "closed", message: `${place} lies in ${inside.path}, closed by ${inside.from}` });
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
// Opening a closed place for reading cannot also make an overlapping write reachable.
|
|
426
|
+
for (const one of always) {
|
|
427
|
+
if (!explicit.includes(one.path) || explicitWrites.includes(one.path)) continue;
|
|
428
|
+
for (const need of paths) {
|
|
429
|
+
if (need.mode !== "write") continue;
|
|
430
|
+
const place = realPlace(need.path);
|
|
431
|
+
if ((covers(place, one.path) || covers(one.path, place)) && !explicitWrites.some((root) => covers(one.path, root) && covers(root, place))) {
|
|
432
|
+
refusals.push({ code: "closed", message: `${one.path} was opened for reading only; ${place} requires write access` });
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
return { cwd: given, request, paths: distinctNeeds(paths), net: distinctHosts(net), closed, skipped, rules, refusals };
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
/** The needs with each path once, writable when any need writes it, from the first that named it. */
|
|
441
|
+
function distinctNeeds(needs: readonly PathNeed[]): PathNeed[] {
|
|
442
|
+
const out = new Map<string, PathNeed>();
|
|
443
|
+
for (const need of needs) {
|
|
444
|
+
const before = out.get(need.path);
|
|
445
|
+
if (before === undefined) out.set(need.path, need);
|
|
446
|
+
else if (before.mode === "read" && need.mode === "write") out.set(need.path, need);
|
|
447
|
+
}
|
|
448
|
+
return [...out.values()];
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
function distinctHosts(hosts: readonly { host: string; from: Origin }[]): { host: string; from: Origin }[] {
|
|
452
|
+
const seen = new Set<string>();
|
|
453
|
+
return hosts.filter((one) => (seen.has(one.host) ? false : (seen.add(one.host), true)));
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
/** Read a small regular pointer without following links or waiting on special files. */
|
|
457
|
+
function gitPointer(path: string): string {
|
|
458
|
+
const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
459
|
+
try {
|
|
460
|
+
const stat = fstatSync(fd);
|
|
461
|
+
if (!stat.isFile() || stat.size === 0 || stat.size > 8192) throw new Error("invalid Git pointer");
|
|
462
|
+
const buffer = Buffer.alloc(stat.size + 1);
|
|
463
|
+
if (readSync(fd, buffer, 0, buffer.length, 0) !== stat.size) throw new Error("Git pointer changed");
|
|
464
|
+
return buffer.toString("utf8", 0, stat.size);
|
|
465
|
+
} finally {
|
|
466
|
+
closeSync(fd);
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
/** External metadata of a linked checkout. Only a host registration can add a path. */
|
|
471
|
+
export function repositoryOf(dir: string, registered?: PlanInput["worktree"], authorized: readonly PathNeed[] = []): PathNeed[] {
|
|
472
|
+
const refuse = (): never => {
|
|
473
|
+
throw new BoxRefused([{ code: "not-granted", message: `no matching Git worktree registration or explicit access for ${dir}` }]);
|
|
474
|
+
};
|
|
475
|
+
for (let at = dir; ; at = dirname(at)) {
|
|
476
|
+
const dot = join(at, ".git");
|
|
477
|
+
let entry;
|
|
478
|
+
try {
|
|
479
|
+
entry = lstatSync(dot, { throwIfNoEntry: false });
|
|
480
|
+
} catch {
|
|
481
|
+
return refuse();
|
|
482
|
+
}
|
|
483
|
+
const expected = registered?.path === at ? registered : undefined;
|
|
484
|
+
if (expected || entry) {
|
|
485
|
+
if (entry?.isDirectory() && !expected) return [];
|
|
486
|
+
if (!entry?.isFile() || entry.size > 8192) return refuse();
|
|
487
|
+
try {
|
|
488
|
+
const name = /^gitdir: ([^\r\n]+)\r?\n?$/.exec(gitPointer(dot))?.[1];
|
|
489
|
+
if (!name) return refuse();
|
|
490
|
+
const pointed = resolve(at, name);
|
|
491
|
+
if (!expected) {
|
|
492
|
+
if (authorized.some((need) => need.mode === "write" && covers(need.path, realPlace(pointed)))) return [];
|
|
493
|
+
return refuse();
|
|
494
|
+
}
|
|
495
|
+
const { id, repo } = expected;
|
|
496
|
+
if (!isAbsolute(repo) || basename(id) !== id || !id || id === "." || id === "..") return refuse();
|
|
497
|
+
const common = join(repo, ".git");
|
|
498
|
+
const admin = join(common, "worktrees", id);
|
|
499
|
+
if (pointed !== admin || realPlace(admin) !== admin || !statSync(admin).isDirectory()) return refuse();
|
|
500
|
+
const pointer = (file: string) => {
|
|
501
|
+
return resolve(admin, gitPointer(join(admin, file)).trimEnd());
|
|
502
|
+
};
|
|
503
|
+
if (pointer("gitdir") !== dot || pointer("commondir") !== common) return refuse();
|
|
504
|
+
const paths: PathNeed[] = [{ path: admin, mode: "write", from: "repository" }, { path: common, mode: "read", from: "repository" }];
|
|
505
|
+
for (const part of ["objects", "refs", "logs"]) {
|
|
506
|
+
const path = join(common, part);
|
|
507
|
+
const stat = lstatSync(path, { throwIfNoEntry: false });
|
|
508
|
+
if (stat && !stat.isDirectory()) return refuse();
|
|
509
|
+
paths.push({ path, mode: "write", from: "repository" });
|
|
510
|
+
}
|
|
511
|
+
return paths;
|
|
512
|
+
} catch {
|
|
513
|
+
return refuse();
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
if (dirname(at) === at) return [];
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
/** The places `toolchains` reads: the PATH, Homebrew, and the programs of every profile a box may ask for. */
|
|
521
|
+
function toolchains(env: Readonly<Record<string, string | undefined>>, home: string, names: readonly string[]): { path: string; program: boolean }[] {
|
|
522
|
+
const dirs = [...(env["PATH"] ?? "").split(":"), ...homebrewPrefix(env)].filter((dir) => isAbsolute(dir));
|
|
523
|
+
const out: { path: string; program: boolean }[] = [];
|
|
524
|
+
const seen = new Set<string>();
|
|
525
|
+
const add = (path: string, program: boolean) => {
|
|
526
|
+
const real = program ? linkPlace(path, home) : realPlace(path, home);
|
|
527
|
+
if (seen.has(real)) return;
|
|
528
|
+
seen.add(real);
|
|
529
|
+
out.push({ path: real, program });
|
|
530
|
+
};
|
|
531
|
+
for (const dir of dirs) if (exists(dir)) add(dir, false);
|
|
532
|
+
for (const name of names) for (const path of programPaths(name, env)) add(path, true);
|
|
533
|
+
return out;
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
function exists(path: string): boolean {
|
|
537
|
+
try {
|
|
538
|
+
return statSync(path).isDirectory();
|
|
539
|
+
} catch {
|
|
540
|
+
return false;
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
/** The spec a plan makes, with what the box is started with besides. */
|
|
545
|
+
export function planSpec(plan: BoxPlan, extra: { readonly env?: Readonly<Record<string, string>>; readonly sockets?: readonly string[] } = {}): BoxSpec {
|
|
546
|
+
return boxSpec({
|
|
547
|
+
cwd: plan.cwd,
|
|
548
|
+
read: plan.paths.filter((need) => need.mode === "read").map((need) => need.path),
|
|
549
|
+
write: plan.paths.filter((need) => need.mode === "write").map((need) => need.path),
|
|
550
|
+
closed: [...new Set(plan.closed.map((one) => one.path))],
|
|
551
|
+
net: plan.net.map((one) => one.host),
|
|
552
|
+
env: { ...extra.env },
|
|
553
|
+
sockets: [...(extra.sockets ?? [])],
|
|
554
|
+
});
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
/** The policy as a record holds it. */
|
|
558
|
+
export const BoxPolicySchema = z.object({
|
|
559
|
+
write: z.array(z.string()),
|
|
560
|
+
devices: z.array(z.string()),
|
|
561
|
+
read: z.union([z.object({ only: z.array(z.string()) }), z.object({ except: z.array(z.string()) })]),
|
|
562
|
+
net: z.array(z.string()),
|
|
563
|
+
});
|
|
564
|
+
|
|
565
|
+
/**
|
|
566
|
+
* The manifest of a box, as it is recorded: the request with where each item came from, the paths
|
|
567
|
+
* it resolved to and where each came from, what was closed and left out, the rules of the grant it
|
|
568
|
+
* took, and the policy the sandbox reports it applies. The environment is its names, never a value.
|
|
569
|
+
*/
|
|
570
|
+
export const BoxManifestSchema = z.object({
|
|
571
|
+
sandbox: z.string().min(1),
|
|
572
|
+
/** The working directory of the box. */
|
|
573
|
+
cwd: z.string().min(1),
|
|
574
|
+
request: z.object({
|
|
575
|
+
mode: z.enum(["allow", "only"]),
|
|
576
|
+
items: z.array(z.object({ item: AccessItemSchema, from: z.enum(["host", "call"]) })),
|
|
577
|
+
}),
|
|
578
|
+
paths: z.array(z.object({ path: z.string(), mode: z.enum(["read", "write"]), from: z.string() })),
|
|
579
|
+
net: z.array(z.object({ host: z.string(), from: z.string() })),
|
|
580
|
+
closed: z.array(z.object({ path: z.string(), from: z.string() })),
|
|
581
|
+
skipped: z.array(z.object({ place: z.string(), from: z.string(), why: z.string() })),
|
|
582
|
+
rules: z.array(z.string()),
|
|
583
|
+
policy: BoxPolicySchema,
|
|
584
|
+
env: z.array(EnvNameSchema),
|
|
585
|
+
});
|
|
586
|
+
export type BoxManifest = z.output<typeof BoxManifestSchema>;
|
|
587
|
+
|
|
588
|
+
/** The manifest of a box from its plan, the grant's rules it took, and what the sandbox reports. */
|
|
589
|
+
export function boxManifest(plan: BoxPlan, rules: readonly string[], made: SandboxManifest): BoxManifest {
|
|
590
|
+
const policy: BoxPolicy = made.policy ?? { write: [], devices: [], read: { except: [] }, net: [] };
|
|
591
|
+
return {
|
|
592
|
+
sandbox: made.sandbox,
|
|
593
|
+
cwd: plan.cwd,
|
|
594
|
+
request: { mode: plan.request.mode, items: plan.request.items.map((one) => ({ item: one.item, from: one.from })) },
|
|
595
|
+
paths: [...plan.paths],
|
|
596
|
+
net: [...plan.net],
|
|
597
|
+
closed: [...plan.closed],
|
|
598
|
+
skipped: [...plan.skipped],
|
|
599
|
+
rules: [...rules],
|
|
600
|
+
policy: {
|
|
601
|
+
write: [...policy.write],
|
|
602
|
+
devices: [...policy.devices],
|
|
603
|
+
read: "only" in policy.read ? { only: [...policy.read.only] } : { except: [...policy.read.except] },
|
|
604
|
+
net: [...policy.net],
|
|
605
|
+
},
|
|
606
|
+
env: Object.keys(made.env).map((name) => EnvNameSchema.parse(name)),
|
|
607
|
+
};
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
/**
|
|
611
|
+
* Admits a plan into a sandbox, or refuses it with every reason at once: what kept the plan from
|
|
612
|
+
* being a box, each rule the grant lacks, and whatever the sandbox cannot hold. `held` answers, for
|
|
613
|
+
* a rule the plan needs, the rule of the grant that covers it, or undefined.
|
|
614
|
+
*/
|
|
615
|
+
export function admit(
|
|
616
|
+
plan: BoxPlan,
|
|
617
|
+
sandbox: Sandbox,
|
|
618
|
+
held: (rule: string) => string | undefined,
|
|
619
|
+
extra: { readonly env?: Readonly<Record<string, string>>; readonly sockets?: readonly string[] } = {},
|
|
620
|
+
): { readonly spec: BoxSpec; readonly manifest: SandboxManifest; readonly rules: readonly string[] } {
|
|
621
|
+
const reasons: BoxRefusal[] = [...plan.refusals];
|
|
622
|
+
const used: string[] = [];
|
|
623
|
+
for (const rule of plan.rules) {
|
|
624
|
+
const by = held(rule);
|
|
625
|
+
if (by === undefined) reasons.push({ code: "not-granted", message: `it is wider than the host's default and the grant has no ${rule}`, rule });
|
|
626
|
+
else if (!used.includes(by)) used.push(by);
|
|
627
|
+
}
|
|
628
|
+
const spec = planSpec(plan, extra);
|
|
629
|
+
for (const socket of spec.sockets) {
|
|
630
|
+
const place = placeOf(socket, plan.cwd, homedir());
|
|
631
|
+
if (plan.closed.some((one) => covers(one.path, place))) reasons.push({ code: "closed", message: `socket ${socket} lies in a closed directory` });
|
|
632
|
+
}
|
|
633
|
+
let manifest: SandboxManifest | undefined;
|
|
634
|
+
try {
|
|
635
|
+
manifest = sandbox.manifest(spec);
|
|
636
|
+
} catch (error) {
|
|
637
|
+
if (!(error instanceof BoxRefused)) throw error;
|
|
638
|
+
reasons.push(...error.reasons);
|
|
639
|
+
}
|
|
640
|
+
if (reasons.length > 0 || manifest === undefined) throw new BoxRefused(reasons, sandbox.name);
|
|
641
|
+
return { spec, manifest, rules: used };
|
|
642
|
+
}
|