Public: anyone can read this; the crew can change it.

The crew's shell sandbox has a boundary test that names each path it denies and fails when one becomes readable #15985

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

mason/forge:mason/15968-the-crew-s-shell-sandbox-has-a-boundary → main 0 commits fork

  • Merged. mason/15968-the-crew-s-shell-sandbox-has-a-boundary was merged into main as 5c8917f.

Review

Sign in to review this change.
2 files changed +185 −2
src/crew/sandbox.ts +7 −2
@@ -196,8 +196,13 @@ function tempDenied(data: string, tmpDir: string | undefined, temp: string): str
196196 ];
197197 }
198198
199 /** Denied by name whatever the listing says: what must never be read. */
200 const ALWAYS_DENIED = [
199 /**
200 * Denied by name whatever the listing says: what must never be read, each a
201 * name under the data directory. The one list: `test/crew-sandbox-boundary.test.ts`
202 * reads it and tries every entry from a real sandboxed shell, so a new
203 * denial is one line here and is tried without touching the test.
204 */
205 export const ALWAYS_DENIED: readonly string[] = [
201206 "repos",
202207 "forge.db",
203208 "forge.db-wal",
test/crew-sandbox-boundary.test.ts added +178
@@ -0,0 +1,178 @@
1 /**
2 * The crew shell's boundary, one path at a time (#15968). The paths are read
3 * from the one list the sandbox denies by name (`ALWAYS_DENIED` in
4 * `src/crew/sandbox.ts`: the database and its journals, the secret key, the
5 * repositories, …), plus two run directories that are not the shell's own:
6 * another agent's clone and this agent's other run's temp directory. A new
7 * denial is one line in that list and is tried here without touching this
8 * file. Paths are made under a fresh data directory, never the host's, so the
9 * check cell and production differ in nothing this test reads.
10 *
11 * Two halves. The policy half runs everywhere: `sandboxPolicy` must name each
12 * path in `denyRead` even when the data directory is empty, since the floor
13 * is denied by name and not by listing. The shell half starts a real shell
14 * under the settings the crew hands Claude Code (`claudeSettings`), through
15 * Claude Code's own runtime (`srt`), and tries to read each path; every path
16 * is its own test, so a failure names the path that became readable.
17 *
18 * The shell half is skipped, naming itself and why on the console, in the
19 * two places it truly cannot run: where no sandbox can be made (a crew run is
20 * already inside one, or user namespaces are refused: `sandboxCause`), and in
21 * FORGE_TEST_SOCKET mode, where unix sockets cannot be bound and `srt` binds
22 * one for each bridge to its network proxy. The forge's check runs it.
23 */
24 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
25 import { existsSync, mkdirSync, writeFileSync } from "node:fs";
26 import { mkdtemp, rm } from "node:fs/promises";
27 import { tmpdir } from "node:os";
28 import { join } from "node:path";
29 import { rgPath } from "@vscode/ripgrep";
30 import { claudeSettings } from "../src/crew/claude.ts";
31 import { ALWAYS_DENIED, sandboxAvailable, sandboxPolicy } from "../src/crew/sandbox.ts";
32 import { sandboxCause, skipReason } from "../src/crew/sandbox_cause.ts";
33 import { runtimeSettings, srtEnv } from "./helpers/srt.ts";
34
35 const CANARY = "the-boundary-canary-must-not-be-read";
36 const AGENT = "scout";
37 const RUN_ID = "01m46abcdefghjkmnpqrstvwxy";
38 /** The shell's own clone, relative to the data directory. */
39 const WORK = `crew/${AGENT}/01repo/1`;
40 /** Run directories that are not this run's, relative to the data directory. */
41 const OTHER_RUNS = [
42 // Another agent's clone.
43 "crew/mason/01repo/3",
44 // This agent's other run's temp directory (`runTmpDir` keeps the id's last 12).
45 `crew/${AGENT}/.t/0000othr0000`,
46 ];
47
48 /** Every path tried, relative to the data directory: the list, then the other runs. */
49 const TRIED = [...ALWAYS_DENIED, ...OTHER_RUNS];
50
51 /**
52 * A name with an extension is a file (`forge.db`, `secret.key`); any other is
53 * a directory holding one file. Both hold the canary.
54 */
55 function plant(data: string, name: string): void {
56 const path = join(data, name);
57 if (/\.[a-z-]+$/.test(name)) {
58 writeFileSync(path, CANARY);
59 return;
60 }
61 mkdirSync(path, { recursive: true });
62 writeFileSync(join(path, "canary.txt"), CANARY);
63 }
64
65 describe("the crew policy denies every path the boundary tries", () => {
66 let data: string;
67 beforeAll(async () => {
68 // Empty: the floor must be denied by name, whatever the listing sees.
69 data = await mkdtemp(join(tmpdir(), "forge-boundary-policy-"));
70 });
71 afterAll(async () => {
72 await rm(data, { recursive: true, force: true });
73 });
74
75 test("the list is not empty and names the database and the key", () => {
76 expect(ALWAYS_DENIED).toContain("forge.db");
77 expect(ALWAYS_DENIED).toContain("secret.key");
78 expect(ALWAYS_DENIED).toContain("repos");
79 });
80
81 test.each([...ALWAYS_DENIED])("denies %s by name in an empty data directory", (name) => {
82 const policy = sandboxPolicy({ dataDir: data, agentName: AGENT, urls: [], runId: RUN_ID });
83 expect(policy.denyRead).toContain(join(data, name));
84 });
85 });
86
87 const probe = await sandboxAvailable();
88 const srt = join(import.meta.dir, "../node_modules/.bin/srt");
89 const skipShell = process.env["FORGE_TEST_SOCKET"]
90 ? "FORGE_TEST_SOCKET mode: srt binds a unix socket for each bridge to its proxy"
91 : !probe.ok
92 ? skipReason(sandboxCause(probe.reason))
93 : undefined;
94 if (skipShell !== undefined) console.warn(`skipped: test/crew-sandbox-boundary.test.ts (the shell half): ${skipShell}`);
95 else
96 for (const [binary, path] of [
97 ["srt", srt],
98 ["rg", rgPath],
99 ] as const)
100 if (!existsSync(path))
101 throw new Error(
102 `a sandbox can be made here but its runtime is not: ${sandboxCause(`missing binary: ${binary}`).words} (${path}): run bun install`,
103 );
104
105 describe.skipIf(skipShell !== undefined)("a real crew shell reads none of the denied paths", () => {
106 let data: string;
107 /** Per path tried: what the shell got, `refused` or `read`. */
108 let report: Record<string, "refused" | "read">;
109 let own: "refused" | "read";
110
111 beforeAll(async () => {
112 data = await mkdtemp(join(tmpdir(), "forge-boundary-"));
113 const work = join(data, WORK);
114 mkdirSync(work, { recursive: true });
115 for (const name of TRIED) plant(data, name);
116 writeFileSync(join(work, "own.txt"), CANARY);
117
118 const policy = sandboxPolicy({
119 dataDir: data,
120 agentName: AGENT,
121 urls: [],
122 runId: RUN_ID,
123 });
124 const paths = Object.fromEntries(TRIED.map((name) => [name, join(data, name)]));
125 writeFileSync(
126 join(work, "probe.ts"),
127 `
128 import { readFileSync, readdirSync, statSync } from "node:fs";
129 const CANARY = ${JSON.stringify(CANARY)};
130 // Read: the canary came back, by the file or by a file in the directory.
131 const tryRead = (path: string): "refused" | "read" => {
132 try {
133 if (!statSync(path).isDirectory()) return readFileSync(path, "utf8").includes(CANARY) ? "read" : "refused";
134 for (const name of readdirSync(path))
135 try { if (readFileSync(path + "/" + name, "utf8").includes(CANARY)) return "read"; } catch {}
136 return "refused";
137 } catch { return "refused"; }
138 };
139 const paths: Record<string, string> = ${JSON.stringify(paths)};
140 const report: Record<string, string> = {};
141 for (const [name, path] of Object.entries(paths)) report[name] = tryRead(path);
142 console.log(JSON.stringify({ own: tryRead("own.txt"), report }));
143 `,
144 );
145 const settings = join(data, "srt-settings.json");
146 const real = claudeSettings(policy).sandbox as Record<string, any>;
147 expect(real.enabled).toBe(true);
148 writeFileSync(settings, JSON.stringify(runtimeSettings(real, work)));
149 const proc = Bun.spawn([srt, "--settings", settings, "-c", `'${process.execPath}' probe.ts`], {
150 cwd: work,
151 env: srtEnv(process.env),
152 stdin: "ignore",
153 stdout: "pipe",
154 stderr: "pipe",
155 });
156 const [out, err, code] = await Promise.all([
157 new Response(proc.stdout).text(),
158 new Response(proc.stderr).text(),
159 proc.exited,
160 ]);
161 if (code !== 0) throw new Error(`sandboxed shell exited ${code}: ${err}`);
162 const parsed = JSON.parse(out.trim().split("\n").pop() ?? "{}");
163 own = parsed.own;
164 report = parsed.report;
165 });
166 afterAll(async () => {
167 await rm(data, { recursive: true, force: true });
168 });
169
170 test("reads its own clone (the probe ran)", () => {
171 expect(own).toBe("read");
172 });
173
174 test.each(TRIED)("refuses to read %s", (name) => {
175 // The path in the failure: `expected "refused", received "read"` under this test's name.
176 expect({ path: name, got: report[name] }).toEqual({ path: name, got: "refused" });
177 });
178 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs