@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.
@@ -0,0 +1,327 @@
1
+ // The process of a boxed launch.
2
+ //
3
+ // What it proves:
4
+ // 1. a boxed launch that asks to be detached leads its own process group, and a signal sent to
5
+ // the process reaches the wrapper as that signal
6
+ // 2. a box's output is read at the pace of its reader
7
+ // 3. a clean-up that fails ends the process with an exit and an error, not an unhandled rejection
8
+ // 4. a listener that comes after the box ended is still told of the exit and the close
9
+ // 5. a relative path of a spec is read from its working directory, in the flags and in the check
10
+ // 6. a wrapper that is not there is `SandboxUnavailable`, not a bare ENOENT
11
+ // 7. a reader that closes its end does not keep the process from closing
12
+ // 8. a launch that fails behind the returned process is told to a late listener, and never throws
13
+ // 9. a process ended by a signal reports the signal and no code; an exit with a signal's code is a code
14
+ //
15
+ // Only the public API is used: "@niwa-labs/sandbox".
16
+
17
+ import { afterEach, expect, test } from "bun:test";
18
+ import { chmod, writeFile } from "node:fs/promises";
19
+ import { join, resolve } from "node:path";
20
+ import { setTimeout as sleep } from "node:timers/promises";
21
+
22
+ import { SandboxUnavailable, BoxRefused, boxSpec, nono, spawnAgent, spawnAgentNow, srt, useSandbox } from "@niwa-labs/sandbox";
23
+ import type { AgentProcess, LaunchedBox, Sandbox } from "@niwa-labs/sandbox";
24
+ import { tempDir } from "@niwa-labs/testing";
25
+
26
+ const undo: Array<() => void> = [];
27
+
28
+ afterEach(() => {
29
+ for (const restore of undo.splice(0)) restore();
30
+ });
31
+
32
+ /** A wrapper that confines nothing: it drops its own flags and runs what follows `--`. */
33
+ async function passthroughBinary(dir: string): Promise<string> {
34
+ const path = join(dir, "wrapper");
35
+ // Asked how it resolves its profile, it grants nothing; asked to run, it runs what follows `--`.
36
+ await writeFile(
37
+ path,
38
+ '#!/bin/sh\nif [ "$1" = profile ]; then echo \'{"filesystem":{"grants":[]}}\'; exit 0; fi\nwhile [ "$1" != "--" ]; do shift; done\nshift\nexec "$@"\n',
39
+ );
40
+ await chmod(path, 0o755);
41
+ return path;
42
+ }
43
+
44
+ async function boxed(program: string, args: string[], detached: boolean): Promise<AgentProcess> {
45
+ const dir = await tempDir("box-process");
46
+ undo.push(useSandbox("nono", nono({ binary: await passthroughBinary(dir) })));
47
+ return await spawnAgent({
48
+ harness: "t",
49
+ program,
50
+ args,
51
+ cwd: dir,
52
+ env: { PATH: process.env["PATH"] ?? "/usr/bin:/bin" },
53
+ detached,
54
+ box: { sandbox: "nono", spec: { cwd: dir } },
55
+ });
56
+ }
57
+
58
+ function lines(child: AgentProcess): { next(): Promise<string> } {
59
+ let text = "";
60
+ const waiting: Array<() => void> = [];
61
+ child.stdout.setEncoding("utf8");
62
+ child.stdout.on("data", (chunk: string) => {
63
+ text += chunk;
64
+ for (const wake of waiting.splice(0)) wake();
65
+ });
66
+ return {
67
+ async next() {
68
+ while (!text.includes("\n")) await new Promise<void>((resolve) => waiting.push(resolve));
69
+ const at = text.indexOf("\n");
70
+ const line = text.slice(0, at);
71
+ text = text.slice(at + 1);
72
+ return line;
73
+ },
74
+ };
75
+ }
76
+
77
+ function alive(pid: number): boolean {
78
+ try {
79
+ process.kill(pid, 0);
80
+ return true;
81
+ } catch {
82
+ return false;
83
+ }
84
+ }
85
+
86
+ test("a detached boxed process leads its group, so a signal to the group reaches what it started", async () => {
87
+ const child = await boxed("/bin/sh", ["-c", "sleep 60 & echo $!; wait"], true);
88
+ const output = lines(child);
89
+ const grandchild = Number(await output.next());
90
+ try {
91
+ expect(alive(grandchild)).toBe(true);
92
+ // The wrapper's own pid names the group: this throws ESRCH when the process is not its leader.
93
+ process.kill(-child.pid!, "SIGKILL");
94
+ for (let tries = 0; tries < 100 && alive(grandchild); tries++) await sleep(20);
95
+ expect(alive(grandchild)).toBe(false);
96
+ } finally {
97
+ if (alive(grandchild)) process.kill(grandchild, "SIGKILL");
98
+ }
99
+ });
100
+
101
+ test("the signal given to kill reaches the boxed process", async () => {
102
+ const child = await boxed("/bin/sh", ["-c", "trap 'echo got; exit 7' USR1; echo ready; while :; do sleep 0.1; done"], false);
103
+ const output = lines(child);
104
+ expect(await output.next()).toBe("ready");
105
+ const codes: Array<number | null> = [];
106
+ child.on("exit", (code) => codes.push(code));
107
+ expect(child.kill("SIGUSR1")).toBe(true);
108
+ expect(await output.next()).toBe("got");
109
+ await new Promise<void>((resolve) => child.once("close", () => resolve()));
110
+ expect(codes).toEqual([7]);
111
+ });
112
+
113
+ /** A sandbox that runs nothing: its box is what the test makes of it. */
114
+ function fake(box: () => LaunchedBox): Sandbox {
115
+ return {
116
+ name: "nono",
117
+ class: "process",
118
+ available: async () => true,
119
+ manifest: (spec) => ({ sandbox: "nono", cwd: spec.cwd, env: spec.env }),
120
+ launch: async () => box(),
121
+ };
122
+ }
123
+
124
+ const bytes = (size: number) => new Uint8Array(size).fill(97);
125
+ const inert = { write: () => undefined, end: () => undefined };
126
+
127
+ async function spawnFake(box: () => LaunchedBox): Promise<AgentProcess> {
128
+ undo.push(useSandbox("nono", fake(box)));
129
+ return await spawnAgent({ harness: "t", program: "unused", args: [], cwd: "/", box: { sandbox: "nono", spec: { cwd: "/" } } });
130
+ }
131
+
132
+ test("a box's output is read at the pace of its reader", async () => {
133
+ const chunk = 8192;
134
+ const chunks = 2000;
135
+ let pulled = 0;
136
+ const stdout = new ReadableStream<Uint8Array>({
137
+ pull(controller) {
138
+ pulled++;
139
+ if (pulled > chunks) controller.close();
140
+ else controller.enqueue(bytes(chunk));
141
+ },
142
+ });
143
+ const child = await spawnFake(() => ({
144
+ pid: 1,
145
+ stdin: inert,
146
+ stdout,
147
+ stderr: new ReadableStream<Uint8Array>({ start: (controller) => controller.close() }),
148
+ exited: Promise.resolve(0),
149
+ kill: () => undefined,
150
+ }));
151
+ // Nobody reads yet: only what the stream holds is taken from the box.
152
+ await sleep(100);
153
+ expect(pulled).toBeLessThan(50);
154
+
155
+ let received = 0;
156
+ child.stdout.on("data", (data: Buffer) => {
157
+ received += data.length;
158
+ });
159
+ await new Promise<void>((resolve) => child.once("close", () => resolve()));
160
+ expect(received).toBe(chunk * chunks);
161
+ });
162
+
163
+ test("a clean-up that fails ends the process with an exit and an error, not an unhandled rejection", async () => {
164
+ const unhandled: unknown[] = [];
165
+ const hear = (reason: unknown) => unhandled.push(reason);
166
+ process.on("unhandledRejection", hear);
167
+ try {
168
+ const child = await spawnFake(() => ({
169
+ pid: 1,
170
+ stdin: inert,
171
+ stdout: new ReadableStream<Uint8Array>({ start: (controller) => controller.close() }),
172
+ stderr: new ReadableStream<Uint8Array>({ start: (controller) => controller.close() }),
173
+ exited: Promise.reject(new Error("the settings could not be removed")),
174
+ kill: () => undefined,
175
+ }));
176
+ const heard: string[] = [];
177
+ child.on("exit", (code) => heard.push(`exit ${code}`));
178
+ child.on("error", (error) => heard.push(`error ${error.message}`));
179
+ await new Promise<void>((resolve) => child.once("close", () => resolve()));
180
+ await sleep(20);
181
+ expect(heard).toEqual(["exit null", "error the settings could not be removed"]);
182
+ expect(unhandled).toEqual([]);
183
+ } finally {
184
+ process.off("unhandledRejection", hear);
185
+ }
186
+ });
187
+
188
+ test("a failed clean-up with nobody listening for errors does not throw", async () => {
189
+ const child = await spawnFake(() => ({
190
+ pid: 1,
191
+ stdin: inert,
192
+ stdout: new ReadableStream<Uint8Array>({ start: (controller) => controller.close() }),
193
+ stderr: new ReadableStream<Uint8Array>({ start: (controller) => controller.close() }),
194
+ exited: Promise.reject(new Error("gone")),
195
+ kill: () => undefined,
196
+ }));
197
+ const code = await new Promise<number | null>((resolve) => child.once("close", (code) => resolve(code)));
198
+ expect(code).toBeNull();
199
+ });
200
+
201
+ test("a listener that comes after the box ended is told of the exit and the close", async () => {
202
+ const child = await spawnFake(() => ({
203
+ pid: 1,
204
+ stdin: inert,
205
+ stdout: new ReadableStream<Uint8Array>({ start: (controller) => controller.close() }),
206
+ stderr: new ReadableStream<Uint8Array>({ start: (controller) => controller.close() }),
207
+ exited: Promise.resolve(5),
208
+ kill: () => undefined,
209
+ }));
210
+ const told = Promise.all([
211
+ new Promise<number | null>((resolve) => child.once("exit", (code) => resolve(code))),
212
+ new Promise<number | null>((resolve) => child.once("close", (code) => resolve(code))),
213
+ ]);
214
+ expect(await Promise.race([told, sleep(2000).then(() => "silent")])).toEqual([5, 5]);
215
+ expect(child.exitCode).toBe(5);
216
+ });
217
+
218
+ test("relative paths of a spec are read from its working directory, for the flags and for the check", () => {
219
+ const cwd = "/niwa-absent-base/work";
220
+ expect(() => nono().manifest(boxSpec({ cwd, closed: ["secret"] }))).toThrow(BoxRefused);
221
+ expect(() => nono().manifest(boxSpec({ cwd, write: ["out"], closed: ["out/key"] }))).toThrow(BoxRefused);
222
+ // Away from the cwd it is not in the way, wherever the host is.
223
+ expect(() => nono().manifest(boxSpec({ cwd, closed: ["../secret"] }))).not.toThrow();
224
+
225
+ const flags = nono().manifest(boxSpec({ cwd, read: ["lib"], write: ["out"], sockets: ["run/host.sock"] })).flags;
226
+ expect(flags).toEqual([
227
+ "--silent",
228
+ "--read", cwd,
229
+ "--read", `${cwd}/lib`,
230
+ "--allow", `${cwd}/out`,
231
+ "--allow-unix-socket", `${cwd}/run/host.sock`,
232
+ "--block-net",
233
+ ]);
234
+
235
+ const settings = srt().manifest(boxSpec({ cwd, write: ["out", "~/.claude"], closed: ["secret"], sockets: ["run/host.sock"] })).settings;
236
+ expect(settings.filesystem).toEqual({
237
+ denyRead: [{ path: `${cwd}/secret`, literal: true }],
238
+ allowWrite: [
239
+ { path: `${cwd}/out`, literal: true },
240
+ { path: "~/.claude", literal: true },
241
+ ],
242
+ denyWrite: [{ path: `${cwd}/secret`, literal: true }],
243
+ });
244
+ expect(settings.network.allowUnixSockets).toEqual([`${cwd}/run/host.sock`]);
245
+ });
246
+
247
+ test("a relative working directory is resolved once, against the host's", () => {
248
+ const manifest = nono().manifest(boxSpec({ cwd: "work", write: ["out"] }));
249
+ expect(manifest.cwd).toBe(resolve("work"));
250
+ expect(manifest.flags).toContain(resolve("work", "out"));
251
+ });
252
+
253
+ test("a wrapper that is not there is SandboxUnavailable, and a working directory that is not there is not", async () => {
254
+ const spec = boxSpec({ cwd: await tempDir("box-missing") });
255
+ await expect(nono({ binary: "/nonexistent/nono" }).launch(spec, ["true"])).rejects.toBeInstanceOf(SandboxUnavailable);
256
+ await expect(srt({ command: ["/nonexistent/srt"] }).launch(spec, ["true"])).rejects.toBeInstanceOf(SandboxUnavailable);
257
+
258
+ const present = nono({ binary: await passthroughBinary(await tempDir("box-wrapper")) });
259
+ const failure = await present.launch(boxSpec({ cwd: "/niwa-absent-base/work" }), ["true"]).then(
260
+ () => undefined,
261
+ (error: unknown) => error,
262
+ );
263
+ expect(failure).toBeInstanceOf(Error);
264
+ expect(failure).not.toBeInstanceOf(SandboxUnavailable);
265
+ });
266
+
267
+ test("a reader that closes its end does not keep the process from closing", async () => {
268
+ // Output keeps coming after the reader has gone, so a write finds the stream closed already.
269
+ let pulled = 0;
270
+ const stdout = new ReadableStream<Uint8Array>({
271
+ async pull(controller) {
272
+ await sleep(20);
273
+ controller.enqueue(bytes(1024));
274
+ if (++pulled >= 5) controller.close();
275
+ },
276
+ });
277
+ const child = await spawnFake(() => ({
278
+ pid: 1,
279
+ stdin: inert,
280
+ stdout,
281
+ stderr: new ReadableStream<Uint8Array>({ start: (controller) => controller.close() }),
282
+ exited: Promise.resolve(0),
283
+ kill: () => undefined,
284
+ }));
285
+ // The reader gives up on the stream with an error it has heard already: no event is left to come.
286
+ child.stdout.on("error", () => undefined);
287
+ child.stdout.destroy(new Error("the reader is gone"));
288
+ child.stderr.destroy();
289
+ const closed = new Promise<string>((resolve) => child.once("close", () => resolve("closed")));
290
+ expect(await Promise.race([closed, sleep(2000).then(() => "silent")])).toBe("closed");
291
+ });
292
+
293
+ test("a launch that fails behind the returned process is told to a late listener as well, and does not throw", async () => {
294
+ undo.push(
295
+ useSandbox("nono", {
296
+ ...fake(() => {
297
+ throw new Error("unused");
298
+ }),
299
+ launch: async () => {
300
+ throw new Error("the box could not start");
301
+ },
302
+ }),
303
+ );
304
+ const child = spawnAgentNow({ harness: "t", program: "unused", args: [], cwd: "/", box: { sandbox: "nono", spec: { cwd: "/" } } });
305
+ // Only `close` is heard: with no `error` listener the failure must not be thrown.
306
+ const early = new Promise<string>((resolve) => child.once("close", () => resolve("closed")));
307
+ expect(await Promise.race([early, sleep(2000).then(() => "silent")])).toBe("closed");
308
+
309
+ const late: string[] = [];
310
+ child.once("error", (error) => late.push(`error ${error.message}`));
311
+ child.once("close", () => late.push("close"));
312
+ await sleep(50);
313
+ expect(late).toEqual(["error the box could not start", "close"]);
314
+ });
315
+
316
+ test("a process ended by a signal reports the signal and no code; an exit with a signal's code is a code", async () => {
317
+ const signalled = await boxed("/bin/sh", ["-c", "kill -TERM $$"], false);
318
+ const ended = await new Promise<[number | null, NodeJS.Signals | null]>((resolve) => signalled.once("close", (code, signal) => resolve([code, signal])));
319
+ expect(ended).toEqual([null, "SIGTERM"]);
320
+ expect(signalled.exitCode).toBeNull();
321
+ expect(signalled.signalCode).toBe("SIGTERM");
322
+
323
+ const exited = await boxed("/bin/sh", ["-c", "exit 143"], false);
324
+ const code = await new Promise<[number | null, NodeJS.Signals | null]>((resolve) => exited.once("close", (code, signal) => resolve([code, signal])));
325
+ expect(code).toEqual([143, null]);
326
+ expect(exited.signalCode).toBeNull();
327
+ });
@@ -0,0 +1,144 @@
1
+ // The environment of the process that starts a box, and the environment of the command inside it.
2
+ //
3
+ // What it proves, for srt and for nono:
4
+ // 1. the wrapper that applies the restrictions runs with an environment the host defines, never
5
+ // with what the spec lists for the command: a variable that makes a program load code, or the
6
+ // PATH its tools are found by, is the caller's to set only for the command
7
+ // 2. the command gets the environment the spec lists, and the host's own PATH is not among it
8
+ // 3. a program name that `env` would read as a variable is refused before anything starts
9
+ // 4. the wrapper starts from a directory of the host's, not the command's, and the command still
10
+ // starts in its own
11
+ // 5. the values of the command's environment are in no command line while the box runs
12
+
13
+ import { chmod, readFile, writeFile } from "node:fs/promises";
14
+ import { realpath } from "node:fs/promises";
15
+ import { homedir } from "node:os";
16
+ import { join } from "node:path";
17
+ import { expect, test } from "bun:test";
18
+
19
+ import { BoxRefused, boxSpec, nono, srt } from "@niwa-labs/sandbox";
20
+ import type { Sandbox } from "@niwa-labs/sandbox";
21
+ import { tempDir } from "@niwa-labs/testing";
22
+
23
+ /** A wrapper that confines nothing: it writes down its own environment, then runs what follows `--`. */
24
+ async function recordingWrapper(dir: string): Promise<{ path: string; seen: string }> {
25
+ const path = join(dir, "wrapper");
26
+ const seen = join(dir, "wrapper-env");
27
+ await writeFile(path, `#!/bin/sh\nenv > '${seen}'\npwd -P > '${seen}-cwd'\nwhile [ "$1" != "--" ]; do shift; done\nshift\nexec "$@"\n`);
28
+ await chmod(path, 0o755);
29
+ return { path, seen };
30
+ }
31
+
32
+ async function wrapped(): Promise<Array<{ sandbox: Sandbox; seen: string; dir: string }>> {
33
+ const made: Array<{ sandbox: Sandbox; seen: string; dir: string }> = [];
34
+ {
35
+ const dir = await tempDir("launcher-env-nono");
36
+ const wrapper = await recordingWrapper(dir);
37
+ made.push({ sandbox: nono({ binary: wrapper.path }), seen: wrapper.seen, dir });
38
+ }
39
+ {
40
+ const dir = await tempDir("launcher-env-srt");
41
+ const wrapper = await recordingWrapper(dir);
42
+ made.push({ sandbox: srt({ command: [wrapper.path] }), seen: wrapper.seen, dir });
43
+ }
44
+ return made;
45
+ }
46
+
47
+ const HOSTILE = { NODE_OPTIONS: "--require /evil.js", BUN_OPTIONS: "--preload /evil.js", DYLD_LIBRARY_PATH: "/evil", LD_PRELOAD: "/evil.so" };
48
+
49
+ async function ran(sandbox: Sandbox, spec: Parameters<Sandbox["launch"]>[0], argv: string[]) {
50
+ const box = await sandbox.launch(spec, argv);
51
+ box.stdin.end();
52
+ const [stdout, code] = await Promise.all([new Response(box.stdout).text(), box.exited]);
53
+ return { stdout, code };
54
+ }
55
+
56
+ test("the wrapper that applies the restrictions runs with the host's environment, not the command's", async () => {
57
+ for (const { sandbox, seen, dir } of await wrapped()) {
58
+ const spec = boxSpec({ cwd: dir, env: { ...HOSTILE, PATH: "/custom/bin:/usr/bin:/bin", MARKER: "for-the-command" } });
59
+ const result = await ran(sandbox, spec, ["/usr/bin/env"]);
60
+ expect(result.code).toBe(0);
61
+
62
+ const wrapperEnv = Object.fromEntries((await readFile(seen, "utf8")).split("\n").filter(Boolean).map((line) => [line.slice(0, line.indexOf("=")), line.slice(line.indexOf("=") + 1)]));
63
+ for (const name of [...Object.keys(HOSTILE), "MARKER"]) expect(wrapperEnv[name]).toBeUndefined();
64
+ expect(wrapperEnv["PATH"]).toBe("/usr/bin:/bin");
65
+ // Besides the host's own names, only the command's values, under the names they travel by.
66
+ expect(Object.keys(wrapperEnv).every((name) => ["PATH", "HOME", "PWD", "SHLVL", "_", "OLDPWD"].includes(name) || name.startsWith("NIWA_BOX__"))).toBe(true);
67
+
68
+ for (const [name, value] of Object.entries(HOSTILE)) expect(result.stdout).toContain(`${name}=${value}`);
69
+ expect(result.stdout).toContain("MARKER=for-the-command");
70
+ expect(result.stdout).toContain("PATH=/custom/bin:/usr/bin:/bin");
71
+ }
72
+ });
73
+
74
+ test("the command is found by the PATH the spec lists, and gets no variable of the launcher that the spec leaves out", async () => {
75
+ for (const { sandbox, seen, dir } of await wrapped()) {
76
+ const tools = join(dir, "tools");
77
+ await Bun.$`mkdir -p ${tools}`.quiet();
78
+ await writeFile(join(tools, "mytool"), "#!/bin/sh\necho tool-ran\n");
79
+ await chmod(join(tools, "mytool"), 0o755);
80
+ const spec = boxSpec({ cwd: dir, env: { PATH: `${tools}:/usr/bin:/bin` } });
81
+ const found = await ran(sandbox, spec, ["mytool"]);
82
+ expect(found.stdout).toBe("tool-ran\n");
83
+
84
+ const bare = await ran(sandbox, boxSpec({ cwd: dir, env: { PATH: "/usr/bin:/bin" } }), ["/usr/bin/env"]);
85
+ expect(bare.stdout).not.toContain(`HOME=${homedir()}`);
86
+ expect(await readFile(seen, "utf8")).toContain("PATH=/usr/bin:/bin");
87
+ }
88
+ });
89
+
90
+ test("a program whose name `env` would read as a variable is refused", async () => {
91
+ for (const { sandbox, dir } of await wrapped()) {
92
+ await expect(sandbox.launch(boxSpec({ cwd: dir }), ["FOO=bar", "x"])).rejects.toBeInstanceOf(BoxRefused);
93
+ }
94
+ });
95
+
96
+ test("the wrapper starts from a directory of the host's, and the command starts in its own", async () => {
97
+ for (const { sandbox, seen, dir } of await wrapped()) {
98
+ const cwd = join(dir, "work");
99
+ await Bun.$`mkdir -p ${cwd}`.quiet();
100
+ const result = await ran(sandbox, boxSpec({ cwd, env: { PATH: "/usr/bin:/bin" } }), ["/bin/pwd", "-P"]);
101
+ expect(result.stdout.trim()).toBe(await realpath(cwd));
102
+ const wrapperCwd = (await readFile(`${seen}-cwd`, "utf8")).trim();
103
+ expect(wrapperCwd.startsWith(await realpath(dir))).toBe(false);
104
+ }
105
+ });
106
+
107
+ test("the values of the command's environment are in no command line while the box runs", async () => {
108
+ // A wrapper that stays alive around the command, as srt and nono do, so its command line can be read.
109
+ const dir = await tempDir("launcher-env-argv");
110
+ const path = join(dir, "waiting");
111
+ await writeFile(path, '#!/bin/sh\nwhile [ "$1" != "--" ]; do shift; done\nshift\n"$@"\nexit $?\n');
112
+ await chmod(path, 0o755);
113
+ // Built here, so that no command line of this run spells it out before the box does.
114
+ const secret = ["x9q7", "secret", "value"].join("-");
115
+ for (const sandbox of [nono({ binary: path }), srt({ command: [path] })]) {
116
+ const box = await sandbox.launch(boxSpec({ cwd: dir, env: { PATH: "/usr/bin:/bin", NIWA_SECRET: secret } }), ["/bin/sh", "-c", 'echo "$NIWA_SECRET"; sleep 1']);
117
+ const reader = box.stdout.getReader();
118
+ expect(new TextDecoder().decode((await reader.read()).value).trim()).toBe(secret);
119
+ const processes = await Bun.$`ps -axww -o args=`.text();
120
+ expect(processes).not.toContain(secret);
121
+ expect(processes).toContain("niwa-box");
122
+ await box.exited;
123
+ }
124
+ });
125
+
126
+ test("nono is given its profile as a file only the host can read, and the file is gone once the box has ended", async () => {
127
+ const dir = await tempDir("nono-profile-file");
128
+ const path = join(dir, "wrapper");
129
+ const seen = join(dir, "profile-path");
130
+ // Writes down the file named after `--profile` and what it holds, then runs what follows `--`.
131
+ await writeFile(
132
+ path,
133
+ `#!/bin/sh\nwhile [ "$1" != "--profile" ]; do shift; done\nprintf %s "$2" > '${seen}'\ncat "$2" > '${seen}-content'\n(stat -c %a "$2" || stat -f %Lp "$2") > '${seen}-mode' 2>/dev/null\nwhile [ "$1" != "--" ]; do shift; done\nshift\nexec "$@"\n`,
134
+ );
135
+ await chmod(path, 0o755);
136
+ const sandbox = nono({ binary: path });
137
+ const spec = boxSpec({ cwd: dir, env: { PATH: "/usr/bin:/bin" } });
138
+ const result = await ran(sandbox, spec, ["/usr/bin/true"]);
139
+ expect(result.code).toBe(0);
140
+ const profile = await readFile(seen, "utf8");
141
+ expect(JSON.parse(await readFile(`${seen}-content`, "utf8"))).toEqual(JSON.parse(JSON.stringify(sandbox.manifest(spec).profile)));
142
+ expect((await readFile(`${seen}-mode`, "utf8")).trim()).toBe("600");
143
+ expect(await Bun.file(profile).exists()).toBe(false);
144
+ });