Public: anyone can read this; the crew can change it.
Sandbox floor with Landlock where bwrap cannot run. #16888
Check · Review · Land · Live done — Landed and live in production.
torque/forge:torque/16835-sandbox-floor-with-landlock-where-bwrap → main 0 commits fork 3 threads · 3 unresolved
29 files
changed +771
−39
- docs/features/landlock-floor.md
- scripts/spawn-argv-allow.json
- src/apps/contain.ts
- src/apps/process.ts
- src/checks/run_tier.ts
- src/crew/claude.ts
- src/crew/dispatch.ts
- src/crew/run_prepare.ts
- src/crew/runner.ts
- src/crew/sandbox.ts
- src/crew/sandbox_floor.ts
- src/crew/sandbox_policy.ts
- src/sandbox/landlock.ts
- src/sandbox/landlock_helper.ts
- src/sandbox/landlock_probe.ts
- test/crew-sandbox-boundary.test.ts
- test/crew-sandbox-escape.test.ts
- test/crew-sandbox-floor.test.ts
- test/crew-sandbox-real.test.ts
- test/crew-sandbox.test.ts
- test/crew.test.ts
- test/helpers/preload.ts
- test/landlock-real.test.ts
- test/landlock.test.ts
- test/openai-real-cell.test.ts
- test/openai-runner-escape.test.ts
- test/spawn-pipes.test.ts
- test/spawn-sites.test.ts
- test/timers-named.test.ts
docs/features/landlock-floor.md added +36
| @@ -0,0 +1,36 @@ | ||
| 1 | --- | |
| 2 | topic: Your apps | |
| 3 | row: Landlock floor where bubblewrap cannot run | |
| 4 | --- | |
| 5 | # Landlock floor | |
| 6 | ||
| 7 | Where bubblewrap cannot make a user namespace (Ubuntu's AppArmor userns restriction without the | |
| 8 | forge-bwrap profile, `hostUsers: false` pods, a nested forge), the forge no longer falls back to | |
| 9 | unrestricted. If the kernel has [](https://docs.kernel.org/userspace-api/landlock.html) it | |
| 10 | holds the work instead, with no root and no namespace. | |
| 11 | ||
| 12 | - **Crew runs.** `sandboxAvailable` tries bubblewrap, then Landlock. With Landlock the run's own | |
| 13 | process is exec-wrapped (`src/sandbox/landlock_helper.ts`): read-only everywhere, writable only | |
| 14 | the clone, the run's temp directory, the install cache and a home of the run's own (`HOME` under | |
| 15 | its temp directory, with a copy of the login; the forge user's `~/.bun`, `~/.npm`, `~/.cache` and | |
| 16 | Claude config are never writable, so nothing a run plants outlives it); signals and abstract | |
| 17 | sockets scoped (ABI 6). **Reads are not hidden:** Landlock cannot hide a subtree under a readable | |
| 18 | root, so the whole filesystem, the forge's secrets included, stays readable, and TCP is open. | |
| 19 | `FORGE_CREW_SANDBOX=require` therefore does **not** accept the floor: its runs stay held. Only | |
| 20 | the default best-effort mode runs behind it, and the run log and record say `landlock ABI N: …`, | |
| 21 | `reads are not hidden`, and what that kernel did not enforce. | |
| 22 | - **Checks.** Under bubblewrap the step command is also wrapped in Landlock (stacked, inside the | |
| 23 | cell). With no cell, the check step is held by Landlock alone, writing its checkout, its home and | |
| 24 | a temp directory of its own (not the machine's `/tmp`); the log line names the ABI and says reads | |
| 25 | are open. | |
| 26 | - **Never silent.** The kernel's ABI is probed; rights it lacks are dropped and named. UDP is never | |
| 27 | covered before ABI 10 and every record says so. | |
| 28 | - `FORGE_LANDLOCK=off` declines the floor on purpose. | |
| 29 | ||
| 30 | Not covered: network. Crew runs must reach their model's API and checks start servers on loopback | |
| 31 | ports, so TCP connect is not confined yet (the plan supports `connect: [ports]`, ABI 4+, for a | |
| 32 | cell whose only way out is a proxy port). The install step of a no-cell check is not wrapped, and | |
| 33 | resource limits (cgroups) and read hiding (bubblewrap) are unchanged. | |
| 34 | ||
| 35 | The helper uses `bun:ffi` in its own short-lived process, never in the forge: restricting the forge | |
| 36 | itself would confine it. |
scripts/spawn-argv-allow.json +2 −2
| @@ -8,8 +8,8 @@ | ||
| 8 | 8 | { |
| 9 | 9 | "file": "src/apps/process.ts", |
| 10 | 10 | "kind": "spawn", |
| 11 | "code": "cell?.argv(command) ?? [\"/bin/sh\", \"-c\", command]", | |
| 12 | "why": "a build or check step (runStep): the app's forge.json command in the step's cell (bwrap first) or /bin/sh, both behind backgroundArgv's fixed script" | |
| 11 | "code": "cell?.argv(command) ?? floored", | |
| 12 | "why": "a build or check step (runStep): the app's forge.json command in the step's cell (bwrap first), else /bin/sh behind the Landlock helper where the kernel has it (landlockArgv: bun, a fixed helper, a plan, then --), all behind backgroundArgv's fixed script" | |
| 13 | 13 | }, |
| 14 | 14 | { |
| 15 | 15 | "file": "src/apps/process.ts", |
src/apps/contain.ts +27 −5
| @@ -60,6 +60,8 @@ import { isSize, SIZES, type Size } from "../spawn/sizes.ts"; | ||
| 60 | 60 | import { CELL_MEMORY_FLOOR_MIB, CELL_MEMORY_RESERVE_MIB, cellMemoryCeilingMiB, servingCores } from "../core/capacity.ts"; |
| 61 | 61 | import { cpuWatch } from "./cpu_rule.ts"; |
| 62 | 62 | import { dutyTick, newDuty, resumeNow, type Duty, type DutyLater, type Signaller } from "./cpu_duty.ts"; |
| 63 | import { HELPER, landlockArgv, landlockPlan } from "../sandbox/landlock.ts"; | |
| 64 | import { probeLandlock, type LandlockProbe } from "../sandbox/landlock_probe.ts"; | |
| 63 | 65 | |
| 64 | 66 | /** |
| 65 | 67 | * `ceiling`: a declaration was cut to the machine's maximum; `declared`: forge.json's own; |
| @@ -323,6 +325,8 @@ export function breachLine(why: string, limits: Limits): string | undefined { | ||
| 323 | 325 | export const STEP_HOSTS = ["registry.npmjs.org"]; |
| 324 | 326 | |
| 325 | 327 | export interface CellSpec { |
| 328 | /** The Landlock floor under this cell; the host's own probe (`cellsAvailable`) when absent. */ | |
| 329 | readonly floor?: { readonly abi: number } | undefined; | |
| 326 | 330 | /** The working directory; writable. */ |
| 327 | 331 | readonly dir: string; |
| 328 | 332 | /** Other directories the cell may write (an environment's data). */ |
| @@ -464,6 +468,12 @@ async function probe(): Promise<{ ok: true } | { ok: false; reason: string }> { | ||
| 464 | 468 | if (Bun.which(tool) === null) |
| 465 | 469 | return { ok: false, reason: `${tool} is not installed` }; |
| 466 | 470 | const verdict = await askUntilBelieved(() => tryOnce()); |
| 471 | // Landlock stacks under bubblewrap where the kernel has it (#16835); its ABI is recorded with the | |
| 472 | // cell. | |
| 473 | if (verdict.ok) { | |
| 474 | const floor = await probeLandlock(); | |
| 475 | cellFloor = floor.ok ? floor : undefined; | |
| 476 | } | |
| 467 | 477 | // Some hosts hold a cell but refuse its sethostname (EPERM from bwrap's |
| 468 | 478 | // `--hostname`, seen on the check machine): asked once, after the cell is |
| 469 | 479 | // believed, so a refused name costs the cell nothing (#10850). |
| @@ -471,6 +481,20 @@ async function probe(): Promise<{ ok: true } | { ok: false; reason: string }> { | ||
| 471 | 481 | return verdict; |
| 472 | 482 | } |
| 473 | 483 | |
| 484 | /** The Landlock floor stacked under every cell on this host, once `cellsAvailable` has asked. */ | |
| 485 | let cellFloor: Extract<LandlockProbe, { ok: true }> | undefined; | |
| 486 | ||
| 487 | /** | |
| 488 | * The command a cell runs, behind Landlock where the kernel holds it: read-only outside what the | |
| 489 | * cell may write, signals and abstract sockets scoped. TCP is left to the cell's own network | |
| 490 | * namespace: its checks connect to servers they start on loopback ports of their own. | |
| 491 | */ | |
| 492 | export function floored(spec: Pick<CellSpec, "dir" | "home" | "writable">, argv: readonly string[], floor: { readonly abi: number } | undefined = cellFloor): string[] { | |
| 493 | if (floor === undefined) return [...argv]; | |
| 494 | const writable = [...new Set([spec.dir, spec.home, ...spec.writable, "/tmp", "/dev", INSIDE])]; | |
| 495 | return landlockArgv(landlockPlan(floor.abi, { writable }), argv); | |
| 496 | } | |
| 497 | ||
| 474 | 498 | /** Whether this host lets a cell set its own hostname; false until `cellsAvailable` has asked. */ |
| 475 | 499 | let hostnameAllowed = false; |
| 476 | 500 | |
| @@ -680,7 +704,7 @@ const within = (path: string, root: string): boolean => path === root || path.st | ||
| 680 | 704 | * remounting that read-only would leave the inner cell no socket to listen on. |
| 681 | 705 | */ |
| 682 | 706 | export function cellMounts( |
| 683 | spec: Pick<CellSpec, "hide" | "reveal">, | |
| 707 | spec: Pick<CellSpec, "hide" | "reveal" | "floor">, | |
| 684 | 708 | machine: readonly string[], |
| 685 | 709 | kind: (path: string) => "dir" | "file" | undefined = pathKind, |
| 686 | 710 | real: (path: string) => string = realPath, |
| @@ -704,7 +728,7 @@ export function cellMounts( | ||
| 704 | 728 | // (`~/.bun/bin/bun` on a developer's machine). |
| 705 | 729 | // Kept when it sits under something hidden by either name: the forge's own code is known by its |
| 706 | 730 | // real path. |
| 707 | const reveal = [dirname(process.execPath), ...(spec.reveal ?? [])].filter((path) => | |
| 731 | const reveal = [dirname(process.execPath), ...((spec.floor ?? cellFloor) === undefined ? [] : [dirname(HELPER)]), ...(spec.reveal ?? [])].filter((path) => | |
| 708 | 732 | hide.some((h) => within(path, h) || within(real(path), h)), |
| 709 | 733 | ); |
| 710 | 734 | return { hide, blank, reveal }; |
| @@ -1084,9 +1108,7 @@ export function openCell( | ||
| 1084 | 1108 | String(rlimits.fileBlocks), |
| 1085 | 1109 | String(rlimits.files), |
| 1086 | 1110 | String(rlimits.tasks), |
| 1087 | "/bin/sh", | |
| 1088 | "-c", | |
| 1089 | command, | |
| 1111 | ...floored({ dir: spec.dir, home: spec.home, writable: asked }, ["/bin/sh", "-c", command], spec.floor ?? cellFloor), | |
| 1090 | 1112 | ]; |
| 1091 | 1113 | |
| 1092 | 1114 | const env = (base: Record<string, string>): Record<string, string> => { |
src/apps/process.ts +9 −1
| @@ -10,6 +10,7 @@ | ||
| 10 | 10 | * app, not to a shell that would swallow it. |
| 11 | 11 | */ |
| 12 | 12 | |
| 13 | import { landlockArgv, landlockPlan } from "../sandbox/landlock.ts"; | |
| 13 | 14 | import type { AppManifest } from "./manifest.ts"; |
| 14 | 15 | import type { EnvName } from "./data.ts"; |
| 15 | 16 | import { envPull } from "./data.ts"; |
| @@ -384,6 +385,11 @@ export async function runStep( | ||
| 384 | 385 | timeoutMs?: number; |
| 385 | 386 | /** Run inside a cell (`apps/contain.ts`) instead of as a plain child. */ |
| 386 | 387 | cell?: CellSpec | undefined; |
| 388 | /** | |
| 389 | * Where no cell can be made: the Landlock floor the plain child is exec-wrapped in (#16835). | |
| 390 | * Writable: its directory and `writable`; read-only elsewhere. | |
| 391 | */ | |
| 392 | floor?: { readonly abi: number; readonly writable: readonly string[] } | undefined; | |
| 387 | 393 | /** |
| 388 | 394 | * Set for a build step (install, test): its limits. The time is the |
| 389 | 395 | * step's bound, and a stop by any limit is one line saying which. |
| @@ -413,7 +419,9 @@ export async function runStep( | ||
| 413 | 419 | : openCell({ ...options.cell, background: true }, options.log); |
| 414 | 420 | let proc: ReturnType<typeof Bun.spawn<"ignore", "pipe", "pipe">>; |
| 415 | 421 | try { |
| 416 | proc = Bun.spawn(backgroundArgv(cell?.argv(command) ?? ["/bin/sh", "-c", command]), { | |
| 422 | const plain = ["/bin/sh", "-c", command]; | |
| 423 | const floored = options.floor === undefined ? plain : landlockArgv(landlockPlan(options.floor.abi, { writable: options.floor.writable }), plain); | |
| 424 | proc = Bun.spawn(backgroundArgv(cell?.argv(command) ?? floored), { | |
| 417 | 425 | cwd: options.cwd, |
| 418 | 426 | env: cell?.env(options.env) ?? options.env, |
| 419 | 427 | stdin: "ignore", |
src/checks/run_tier.ts +19 −2
| @@ -1,4 +1,6 @@ | ||
| 1 | 1 | |
| 2 | import { READS_OPEN } from "../sandbox/landlock.ts"; | |
| 3 | import { probeLandlock } from "../sandbox/landlock_probe.ts"; | |
| 2 | 4 | import { cellHides } from "../spawn/hosted-mark.ts"; |
| 3 | 5 | import { forgeApiKey } from "../crew/runner_env.ts"; |
| 4 | 6 | import { existsSync, mkdirSync, writeFileSync } from "node:fs"; |
| @@ -193,13 +195,25 @@ export async function runTier(lane: LaneState, x: Execution): Promise<CheckOutco | ||
| 193 | 195 | write("placement: job skipped, this cluster names no egress gate for a Job (FORGE_CHECKS_EGRESS_GATE)"); |
| 194 | 196 | // A Job is its own boundary: no cell here, the cluster and its gate hold it. |
| 195 | 197 | const cells = job === undefined ? await cellsAvailable() : undefined; |
| 198 | let floor: { abi: number; writable: string[] } | undefined; | |
| 196 | 199 | if (cells !== undefined) { |
| 197 | 200 | if (x.runId !== undefined) |
| 198 | 201 | noteRunProgress(app.db, x.runId, { |
| 199 | 202 | sandbox: { enforced: cells.ok, note: cells.ok ? "" : cells.reason }, |
| 200 | 203 | }); |
| 201 | if (!cells.ok) | |
| 202 | write(`uncontained here: ${cells.reason}; the check runs unrestricted`); | |
| 204 | if (!cells.ok) { | |
| 205 | // No cell: Landlock alone replaces the unrestricted fallback where the kernel has it | |
| 206 | // (#16835). | |
| 207 | const held = await probeLandlock(); | |
| 208 | if (held.ok) { | |
| 209 | // The checkout, its home and a temp directory of this check's own: never the machine's | |
| 210 | // /tmp, which other users share. | |
| 211 | floor = { abi: held.abi, writable: [dir, `${dir}.home`, `${dir}.tmp`] }; | |
| 212 | const note = `${held.note}; ${READS_OPEN}`; | |
| 213 | if (x.runId !== undefined) noteRunProgress(app.db, x.runId, { sandbox: { enforced: true, note } }); | |
| 214 | write(`no cell here: ${cells.reason}; the check step is held by ${note}`); | |
| 215 | } else write(`uncontained here: ${cells.reason}; ${held.reason}; the check runs unrestricted`); | |
| 216 | } | |
| 203 | 217 | } else { |
| 204 | 218 | if (x.runId !== undefined) |
| 205 | 219 | noteRunProgress(app.db, x.runId, { sandbox: { enforced: true, note: JOB_GATE_NOTE } }); |
| @@ -235,6 +249,7 @@ export async function runTier(lane: LaneState, x: Execution): Promise<CheckOutco | ||
| 235 | 249 | const cellCpus = resolveLimits("step", manifest.limits).cpus; |
| 236 | 250 | const shardCpus = checkShardCpus(cellCpus); |
| 237 | 251 | write(shardsLine(shardsInForce(app.db, shardCpus, x.tier === "verify"))); |
| 252 | if (floor !== undefined) for (const path of floor.writable) mkdirSync(path, { recursive: true }); | |
| 238 | 253 | const env = childEnv({ |
| 239 | 254 | // The shard count an admin set (`core/capacity.ts`), else the |
| 240 | 255 | // default sized to what this check's cell holds, never the pod's. |
| @@ -257,6 +272,7 @@ export async function runTier(lane: LaneState, x: Execution): Promise<CheckOutco | ||
| 257 | 272 | // nested cells, and those never answer in time. Its children run as |
| 258 | 273 | // plain processes here — as they do on a runner without bwrap. |
| 259 | 274 | FORGE_CELLS: "off", |
| 275 | ...(floor === undefined ? {} : { TMPDIR: `${dir}.tmp`, HOME: home }), | |
| 260 | 276 | }); |
| 261 | 277 | let ran: Result<void, string>; |
| 262 | 278 | const checkLines: string[] = []; |
| @@ -323,6 +339,7 @@ export async function runTier(lane: LaneState, x: Execution): Promise<CheckOutco | ||
| 323 | 339 | signal, |
| 324 | 340 | timeoutMs: manifest.timeout * 1000, |
| 325 | 341 | cell, |
| 342 | floor, | |
| 326 | 343 | }); |
| 327 | 344 | } |
| 328 | 345 | if (!ran.ok && ran.error === JOB_VANISHED) return { ok: false, error: JOB_VANISHED }; |
src/crew/claude.ts +7 −1
| @@ -14,6 +14,7 @@ | ||
| 14 | 14 | * spend budget, and a deadline. |
| 15 | 15 | */ |
| 16 | 16 | |
| 17 | import { floorWrap } from "./sandbox_floor.ts"; | |
| 17 | 18 | import { clearedOf, measureOf } from "../core/measure.ts"; |
| 18 | 19 | import { backgroundArgv, crewCpus } from "../apps/background.ts"; |
| 19 | 20 | import { oomFirst } from "../apps/oom.ts"; |
| @@ -246,7 +247,11 @@ async function runClaudeRaw(input: ClaudeInput): Promise<ClaudeOutcome> { | ||
| 246 | 247 | // `FORGE_CREW_CPUS` cores, so it no longer shares the forge's leaf; its |
| 247 | 248 | // machine may narrow that cell with a memory cap and fewer cores. Short |
| 248 | 249 | // of memory the kernel chooses the run before the forge (`apps/oom.ts`). |
| 249 | const argv = [input.binary, ...claudeArgs(input)]; | |
| 250 | const bare = [input.binary, ...claudeArgs(input)]; | |
| 251 | // Where bubblewrap cannot run, the run's own process is held by Landlock (`sandbox_floor.ts`); | |
| 252 | // everything it starts inherits it. Innermost, so the cgroup and oom steps stay outside it. | |
| 253 | const floor = floorWrap(input.sandbox, input.cwd, input.env ?? {}, bare); | |
| 254 | const argv = floor?.argv ?? bare; | |
| 250 | 255 | const present = Bun.which(input.binary) !== null; |
| 251 | 256 | const cell = present ? openRunCell(input.limits ?? {}, cgroupHost(), crewCpus(), input.log) : undefined; |
| 252 | 257 | const cgroup = cell?.cgroup; |
| @@ -257,6 +262,7 @@ async function runClaudeRaw(input: ClaudeInput): Promise<ClaudeOutcome> { | ||
| 257 | 262 | env: childEnv({ |
| 258 | 263 | ...quietEnv(), |
| 259 | 264 | ...input.env, |
| 265 | ...floor?.env, | |
| 260 | 266 | }), |
| 261 | 267 | stdin: "pipe", |
| 262 | 268 | stdout: "pipe", |
src/crew/dispatch.ts +6 −9
| @@ -116,7 +116,7 @@ import { | ||
| 116 | 116 | } from "./guard.ts"; |
| 117 | 117 | import { noteProtection } from "../kernel/protection.ts"; |
| 118 | 118 | import { dataInTemp, sandboxAvailable, sweepRunTmp } from "./sandbox.ts"; |
| 119 | import { SANDBOX_ENV, noteSandbox, reprober, sandboxHoldSentence, sandboxRefusal, type SandboxProbe } from "./sandbox_policy.ts"; | |
| 119 | import { SANDBOX_ENV, accepted, noteSandbox, standingOptions, reprober, sandboxHoldSentence, sandboxRefusal, type SandboxProbe } from "./sandbox_policy.ts"; | |
| 120 | 120 | import { sandboxCause } from "./sandbox_cause.ts"; |
| 121 | 121 | import { mayDirectCrew } from "./direct.ts"; |
| 122 | 122 | import { AUTONOMY_TICK_MS, autonomyTick } from "./autonomy_tick.ts"; |
| @@ -244,7 +244,7 @@ export async function startCrew( | ||
| 244 | 244 | // hold a run to it, the runs say so instead of warning on every command. |
| 245 | 245 | // The default the Capacity page shows and goes back to (`core/capacity.ts`). |
| 246 | 246 | noteBooted(app.db, "crew.concurrency", String(options.concurrency)); |
| 247 | const sandbox = await sandboxAvailable(); | |
| 247 | const sandbox = accepted(await sandboxAvailable(), options.sandboxRequired === true); | |
| 248 | 248 | const noteShells = (probe: SandboxProbe): void => |
| 249 | 249 | noteProtection(app, "crew shells", probe, options.sandboxRequired === true ? `its runs are refused (${SANDBOX_ENV}=require)` : undefined); |
| 250 | 250 | noteShells(sandbox); |
| @@ -273,11 +273,7 @@ export async function startCrew( | ||
| 273 | 273 | cause: sandboxCause(sandbox.reason).words, |
| 274 | 274 | reason: sandbox.reason, |
| 275 | 275 | }); |
| 276 | const standing = (probe: SandboxProbe): CrewOptions => ({ | |
| 277 | ...options, | |
| 278 | sandboxEnforced: probe.ok, | |
| 279 | ...(probe.ok ? {} : { sandboxNote: probe.reason }), | |
| 280 | }); | |
| 276 | const standing = (probe: SandboxProbe): CrewOptions => standingOptions(options, probe); | |
| 281 | 277 | let ready: CrewOptions = standing(sandbox); |
| 282 | 278 | |
| 283 | 279 | let stopped = false; |
| @@ -286,8 +282,9 @@ export async function startCrew( | ||
| 286 | 282 | // stops saying reduced, and what was held starts. |
| 287 | 283 | const again = reprober({ |
| 288 | 284 | last: Date.now(), |
| 289 | heard: (probe) => { | |
| 285 | heard: (answer) => { | |
| 290 | 286 | if (stopped) return; |
| 287 | const probe = accepted(answer, options.sandboxRequired === true); | |
| 291 | 288 | ready = standing(probe); |
| 292 | 289 | noteShells(probe); |
| 293 | 290 | noteSandbox(app, options.sandboxRequired === true, probe, again); |
| @@ -404,7 +401,7 @@ export async function startCrew( | ||
| 404 | 401 | |
| 405 | 402 | const handle: CrewHandle = { |
| 406 | 403 | ready: detected.ok, |
| 407 | sandbox: { enforced: sandbox.ok, reason: sandbox.ok ? "" : sandbox.reason }, | |
| 404 | sandbox: { enforced: sandbox.ok && sandbox.floor === undefined, reason: sandbox.ok ? (sandbox.floor?.note ?? "") : sandbox.reason }, | |
| 408 | 405 | detail: detected.ok ? `Claude Code ${detected.version}` : detected.error, |
| 409 | 406 | stop: async (options = {}) => { |
| 410 | 407 | stopped = true; |
src/crew/run_prepare.ts +5 −1
| @@ -4,6 +4,7 @@ | ||
| 4 | 4 | * closure that invokes it, metered as it goes. |
| 5 | 5 | */ |
| 6 | 6 | |
| 7 | import { floorLine } from "./sandbox_floor.ts"; | |
| 7 | 8 | import type { App } from "../app.ts"; |
| 8 | 9 | import type { Agent } from "../core/agents.ts"; |
| 9 | 10 | import { capacityEnv } from "../core/capacity.ts"; |
| @@ -163,6 +164,7 @@ export async function prepareAgent(s: PrepareState): Promise<Prepared> { | ||
| 163 | 164 | ], |
| 164 | 165 | gateway: held.gatewayDoor?.base, |
| 165 | 166 | enforced: options.sandboxEnforced, |
| 167 | floor: options.sandboxFloor, | |
| 166 | 168 | runId: run.id, |
| 167 | 169 | repoId: repo.id, |
| 168 | 170 | }); |
| @@ -289,7 +291,9 @@ export async function prepareAgent(s: PrepareState): Promise<Prepared> { | ||
| 289 | 291 | note: options.sandboxNote ?? "", |
| 290 | 292 | }, |
| 291 | 293 | }); |
| 292 | if (!sandbox.enforced) | |
| 294 | if (sandbox.floor !== undefined) | |
| 295 | write(floorLine(sandbox.floor)); | |
| 296 | else if (!sandbox.enforced) | |
| 293 | 297 | write( |
| 294 | 298 | `sandbox: off here${options.sandboxNote === undefined ? "" : ` — ${options.sandboxNote}`}; the shell runs unrestricted`, |
| 295 | 299 | ); |
src/crew/runner.ts +3
| @@ -14,6 +14,7 @@ | ||
| 14 | 14 | import { existsSync } from "node:fs"; |
| 15 | 15 | import { rm } from "node:fs/promises"; |
| 16 | 16 | import { join } from "node:path"; |
| 17 | import type { LandlockFloor } from "./sandbox.ts"; | |
| 17 | 18 | import { dropBrief } from "../actions/drop.ts"; |
| 18 | 19 | import { announceRun } from "../actions/runs.ts"; |
| 19 | 20 | import type { App } from "../app.ts"; |
| @@ -111,6 +112,8 @@ export interface CrewOptions { | ||
| 111 | 112 | readonly sandboxEnforced?: boolean | undefined; |
| 112 | 113 | /** Why it cannot, when it cannot — said once in every run's log. */ |
| 113 | 114 | readonly sandboxNote?: string | undefined; |
| 115 | /** The Landlock floor holding runs where bubblewrap cannot (`sandboxAvailable`). */ | |
| 116 | readonly sandboxFloor?: LandlockFloor | undefined; | |
| 114 | 117 | /** Refuse crew runs while the sandbox is unavailable (`sandbox_policy.ts`). */ |
| 115 | 118 | readonly sandboxRequired?: boolean | undefined; |
| 116 | 119 | /** Milliseconds between the crew's ticks; tests pass a small one. @default 5000 */ |
src/crew/sandbox.ts +36 −1
| @@ -36,6 +36,8 @@ import { accessSync, constants, lstatSync, mkdirSync, readdirSync, rmSync, statS | ||
| 36 | 36 | import { homedir, tmpdir } from "node:os"; |
| 37 | 37 | import { basename, dirname, isAbsolute, join, relative } from "node:path"; |
| 38 | 38 | import { dropDir } from "../drop/store.ts"; |
| 39 | import { READS_OPEN } from "../sandbox/landlock.ts"; | |
| 40 | import { probeLandlock, type LandlockProbe } from "../sandbox/landlock_probe.ts"; | |
| 39 | 41 | import { cacheRoot, crewRoot, installCacheDir } from "./workdir.ts"; |
| 40 | 42 | |
| 41 | 43 | export interface SandboxPolicy { |
| @@ -59,6 +61,11 @@ export interface SandboxPolicy { | ||
| 59 | 61 | readonly installCache?: string | undefined; |
| 60 | 62 | /** Paths re-allowed within `denyRead`: this run's own repository's cache and drop. */ |
| 61 | 63 | readonly readAllow: readonly string[]; |
| 64 | /** | |
| 65 | * Where bubblewrap cannot run: the Landlock floor the run's process is wrapped in | |
| 66 | * (`runClaude`). `enforced` stays false then: Claude Code's own sandbox is bubblewrap. | |
| 67 | */ | |
| 68 | readonly floor?: LandlockFloor | undefined; | |
| 62 | 69 | } |
| 63 | 70 | |
| 64 | 71 | /** |
| @@ -97,7 +104,32 @@ export function installCacheEnv( | ||
| 97 | 104 | * profile that let an unprivileged process make a user namespace — which a |
| 98 | 105 | * locked-down container usually does not. Probed once, at crew start. |
| 99 | 106 | */ |
| 100 | export async function sandboxAvailable(): Promise< | |
| 107 | export async function sandboxAvailable( | |
| 108 | landlock: () => Promise<LandlockProbe> = probeLandlock, | |
| 109 | bubblewrap: () => Promise<{ ok: true } | { ok: false; reason: string }> = bwrapAvailable, | |
| 110 | ): Promise<SandboxAnswer> { | |
| 111 | const bwrap = await bubblewrap(); | |
| 112 | if (bwrap.ok) return bwrap; | |
| 113 | // Where bubblewrap cannot run, Landlock alone is the floor (#16835), never the unrestricted | |
| 114 | // fallback. | |
| 115 | const floor = await landlock(); | |
| 116 | if (floor.ok) return { ok: true, floor: { kind: "landlock", abi: floor.abi, note: `${floor.note}; ${READS_OPEN}` } }; | |
| 117 | return { ok: false, reason: `${bwrap.reason}; ${floor.reason}` }; | |
| 118 | } | |
| 119 | ||
| 120 | /** What `sandboxAvailable` answers: bubblewrap's, or the Landlock floor that stands in for it. */ | |
| 121 | export type SandboxAnswer = | |
| 122 | | { ok: true; floor?: LandlockFloor } | |
| 123 | | { ok: false; reason: string }; | |
| 124 | ||
| 125 | /** The Landlock floor a run is held to where bubblewrap cannot run, and the ABI that applied. */ | |
| 126 | export interface LandlockFloor { | |
| 127 | readonly kind: "landlock"; | |
| 128 | readonly abi: number; | |
| 129 | readonly note: string; | |
| 130 | } | |
| 131 | ||
| 132 | export async function bwrapAvailable(): Promise< | |
| 101 | 133 | { ok: true } | { ok: false; reason: string } |
| 102 | 134 | > { |
| 103 | 135 | if (process.platform === "darwin") return { ok: true }; |
| @@ -434,6 +466,8 @@ export function sandboxPolicy(input: { | ||
| 434 | 466 | gateway?: string | null | undefined; |
| 435 | 467 | /** Whether the host can enforce it (`sandboxAvailable`); yes by default. */ |
| 436 | 468 | enforced?: boolean | undefined; |
| 469 | /** The Landlock floor standing in for bubblewrap on this host (`sandboxAvailable`). */ | |
| 470 | floor?: LandlockFloor | undefined; | |
| 437 | 471 | /** The run this is for: it gets a temp directory of its own (`tmpDir`). */ |
| 438 | 472 | runId?: string | undefined; |
| 439 | 473 | /** The repository the run is on: its install cache is writable (`installCache`). */ |
| @@ -513,5 +547,6 @@ export function sandboxPolicy(input: { | ||
| 513 | 547 | readAllow: [...(installCache === undefined ? [] : [installCache]), ...(input.repoId === undefined ? [] : [dropDir(data, input.repoId)])], |
| 514 | 548 | ...(tmpDir === undefined ? {} : { tmpDir }), |
| 515 | 549 | ...(installCache === undefined ? {} : { installCache }), |
| 550 | ...(input.floor === undefined ? {} : { floor: input.floor }), | |
| 516 | 551 | }; |
| 517 | 552 | } |
src/crew/sandbox_floor.ts added +72
| @@ -0,0 +1,72 @@ | ||
| 1 | /** | |
| 2 | * What the Landlock floor lets a crew run's process write, where bubblewrap cannot hold its shell | |
| 3 | * (#16835): the clone, the run's own temp directory, the repository's install cache, and a home of | |
| 4 | * the run's own. Everything else is read-only. Reads are not hidden and TCP is not confined (the | |
| 5 | * agent must reach its model's API), which is why `FORGE_CREW_SANDBOX=require` does not accept it | |
| 6 | * (`sandbox_policy.ts`, `accepted`). | |
| 7 | * | |
| 8 | * State the forge user shares between runs and with the forge (`~/.bun`, `~/.npm`, `~/.cache`, the | |
| 9 | * Claude config directory) is never writable: a binary planted in `~/.bun/bin` or a rewritten | |
| 10 | * credential would be used by the next run or by the forge. The run gets a `HOME` under its own | |
| 11 | * temp directory instead, holding a copy of the login it needs. | |
| 12 | */ | |
| 13 | import { copyFileSync, existsSync, mkdirSync } from "node:fs"; | |
| 14 | import { homedir } from "node:os"; | |
| 15 | import { dirname, join } from "node:path"; | |
| 16 | import { landlockArgv, landlockPlan } from "../sandbox/landlock.ts"; | |
| 17 | import { shellTmpDir, type SandboxPolicy } from "./sandbox.ts"; | |
| 18 | ||
| 19 | /** The files of a Claude config directory that carry the login; nothing else is copied. */ | |
| 20 | const LOGIN_FILES = [".credentials.json"]; | |
| 21 | ||
| 22 | /** The run's own home: under its temp directory, beside its clone when it has none. */ | |
| 23 | export function floorHome(policy: SandboxPolicy, cwd: string): string { | |
| 24 | return policy.tmpDir === undefined ? `${cwd}.home` : join(policy.tmpDir, "home"); | |
| 25 | } | |
| 26 | ||
| 27 | /** The places a run may write: its own, and nothing of the forge user's. */ | |
| 28 | export function floorWritable(policy: SandboxPolicy, cwd: string, env: Record<string, string | undefined>): string[] { | |
| 29 | const own = [cwd, floorHome(policy, cwd), policy.tmpDir, shellTmpDir(policy), policy.installCache, env["TMPDIR"]]; | |
| 30 | const devices = ["/dev/null", "/dev/tty", "/dev/shm"].filter((p) => existsSync(p)); | |
| 31 | return [...new Set([...own.filter((p): p is string => p !== undefined && p.startsWith("/")), ...devices])]; | |
| 32 | } | |
| 33 | ||
| 34 | /** | |
| 35 | * The run's home made, with a copy of the login from the config directory it would have used | |
| 36 | * (`CLAUDE_CONFIG_DIR`, else `~/.claude`); the env that points the run at it. | |
| 37 | */ | |
| 38 | export function floorState( | |
| 39 | policy: SandboxPolicy, | |
| 40 | cwd: string, | |
| 41 | env: Record<string, string | undefined>, | |
| 42 | home: string = homedir(), | |
| 43 | ): Record<string, string> { | |
| 44 | const own = floorHome(policy, cwd); | |
| 45 | const config = join(own, ".claude"); | |
| 46 | mkdirSync(config, { recursive: true }); | |
| 47 | const from = env["CLAUDE_CONFIG_DIR"] ?? join(env["HOME"] ?? home, ".claude"); | |
| 48 | for (const name of LOGIN_FILES) | |
| 49 | if (existsSync(join(from, name))) copyFileSync(join(from, name), join(config, name)); | |
| 50 | // The global state file sits beside the directory when none was named. | |
| 51 | const global = env["CLAUDE_CONFIG_DIR"] === undefined ? join(dirname(from), ".claude.json") : join(from, ".claude.json"); | |
| 52 | if (existsSync(global)) copyFileSync(global, join(config, ".claude.json")); | |
| 53 | return { HOME: own, CLAUDE_CONFIG_DIR: config }; | |
| 54 | } | |
| 55 | ||
| 56 | /** `argv` behind the floor, and the env that gives the run its own home; none without a floor. */ | |
| 57 | export function floorWrap( | |
| 58 | policy: SandboxPolicy, | |
| 59 | cwd: string, | |
| 60 | env: Record<string, string | undefined>, | |
| 61 | argv: readonly string[], | |
| 62 | ): { argv: string[]; env: Record<string, string> } | undefined { | |
| 63 | if (policy.floor === undefined) return undefined; | |
| 64 | const state = floorState(policy, cwd, env); | |
| 65 | const plan = landlockPlan(policy.floor.abi, { writable: floorWritable(policy, cwd, env) }); | |
| 66 | return { argv: landlockArgv(plan, argv), env: state }; | |
| 67 | } | |
| 68 | ||
| 69 | /** The line a run's log opens its sandbox account with when only the floor holds it. */ | |
| 70 | export function floorLine(floor: { readonly note: string }): string { | |
| 71 | return `sandbox: bubblewrap is unavailable here; the run's process is held by ${floor.note}`; | |
| 72 | } |
src/crew/sandbox_policy.ts +27 −2
| @@ -10,7 +10,7 @@ | ||
| 10 | 10 | * without bubblewrap sets it, then `require` — the one line to change. |
| 11 | 11 | */ |
| 12 | 12 | |
| 13 | import { sandboxAvailable } from "./sandbox.ts"; | |
| 13 | import { sandboxAvailable, type LandlockFloor, type SandboxAnswer } from "./sandbox.ts"; | |
| 14 | 14 | import { sandboxCause } from "./sandbox_cause.ts"; |
| 15 | 15 | |
| 16 | 16 | export const SANDBOX_ENV = "FORGE_CREW_SANDBOX"; |
| @@ -27,7 +27,32 @@ export function sandboxMode(env: Record<string, string | undefined>): SandboxMod | ||
| 27 | 27 | } |
| 28 | 28 | |
| 29 | 29 | /** What the probe (`sandboxAvailable`) answered. */ |
| 30 | export type SandboxProbe = { ok: true } | { ok: false; reason: string }; | |
| 30 | export type SandboxProbe = SandboxAnswer; | |
| 31 | ||
| 32 | /** | |
| 33 | * The probe as this forge takes it. Where it requires the sandbox the Landlock floor does not | |
| 34 | * count (#16835): it holds writes but hides no reads (the forge's secrets stay readable) and leaves | |
| 35 | * TCP open, and `require` has always meant the secrets are hidden. Otherwise as answered. | |
| 36 | */ | |
| 37 | export function accepted(probe: SandboxProbe, required: boolean): SandboxProbe { | |
| 38 | if (!required || !probe.ok || probe.floor === undefined) return probe; | |
| 39 | return { ok: false, reason: `only the Landlock floor is available (${probe.floor.note}); it hides no reads, so ${SANDBOX_ENV}=require does not accept it` }; | |
| 40 | } | |
| 41 | ||
| 42 | /** | |
| 43 | * The crew's options for the probe it holds: Claude Code's own sandbox stays off under the floor. | |
| 44 | */ | |
| 45 | export function standingOptions<T extends { sandboxRequired?: boolean | undefined }>( | |
| 46 | options: T, | |
| 47 | probe: SandboxProbe, | |
| 48 | ): T & { sandboxEnforced: boolean; sandboxNote?: string; sandboxFloor?: LandlockFloor } { | |
| 49 | const held = accepted(probe, options.sandboxRequired === true); | |
| 50 | return { | |
| 51 | ...options, | |
| 52 | sandboxEnforced: held.ok && held.floor === undefined, | |
| 53 | ...(held.ok ? (held.floor === undefined ? {} : { sandboxFloor: held.floor, sandboxNote: held.floor.note }) : { sandboxNote: held.reason }), | |
| 54 | }; | |
| 55 | } | |
| 31 | 56 | |
| 32 | 57 | /** The least time between two probes of a host that could not hold the sandbox. */ |
| 33 | 58 | export const SANDBOX_REPROBE_MS = 60_000; |
src/sandbox/landlock.ts added +97
| @@ -0,0 +1,97 @@ | ||
| 1 | /** | |
| 2 | * The Landlock floor, as plain data: what a ruleset asks for, what the running kernel can hold, and | |
| 3 | * the argv that runs a command under it (`landlock_helper.ts`). | |
| 4 | * | |
| 5 | * Landlock (https://docs.kernel.org/userspace-api/landlock.html) needs no root and no user | |
| 6 | * namespace: a process restricts itself and its children, one way. The restriction is made in a | |
| 7 | * small helper process that then `exec`s the command, never in the forge (a restricted forge would | |
| 8 | * be confined with it). | |
| 9 | * | |
| 10 | * ABI levels (Documentation/userspace-api/landlock.rst, "Landlock ABI versions"): | |
| 11 | * 1 filesystem rights; 2 REFER; 3 TRUNCATE; 4 TCP bind/connect; 5 IOCTL_DEV; | |
| 12 | * 6 scopes (abstract unix sockets, signals). UDP is covered by no ABI this module knows (it | |
| 13 | * arrived in ABI 10), so every run record says it is not. | |
| 14 | */ | |
| 15 | ||
| 16 | /** Filesystem access bits, by the ABI that introduced them (include/uapi/linux/landlock.h). */ | |
| 17 | const FS_BITS: readonly (readonly [string, number, number])[] = [ | |
| 18 | ["execute", 0, 1], ["write_file", 1, 1], ["read_file", 2, 1], ["read_dir", 3, 1], | |
| 19 | ["remove_dir", 4, 1], ["remove_file", 5, 1], ["make_char", 6, 1], ["make_dir", 7, 1], | |
| 20 | ["make_reg", 8, 1], ["make_sock", 9, 1], ["make_fifo", 10, 1], ["make_block", 11, 1], | |
| 21 | ["make_sym", 12, 1], ["refer", 13, 2], ["truncate", 14, 3], ["ioctl_dev", 15, 5], | |
| 22 | ]; | |
| 23 | ||
| 24 | ||
| 25 | export const NET_CONNECT_TCP = 1 << 1; | |
| 26 | export const SCOPE_ABSTRACT_UNIX = 1 << 0; | |
| 27 | export const SCOPE_SIGNAL = 1 << 1; | |
| 28 | ||
| 29 | export interface LandlockWant { | |
| 30 | /** Written, made and removed under these; read-only everywhere else. */ | |
| 31 | readonly writable: readonly string[]; | |
| 32 | /** TCP connect allowed to these ports only; undefined leaves TCP unconfined. */ | |
| 33 | readonly connect?: readonly number[] | undefined; | |
| 34 | } | |
| 35 | ||
| 36 | export interface LandlockPlan { | |
| 37 | /** The ABI the kernel reported. */ | |
| 38 | readonly abi: number; | |
| 39 | /** Bitmask of the filesystem rights handled (all others are not restricted by Landlock). */ | |
| 40 | readonly handledFs: number; | |
| 41 | readonly handledNet: number; | |
| 42 | readonly scoped: number; | |
| 43 | readonly writable: readonly string[]; | |
| 44 | /** Allowed connect ports; meaningful only when `handledNet` is not 0. */ | |
| 45 | readonly connect: readonly number[]; | |
| 46 | /** What was asked for and the kernel cannot hold: never silent. */ | |
| 47 | readonly stripped: readonly string[]; | |
| 48 | } | |
| 49 | ||
| 50 | /** The plan for `want` on a kernel of `abi`: what the kernel lacks is dropped and named. */ | |
| 51 | export function landlockPlan(abi: number, want: LandlockWant): LandlockPlan { | |
| 52 | const stripped: string[] = []; | |
| 53 | let handledFs = 0; | |
| 54 | for (const [, bit, since] of FS_BITS) if (abi >= since) handledFs |= 1 << bit; | |
| 55 | for (const [name, , since] of FS_BITS) | |
| 56 | if (abi < since) stripped.push(`fs ${name} (needs ABI ${since})`); | |
| 57 | let handledNet = 0; | |
| 58 | if (want.connect !== undefined) { | |
| 59 | if (abi >= 4) handledNet = NET_CONNECT_TCP; | |
| 60 | else stripped.push("tcp connect (needs ABI 4)"); | |
| 61 | } | |
| 62 | let scoped = 0; | |
| 63 | if (abi >= 6) scoped = SCOPE_ABSTRACT_UNIX | SCOPE_SIGNAL; | |
| 64 | else stripped.push("abstract-socket and signal scope (needs ABI 6)"); | |
| 65 | return { abi, handledFs, handledNet, scoped, writable: want.writable, connect: want.connect ?? [], stripped }; | |
| 66 | } | |
| 67 | ||
| 68 | /** The sentence a run records: the ABI that applied and what it does not cover. */ | |
| 69 | export function landlockNote(plan: LandlockPlan): string { | |
| 70 | const held = ["filesystem read-only outside the workspace"]; | |
| 71 | if (plan.handledNet !== 0) held.push(`tcp connect to port${plan.connect.length === 1 ? "" : "s"} ${plan.connect.join(",")} only`); | |
| 72 | if (plan.scoped !== 0) held.push("signals and abstract sockets scoped"); | |
| 73 | const gaps = [...plan.stripped, "udp (not covered before ABI 10)"]; | |
| 74 | return `landlock ABI ${plan.abi}: ${held.join("; ")}; not enforced: ${gaps.join(", ")}`; | |
| 75 | } | |
| 76 | ||
| 77 | /** What a floor used alone, with no bubblewrap above it, leaves open: said wherever it is named. */ | |
| 78 | export const READS_OPEN = "reads are not hidden (the whole filesystem stays readable) and tcp is not confined"; | |
| 79 | ||
| 80 | /** Whether `want` is a safe request: absolute paths without NUL, real ports. */ | |
| 81 | export function validWant(want: LandlockWant): boolean { | |
| 82 | const path = (p: string): boolean => p.startsWith("/") && !p.includes("\0"); | |
| 83 | const port = (n: number): boolean => Number.isInteger(n) && n > 0 && n < 65536; | |
| 84 | return want.writable.every(path) && (want.connect ?? []).every(port); | |
| 85 | } | |
| 86 | ||
| 87 | /** The helper's own path, next to this module. */ | |
| 88 | export const HELPER = new URL("./landlock_helper.ts", import.meta.url).pathname; | |
| 89 | ||
| 90 | /** | |
| 91 | * `argv` behind the helper: the plan as one JSON argument, then `--`, then the command. A plan that | |
| 92 | * is not safe throws, so a request is never turned into a weaker one. | |
| 93 | */ | |
| 94 | export function landlockArgv(plan: LandlockPlan, argv: readonly string[], bun: string = process.execPath): string[] { | |
| 95 | if (!validWant({ writable: plan.writable, connect: plan.connect })) throw new Error("landlock: unsafe plan"); | |
| 96 | return [bun, HELPER, JSON.stringify(plan), "--", ...argv]; | |
| 97 | } |
src/sandbox/landlock_helper.ts added +94
| @@ -0,0 +1,94 @@ | ||
| 1 | /** | |
| 2 | * Restrict this process with Landlock, then become the command. Run as | |
| 3 | * `bun landlock_helper.ts <plan json> -- <command…>` (`landlockArgv`), or `--abi` to print the | |
| 4 | * kernel's ABI number. | |
| 5 | * | |
| 6 | * This uses bun:ffi, which is why it is its own process and never imported by the forge: the | |
| 7 | * restriction applies to the thread that makes it and to what that thread execs, and the forge must | |
| 8 | * not be confined. It fails closed: any step the kernel refuses exits 126 and the command never | |
| 9 | * runs. Calls are the raw syscalls (same numbers on x86_64 and aarch64): landlock_create_ruleset | |
| 10 | * 444, landlock_add_rule 445, landlock_restrict_self 446. | |
| 11 | */ | |
| 12 | import { dlopen, ptr } from "bun:ffi"; | |
| 13 | import { statSync } from "node:fs"; | |
| 14 | ||
| 15 | const libc = dlopen("libc.so.6", { | |
| 16 | syscall: { args: ["i64", "i64", "i64", "i64", "i64"], returns: "i64" }, | |
| 17 | prctl: { args: ["i32", "i64", "i64", "i64", "i64"], returns: "i32" }, | |
| 18 | open: { args: ["ptr", "i32"], returns: "i32" }, | |
| 19 | close: { args: ["i32"], returns: "i32" }, | |
| 20 | execvp: { args: ["ptr", "ptr"], returns: "i32" }, | |
| 21 | }).symbols; | |
| 22 | ||
| 23 | const SYS_CREATE = 444n, SYS_ADD = 445n, SYS_RESTRICT = 446n; | |
| 24 | const O_PATH_CLOEXEC = 0o10000000 | 0o2000000; | |
| 25 | const cstr = (s: string): Buffer => Buffer.from(`${s}\0`); | |
| 26 | ||
| 27 | function die(message: string): never { | |
| 28 | process.stderr.write(`landlock: ${message}\n`); | |
| 29 | process.exit(126); | |
| 30 | } | |
| 31 | ||
| 32 | function abi(): number { | |
| 33 | const n = Number(libc.syscall(SYS_CREATE, 0n, 0n, 1n, 0n)); | |
| 34 | return n; | |
| 35 | } | |
| 36 | ||
| 37 | if (process.argv[2] === "--abi") { | |
| 38 | const have = abi(); | |
| 39 | process.stdout.write(`${have}\n`); | |
| 40 | process.exit(have > 0 ? 0 : 1); | |
| 41 | } | |
| 42 | ||
| 43 | const split = process.argv.indexOf("--"); | |
| 44 | if (split < 3 || split === process.argv.length - 1) die("usage: <plan> -- <command…>"); | |
| 45 | const plan = JSON.parse(process.argv[2]!) as { | |
| 46 | abi: number; handledFs: number; handledNet: number; scoped: number; writable: string[]; connect: number[]; | |
| 47 | }; | |
| 48 | const command = process.argv.slice(split + 1); | |
| 49 | ||
| 50 | // Layout of struct landlock_ruleset_attr: handled_access_fs, handled_access_net, scoped (u64 each). | |
| 51 | const size = plan.scoped !== 0 ? 24 : plan.handledNet !== 0 ? 16 : 8; | |
| 52 | const attr = new BigUint64Array([BigInt(plan.handledFs), BigInt(plan.handledNet), BigInt(plan.scoped)]); | |
| 53 | const ruleset = Number(libc.syscall(SYS_CREATE, BigInt(ptr(attr)), BigInt(size), 0n, 0n)); | |
| 54 | if (ruleset < 0) die(`the kernel refused the ruleset (ABI ${plan.abi} planned)`); | |
| 55 | ||
| 56 | /** | |
| 57 | * Allow `access` beneath `path` (struct landlock_path_beneath_attr: u64 access, s32 fd, packed). | |
| 58 | */ | |
| 59 | function allow(path: string, access: number): void { | |
| 60 | const fd = libc.open(ptr(cstr(path)), O_PATH_CLOEXEC); | |
| 61 | if (fd < 0) { | |
| 62 | // A writable place that is not there grants nothing; a read root that is not there is an error. | |
| 63 | if (access === (plan.handledFs & READ)) die(`cannot open ${path}`); | |
| 64 | return; | |
| 65 | } | |
| 66 | // A file takes only the rights that mean something for one (the kernel refuses the rest). | |
| 67 | const rights = statSync(path).isDirectory() ? access : access & FILE_RIGHTS; | |
| 68 | const rule = Buffer.alloc(12); | |
| 69 | rule.writeBigUInt64LE(BigInt(rights), 0); | |
| 70 | rule.writeInt32LE(fd, 8); | |
| 71 | const r = Number(libc.syscall(SYS_ADD, BigInt(ruleset), 1n, BigInt(ptr(rule)), 0n)); | |
| 72 | libc.close(fd); | |
| 73 | if (r < 0) die(`cannot allow ${path}`); | |
| 74 | } | |
| 75 | // execute, write_file, read_file, truncate, ioctl_dev | |
| 76 | const FILE_RIGHTS = (1 << 0) | (1 << 1) | (1 << 2) | (1 << 14) | (1 << 15); | |
| 77 | const READ = (1 << 0) | (1 << 2) | (1 << 3); | |
| 78 | allow("/", plan.handledFs & READ); | |
| 79 | for (const path of plan.writable) allow(path, plan.handledFs); | |
| 80 | // struct landlock_net_port_attr: u64 allowed_access, u64 port. | |
| 81 | for (const port of plan.connect) { | |
| 82 | const rule = new BigUint64Array([BigInt(plan.handledNet), BigInt(port)]); | |
| 83 | if (Number(libc.syscall(SYS_ADD, BigInt(ruleset), 2n, BigInt(ptr(rule)), 0n)) < 0) die(`cannot allow port ${port}`); | |
| 84 | } | |
| 85 | // PR_SET_NO_NEW_PRIVS = 38: required to restrict oneself without privilege. | |
| 86 | if (libc.prctl(38, 1n, 0n, 0n, 0n) !== 0) die("cannot set no_new_privs"); | |
| 87 | if (Number(libc.syscall(SYS_RESTRICT, BigInt(ruleset), 0n, 0n, 0n)) < 0) die("the kernel refused to restrict this process"); | |
| 88 | libc.close(ruleset); | |
| 89 | ||
| 90 | const args = command.map(cstr); | |
| 91 | const vector = new BigUint64Array(args.length + 1); | |
| 92 | args.forEach((a, i) => (vector[i] = BigInt(ptr(a)))); | |
| 93 | libc.execvp(ptr(args[0]!), ptr(vector)); | |
| 94 | die(`cannot run ${command[0]}`); |
src/sandbox/landlock_probe.ts added +34
| @@ -0,0 +1,34 @@ | ||
| 1 | /** | |
| 2 | * Which Landlock ABI this kernel holds, asked of the helper in a child process (the forge never | |
| 3 | * calls Landlock itself). Probed once; a host without it answers why. | |
| 4 | */ | |
| 5 | import { HELPER, landlockNote, landlockPlan } from "./landlock.ts"; | |
| 6 | ||
| 7 | export type LandlockProbe = { ok: true; abi: number; note: string } | { ok: false; reason: string }; | |
| 8 | ||
| 9 | /** The ABI in the helper's `--abi` answer, or undefined when it is not a positive number. */ | |
| 10 | export function parseAbi(text: string): number | undefined { | |
| 11 | const n = Number(text.trim()); | |
| 12 | return Number.isInteger(n) && n >= 1 && n < 1000 ? n : undefined; | |
| 13 | } | |
| 14 | ||
| 15 | /** `FORGE_LANDLOCK=off` declines the floor on purpose (the suite's fakes write anywhere). */ | |
| 16 | export const LANDLOCK_ENV = "FORGE_LANDLOCK"; | |
| 17 | ||
| 18 | export async function probeLandlock( | |
| 19 | env: Record<string, string | undefined> = process.env, | |
| 20 | ): Promise<LandlockProbe> { | |
| 21 | if ((env[LANDLOCK_ENV] ?? "").trim().toLowerCase() === "off") return { ok: false, reason: `${LANDLOCK_ENV}=off` }; | |
| 22 | if (process.platform !== "linux") return { ok: false, reason: `no landlock on ${process.platform}` }; | |
| 23 | try { | |
| 24 | const proc = Bun.spawn([process.execPath, HELPER, "--abi"], { stdin: "ignore", stdout: "pipe", stderr: "pipe" }); | |
| 25 | const timer = setTimeout(() => proc.kill("SIGKILL"), 5_000); | |
| 26 | const [out, err, code] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]); | |
| 27 | clearTimeout(timer); | |
| 28 | const abi = code === 0 ? parseAbi(out) : undefined; | |
| 29 | if (abi === undefined) return { ok: false, reason: `landlock is not available (${(err.trim() || `ABI query exited ${code}`).split("\n").pop()})` }; | |
| 30 | return { ok: true, abi, note: landlockNote(landlockPlan(abi, { writable: [] })) }; | |
| 31 | } catch (error) { | |
| 32 | return { ok: false, reason: error instanceof Error ? error.message : String(error) }; | |
| 33 | } | |
| 34 | } |
test/crew-sandbox-boundary.test.ts +2 −2
| @@ -28,7 +28,7 @@ import { tmpdir } from "node:os"; | ||
| 28 | 28 | import { join } from "node:path"; |
| 29 | 29 | import { rgPath } from "@vscode/ripgrep"; |
| 30 | 30 | import { claudeSettings } from "../src/crew/claude.ts"; |
| 31 | import { ALWAYS_DENIED, sandboxAvailable, sandboxPolicy } from "../src/crew/sandbox.ts"; | |
| 31 | import { ALWAYS_DENIED, bwrapAvailable, sandboxPolicy } from "../src/crew/sandbox.ts"; | |
| 32 | 32 | import { sandboxCause, skipReason } from "../src/crew/sandbox_cause.ts"; |
| 33 | 33 | import { runtimeSettings, srtEnv } from "./helpers/srt.ts"; |
| 34 | 34 | |
| @@ -84,7 +84,7 @@ describe("the crew policy denies every path the boundary tries", () => { | ||
| 84 | 84 | }); |
| 85 | 85 | }); |
| 86 | 86 | |
| 87 | const probe = await sandboxAvailable(); | |
| 87 | const probe = await bwrapAvailable(); | |
| 88 | 88 | const srt = join(import.meta.dir, "../node_modules/.bin/srt"); |
| 89 | 89 | const skipShell = process.env["FORGE_TEST_SOCKET"] |
| 90 | 90 | ? "FORGE_TEST_SOCKET mode: srt binds a unix socket for each bridge to its proxy" |
test/crew-sandbox-escape.test.ts +2 −2
| @@ -43,10 +43,10 @@ import { tmpdir } from "node:os"; | ||
| 43 | 43 | import { join } from "node:path"; |
| 44 | 44 | import { rgPath } from "@vscode/ripgrep"; |
| 45 | 45 | import { claudeSettings } from "../src/crew/claude.ts"; |
| 46 | import { sandboxAvailable, sandboxPolicy } from "../src/crew/sandbox.ts"; | |
| 46 | import { bwrapAvailable, sandboxPolicy } from "../src/crew/sandbox.ts"; | |
| 47 | 47 | import { runtimeSettings, srtEnv } from "./helpers/srt.ts"; |
| 48 | 48 | |
| 49 | const probe = await sandboxAvailable(); | |
| 49 | const probe = await bwrapAvailable(); | |
| 50 | 50 | const srt = join(import.meta.dir, "../node_modules/.bin/srt"); |
| 51 | 51 | const nestedReason = !probe.ok |
| 52 | 52 | ? `no sandbox can be made here (nested in a crew sandbox or user namespaces refused): ${probe.reason}` |
test/crew-sandbox-floor.test.ts added +108
| @@ -0,0 +1,108 @@ | ||
| 1 | /** | |
| 2 | * The Landlock floor where bubblewrap cannot run (#16835): what the run may write, that it never | |
| 3 | * satisfies `FORGE_CREW_SANDBOX=require`, and what the crew does with the answer. | |
| 4 | */ | |
| 5 | import { afterEach, expect, test } from "bun:test"; | |
| 6 | import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; | |
| 7 | import { tmpdir } from "node:os"; | |
| 8 | import { join } from "node:path"; | |
| 9 | import { createApp } from "../src/app.ts"; | |
| 10 | import { createUser } from "../src/core/users.ts"; | |
| 11 | import { createRun } from "../src/core/runs.ts"; | |
| 12 | import { pump } from "../src/crew/dispatch.ts"; | |
| 13 | import type { CrewOptions } from "../src/crew/runner.ts"; | |
| 14 | import { sandboxAvailable, type SandboxPolicy } from "../src/crew/sandbox.ts"; | |
| 15 | import { accepted, noteSandbox, standingOptions } from "../src/crew/sandbox_policy.ts"; | |
| 16 | import { floorLine, floorWrap, floorWritable } from "../src/crew/sandbox_floor.ts"; | |
| 17 | import { readRunLog } from "../src/runs/log.ts"; | |
| 18 | import type { LandlockFloor } from "../src/crew/sandbox.ts"; | |
| 19 | ||
| 20 | const floor: LandlockFloor = { kind: "landlock", abi: 4, note: "landlock ABI 4: x; reads are not hidden" }; | |
| 21 | const policy = (withFloor?: LandlockFloor): SandboxPolicy => ({ | |
| 22 | allowHosts: [], denyRead: [], enforced: false, readAllow: [], tmpDir: "/data/t/run1", installCache: "/data/cache/r/bun", | |
| 23 | ...(withFloor === undefined ? {} : { floor: withFloor }), | |
| 24 | }); | |
| 25 | ||
| 26 | const dirs: string[] = []; | |
| 27 | afterEach(() => { | |
| 28 | while (dirs.length > 0) rmSync(dirs.pop()!, { recursive: true, force: true }); | |
| 29 | }); | |
| 30 | const dir = (): string => { | |
| 31 | const d = mkdtempSync(join(tmpdir(), "floor-")); | |
| 32 | dirs.push(d); | |
| 33 | return d; | |
| 34 | }; | |
| 35 | ||
| 36 | test("a run may write its clone, its own home and temp, the cache, and nothing of the forge user's", () => { | |
| 37 | const w = floorWritable(policy(), "/data/clone", { HOME: "/h", CLAUDE_CONFIG_DIR: "/h/.claude", TMPDIR: "/data/t/run1/claude-0" }); | |
| 38 | expect(w).toEqual(expect.arrayContaining(["/data/clone", "/data/t/run1/home", "/data/t/run1", "/data/cache/r/bun"])); | |
| 39 | for (const shared of ["/h", "/h/.claude", "/h/.bun", "/h/.npm", "/h/.cache"]) expect(w.some((p) => p === shared || p.startsWith(`${shared}/`))).toBe(false); | |
| 40 | }); | |
| 41 | ||
| 42 | test("the run gets a home of its own holding a copy of the login, and the shared config is not its home", () => { | |
| 43 | const forgeHome = dir(); | |
| 44 | mkdirSync(join(forgeHome, ".claude")); | |
| 45 | writeFileSync(join(forgeHome, ".claude", ".credentials.json"), '{"token":"t"}'); | |
| 46 | writeFileSync(join(forgeHome, ".claude", "settings.json"), "{}"); | |
| 47 | const tmp = dir(); | |
| 48 | const wrapped = floorWrap({ ...policy(floor), tmpDir: tmp }, "/c", { HOME: forgeHome }, ["claude", "-p"]); | |
| 49 | expect(wrapped?.env).toEqual({ HOME: join(tmp, "home"), CLAUDE_CONFIG_DIR: join(tmp, "home", ".claude") }); | |
| 50 | expect(readFileSync(join(tmp, "home", ".claude", ".credentials.json"), "utf8")).toBe('{"token":"t"}'); | |
| 51 | expect(existsSync(join(tmp, "home", ".claude", "settings.json"))).toBe(false); | |
| 52 | expect(wrapped?.argv.slice(-3)).toEqual(["--", "claude", "-p"]); | |
| 53 | expect(JSON.parse(wrapped!.argv[2]!).abi).toBe(4); | |
| 54 | }); | |
| 55 | ||
| 56 | test("no floor, no wrapping", () => { | |
| 57 | expect(floorWrap(policy(), "/c", {}, ["claude"])).toBeUndefined(); | |
| 58 | }); | |
| 59 | ||
| 60 | test("bubblewrap ok: no floor; bubblewrap failed and Landlock ok: the floor, saying reads are open; neither: both reasons", async () => { | |
| 61 | const bwrapOk = async () => ({ ok: true as const }); | |
| 62 | const bwrapNo = async () => ({ ok: false as const, reason: "bwrap is not installed" }); | |
| 63 | const landlockOk = async () => ({ ok: true as const, abi: 4, note: "landlock ABI 4: x" }); | |
| 64 | const landlockNo = async () => ({ ok: false as const, reason: "no landlock" }); | |
| 65 | expect(await sandboxAvailable(landlockOk, bwrapOk)).toEqual({ ok: true }); | |
| 66 | const held = await sandboxAvailable(landlockOk, bwrapNo); | |
| 67 | expect(held.ok && held.floor?.abi).toBe(4); | |
| 68 | expect(held.ok && held.floor?.note).toContain("reads are not hidden"); | |
| 69 | const none = await sandboxAvailable(landlockNo, bwrapNo); | |
| 70 | expect(none).toEqual({ ok: false, reason: "bwrap is not installed; no landlock" }); | |
| 71 | }); | |
| 72 | ||
| 73 | test("require does not accept the floor; the default does, and Claude Code's own sandbox stays off under it", () => { | |
| 74 | const probe = { ok: true as const, floor }; | |
| 75 | const strict = accepted(probe, true); | |
| 76 | expect(strict.ok).toBe(false); | |
| 77 | expect(!strict.ok && strict.reason).toContain("hides no reads"); | |
| 78 | expect(accepted(probe, false)).toBe(probe); | |
| 79 | expect(accepted({ ok: true }, true)).toEqual({ ok: true }); | |
| 80 | expect(standingOptions({ sandboxRequired: true }, probe)).toMatchObject({ sandboxEnforced: false }); | |
| 81 | expect(standingOptions({ sandboxRequired: true }, probe).sandboxFloor).toBeUndefined(); | |
| 82 | expect(standingOptions({}, probe)).toMatchObject({ sandboxEnforced: false, sandboxFloor: floor, sandboxNote: floor.note }); | |
| 83 | expect(standingOptions({}, { ok: true })).toMatchObject({ sandboxEnforced: true }); | |
| 84 | }); | |
| 85 | ||
| 86 | test("a run is held for the sandbox when it is required, even with a floor in the options", async () => { | |
| 87 | const data = dir(); | |
| 88 | const app = createApp({ dataDir: data, port: 0, disk: () => ({ freeBytes: 100, totalBytes: 100 }) }); | |
| 89 | try { | |
| 90 | const owner = await createUser(app.db, { origin: "seed", trusted: true, username: "sandboxer", email: "[email protected]", password: "a-good-passphrase" }); | |
| 91 | if (!owner.ok) throw new Error(String(owner.error)); | |
| 92 | const repoId = crypto.randomUUID(); | |
| 93 | app.db.query("INSERT INTO repo (id, owner_id, name, visibility, created_at) VALUES (?1, ?2, 'r', 'private', ?3)").run(repoId, owner.value.id, new Date().toISOString()); | |
| 94 | const queued = createRun(app.db, { repoId, kind: "agent" }); | |
| 95 | noteSandbox(app, true, { ok: false, reason: "only the Landlock floor" }, () => {}); | |
| 96 | const options = { forgeUrl: "http://127.0.0.1:1", localUrl: "http://127.0.0.1:1", binary: "/nonexistent", concurrency: 3, budgetUsd: 1, runTimeoutMs: 60_000, sandboxRequired: true, sandboxEnforced: false, sandboxFloor: floor } as unknown as CrewOptions; | |
| 97 | pump(app, options, new Map()); | |
| 98 | expect(readRunLog(data, queued.id).lines.join("\n")).toContain("queued, not started"); | |
| 99 | } finally { | |
| 100 | app.close(); | |
| 101 | } | |
| 102 | }); | |
| 103 | ||
| 104 | test("a run's log says the floor holds it, and that reads are open", () => { | |
| 105 | const line = floorLine(floor); | |
| 106 | expect(line).toContain("bubblewrap is unavailable here"); | |
| 107 | expect(line).toContain("reads are not hidden"); | |
| 108 | }); |
test/crew-sandbox-real.test.ts +2 −2
| @@ -32,11 +32,11 @@ import { tmpdir } from "node:os"; | ||
| 32 | 32 | import { join } from "node:path"; |
| 33 | 33 | import { rgPath } from "@vscode/ripgrep"; |
| 34 | 34 | import { claudeSettings } from "../src/crew/claude.ts"; |
| 35 | import { sandboxAvailable, sandboxPolicy } from "../src/crew/sandbox.ts"; | |
| 35 | import { bwrapAvailable, sandboxPolicy } from "../src/crew/sandbox.ts"; | |
| 36 | 36 | import { sandboxCause, skipReason } from "../src/crew/sandbox_cause.ts"; |
| 37 | 37 | import { runtimeSettings, srtEnv } from "./helpers/srt.ts"; |
| 38 | 38 | |
| 39 | const probe = await sandboxAvailable(); | |
| 39 | const probe = await bwrapAvailable(); | |
| 40 | 40 | const srt = join(import.meta.dir, "../node_modules/.bin/srt"); |
| 41 | 41 | // One named cause (src/crew/sandbox_cause.ts), so the skip line tells a host |
| 42 | 42 | // that cannot sandbox from a hole in the gate (#10745). |
test/crew-sandbox.test.ts +3 −3
| @@ -42,7 +42,7 @@ import { LOOPBACK, probe } from "../scripts/sandbox-probe.ts"; | ||
| 42 | 42 | import { |
| 43 | 43 | dataInTemp, |
| 44 | 44 | SandboxListingError, |
| 45 | sandboxAvailable, | |
| 45 | bwrapAvailable, | |
| 46 | 46 | runTmpDir, |
| 47 | 47 | longestSocketPath, |
| 48 | 48 | SOCKET_PATH_BUDGET, |
| @@ -181,7 +181,7 @@ describe("the shell sandbox", () => { | ||
| 181 | 181 | }); |
| 182 | 182 | |
| 183 | 183 | test("the probe answers with a reason when it cannot", async () => { |
| 184 | const probe = await sandboxAvailable(); | |
| 184 | const probe = await bwrapAvailable(); | |
| 185 | 185 | if (process.platform === "darwin") expect(probe).toEqual({ ok: true }); |
| 186 | 186 | else if (!probe.ok) expect(probe.reason.length).toBeGreaterThan(0); |
| 187 | 187 | }); |
| @@ -579,7 +579,7 @@ echo '{"type":"result","subtype":"success","is_error":false,"result":"ok","total | ||
| 579 | 579 | // `startCrew` probes the host itself, so the run is sandboxed exactly |
| 580 | 580 | // where this host can hold it to one; the env must follow that. |
| 581 | 581 | test("a sandboxed run carries FORGE_TEST_SOCKET=port, an unsandboxed one does not; a real push meets the pre-receive verdict over the port", async () => { |
| 582 | const enforced = (await sandboxAvailable()).ok; | |
| 582 | const enforced = (await bwrapAvailable()).ok; | |
| 583 | 583 | const r = await runWith(); |
| 584 | 584 | expect(r.env).toBe(enforced ? "port" : "unset"); |
| 585 | 585 | expect(r.address).toMatch(/^tcp:/); |
test/crew.test.ts +2 −2
| @@ -21,7 +21,7 @@ import { proposeResolution } from "../src/crew/proposal.ts"; | ||
| 21 | 21 | import { convergeFork } from "../src/crew/converge.ts"; |
| 22 | 22 | import { convergeWords } from "../src/actions/follow.ts"; |
| 23 | 23 | import { assignIssue, openIssue } from "../src/actions/issues.ts"; |
| 24 | import { sandboxAvailable } from "../src/crew/sandbox.ts"; | |
| 24 | import { bwrapAvailable } from "../src/crew/sandbox.ts"; | |
| 25 | 25 | import type { CrewHandle } from "../src/crew/dispatch.ts"; |
| 26 | 26 | import { workdirFor } from "../src/crew/runner.ts"; |
| 27 | 27 | import { getAgentByName } from "../src/core/agents.ts"; |
| @@ -108,7 +108,7 @@ describe("the crew, with a stand-in Claude Code", () => { | ||
| 108 | 108 | }; |
| 109 | 109 | // Enforced where this host can hold a run to it; switched off, and said |
| 110 | 110 | // so, where it cannot (a locked-down container has no bubblewrap). |
| 111 | expect(settings.sandbox.enabled).toBe((await sandboxAvailable()).ok); | |
| 111 | expect(settings.sandbox.enabled).toBe((await bwrapAvailable()).ok); | |
| 112 | 112 | const domains = settings.sandbox.network.allowedDomains; |
| 113 | 113 | expect(domains).toContain(new URL(servers.url).host); |
| 114 | 114 | expect(domains).not.toContain("127.0.0.1"); |
test/helpers/preload.ts +3
| @@ -16,6 +16,9 @@ import { SCRATCH_ROOT } from "./scratch.ts"; | ||
| 16 | 16 | import { join } from "node:path"; |
| 17 | 17 | |
| 18 | 18 | installCheapHash(); |
| 19 | // Fakes in the suite write wherever they like; the Landlock floor (#16835) is proved in | |
| 20 | // landlock.test.ts. | |
| 21 | process.env["FORGE_LANDLOCK"] = "off"; | |
| 19 | 22 | // Defaults sized from CPUs (#2549) read as on a 4-CPU pod — 4 shards, one |
| 20 | 23 | // check at once — whatever machine runs the suite. |
| 21 | 24 | provideCpusForTest(4); |
test/landlock-real.test.ts added +69
| @@ -0,0 +1,69 @@ | ||
| 1 | /** | |
| 2 | * The Landlock floor run for real (#16835), where the kernel and the host allow it; each part is | |
| 3 | * skipped, and so named, where it does not. The parts: stacked under a real bubblewrap cell (the | |
| 4 | * helper and `bun` must be visible inside it, or every check on that host would fail), and a check | |
| 5 | * that has no cell and is held by the floor alone (`checks/run_tier.ts`). | |
| 6 | */ | |
| 7 | import { afterAll, describe, expect, test } from "bun:test"; | |
| 8 | import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs"; | |
| 9 | import { tmpdir } from "node:os"; | |
| 10 | import { join } from "node:path"; | |
| 11 | import { cellsAvailable, openCell } from "../src/apps/contain.ts"; | |
| 12 | import { cellSpecFor } from "../src/spawn/cell.ts"; | |
| 13 | import { probeLandlock } from "../src/sandbox/landlock_probe.ts"; | |
| 14 | import { readRunLog } from "../src/runs/log.ts"; | |
| 15 | import { checksForge } from "./helpers/checks-forge.ts"; | |
| 16 | import { quietLogs } from "./helpers/globals.ts"; | |
| 17 | ||
| 18 | quietLogs(); | |
| 19 | const kernel = process.platform === "linux" ? await probeLandlock({}) : { ok: false as const, reason: "not linux" }; | |
| 20 | const tmp = mkdtempSync(join(tmpdir(), "landlock-real-")); | |
| 21 | afterAll(() => rmSync(tmp, { recursive: true, force: true })); | |
| 22 | ||
| 23 | describe("stacked under a real cell", () => { | |
| 24 | test.skipIf(!kernel.ok || process.env["FORGE_TEST_SOCKET"] !== undefined)("bun and the helper run inside the cell, it writes only where the cell does", async () => { | |
| 25 | if (!kernel.ok) return; | |
| 26 | const cells = await cellsAvailable(); | |
| 27 | if (!cells.ok) return; | |
| 28 | const parent = join(tmp, "parent"); | |
| 29 | const dir = join(parent, "children", "c1"); | |
| 30 | mkdirSync(dir, { recursive: true }); | |
| 31 | const spec = { ...cellSpecFor({ dir, parentDataDir: parent, parentUrl: "https://f.test", size: "small", port: 4998, label: "forge:landlock" }), floor: { abi: kernel.abi } }; | |
| 32 | const cell = openCell(spec); | |
| 33 | try { | |
| 34 | const proc = Bun.spawn(cell.argv(`echo own > ${dir}/mine; echo ran; echo x > /usr/forge-landlock-probe 2>/dev/null; echo $?`), { env: cell.env({ PATH: process.env["PATH"] ?? "" }), stdout: "pipe", stderr: "pipe" }); | |
| 35 | const out = await new Response(proc.stdout).text(); | |
| 36 | const err = await new Response(proc.stderr).text(); | |
| 37 | expect(await proc.exited, err).toBe(0); | |
| 38 | expect(out.split("\n")[0]).toBe("ran"); | |
| 39 | expect(out.trim().split("\n").pop()).not.toBe("0"); | |
| 40 | expect(readFileSync(join(dir, "mine"), "utf8")).toBe("own\n"); | |
| 41 | } finally { | |
| 42 | cell.close(); | |
| 43 | } | |
| 44 | }); | |
| 45 | }); | |
| 46 | ||
| 47 | describe("a check with no cell is held by the floor", () => { | |
| 48 | const f = checksForge("forge-floor-"); | |
| 49 | const outside = join(tmp, "outside"); | |
| 50 | test.skipIf(!kernel.ok)("it writes its checkout and temp, is refused elsewhere, and the log says reads are open", async () => { | |
| 51 | const was = { cells: process.env["FORGE_CELLS"], landlock: process.env["FORGE_LANDLOCK"] }; | |
| 52 | process.env["FORGE_CELLS"] = "off"; | |
| 53 | delete process.env["FORGE_LANDLOCK"]; | |
| 54 | try { | |
| 55 | mkdirSync(outside, { recursive: true }); | |
| 56 | const command = `echo a > inside && echo b > "$TMPDIR/t" && case "$TMPDIR" in *.tmp) ;; *) exit 3;; esac; if sh -c 'echo c > ${outside}/f' 2>/dev/null; then exit 4; fi`; | |
| 57 | const made = await f.slowCheck(command, "floor check"); | |
| 58 | const run = await f.settled((r) => r.id === made); | |
| 59 | expect(readRunLog(f.dataDir, run.id).lines.join("\n")).toContain("reads are not hidden"); | |
| 60 | expect(run.state).toBe("ok"); | |
| 61 | expect(existsSync(join(outside, "f"))).toBe(false); | |
| 62 | } finally { | |
| 63 | for (const [key, value] of [["FORGE_CELLS", was.cells], ["FORGE_LANDLOCK", was.landlock]] as const) { | |
| 64 | if (value === undefined) delete process.env[key]; | |
| 65 | else process.env[key] = value; | |
| 66 | } | |
| 67 | } | |
| 68 | }); | |
| 69 | }); |
test/landlock.test.ts added +98
| @@ -0,0 +1,98 @@ | ||
| 1 | import { describe, expect, test } from "bun:test"; | |
| 2 | import { mkdtempSync, readFileSync, rmSync } from "node:fs"; | |
| 3 | import { tmpdir } from "node:os"; | |
| 4 | import { join } from "node:path"; | |
| 5 | import { NET_CONNECT_TCP, SCOPE_SIGNAL, landlockArgv, landlockNote, landlockPlan, validWant } from "../src/sandbox/landlock.ts"; | |
| 6 | import { parseAbi, probeLandlock } from "../src/sandbox/landlock_probe.ts"; | |
| 7 | ||
| 8 | describe("landlockPlan", () => { | |
| 9 | test("ABI 1 handles the 13 filesystem rights and names everything the kernel lacks", () => { | |
| 10 | const plan = landlockPlan(1, { writable: ["/w"], connect: [3128] }); | |
| 11 | expect(plan.handledFs).toBe((1 << 13) - 1); | |
| 12 | expect(plan.handledNet).toBe(0); | |
| 13 | expect(plan.scoped).toBe(0); | |
| 14 | expect(plan.stripped).toEqual(expect.arrayContaining(["fs refer (needs ABI 2)", "fs truncate (needs ABI 3)", "fs ioctl_dev (needs ABI 5)", "tcp connect (needs ABI 4)", "abstract-socket and signal scope (needs ABI 6)"])); | |
| 15 | }); | |
| 16 | test("ABI 4 adds tcp connect, ABI 6 adds scopes", () => { | |
| 17 | const four = landlockPlan(4, { writable: [], connect: [3128] }); | |
| 18 | expect(four.handledNet).toBe(NET_CONNECT_TCP); | |
| 19 | expect(four.scoped).toBe(0); | |
| 20 | const six = landlockPlan(6, { writable: [] }); | |
| 21 | expect(six.scoped & SCOPE_SIGNAL).toBe(SCOPE_SIGNAL); | |
| 22 | expect(six.handledFs).toBe((1 << 16) - 1); | |
| 23 | expect(six.handledNet).toBe(0); // tcp left alone unless asked | |
| 24 | expect(six.stripped).toEqual([]); | |
| 25 | }); | |
| 26 | test("the note names the ABI and always says udp is not covered", () => { | |
| 27 | expect(landlockNote(landlockPlan(6, { writable: [], connect: [3128] }))).toBe( | |
| 28 | "landlock ABI 6: filesystem read-only outside the workspace; tcp connect to port 3128 only; signals and abstract sockets scoped; not enforced: udp (not covered before ABI 10)", | |
| 29 | ); | |
| 30 | expect(landlockNote(landlockPlan(3, { writable: [] }))).toContain("abstract-socket and signal scope (needs ABI 6)"); | |
| 31 | }); | |
| 32 | }); | |
| 33 | ||
| 34 | describe("landlockArgv", () => { | |
| 35 | test("puts the plan and the command behind the helper", () => { | |
| 36 | const argv = landlockArgv(landlockPlan(6, { writable: ["/w"] }), ["sh", "-c", "true"], "bun"); | |
| 37 | expect(argv[0]).toBe("bun"); | |
| 38 | expect(argv.slice(-4)).toEqual(["--", "sh", "-c", "true"]); | |
| 39 | expect(JSON.parse(argv[2]!).writable).toEqual(["/w"]); | |
| 40 | }); | |
| 41 | test("refuses a relative path or a port out of range", () => { | |
| 42 | expect(validWant({ writable: ["rel"] })).toBe(false); | |
| 43 | expect(validWant({ writable: ["/ok"], connect: [0] })).toBe(false); | |
| 44 | expect(validWant({ writable: ["/ok"], connect: [3128] })).toBe(true); | |
| 45 | expect(() => landlockArgv(landlockPlan(6, { writable: ["rel"] }), ["x"])).toThrow(); | |
| 46 | }); | |
| 47 | }); | |
| 48 | ||
| 49 | test("FORGE_LANDLOCK=off declines the floor", async () => { | |
| 50 | expect(await probeLandlock({ FORGE_LANDLOCK: "off" })).toEqual({ ok: false, reason: "FORGE_LANDLOCK=off" }); | |
| 51 | }); | |
| 52 | ||
| 53 | test("parseAbi takes a positive integer only", () => { | |
| 54 | expect(parseAbi("6\n")).toBe(6); | |
| 55 | expect(parseAbi("0")).toBeUndefined(); | |
| 56 | expect(parseAbi("x")).toBeUndefined(); | |
| 57 | }); | |
| 58 | ||
| 59 | // The kernel is the judge: skipped (and so named) where this host has no Landlock. | |
| 60 | const probe = process.platform === "linux" ? await probeLandlock({}) : { ok: false as const, reason: "not linux" }; | |
| 61 | describe.skipIf(!probe.ok)("on this kernel", () => { | |
| 62 | test("the helper writes where allowed, is refused elsewhere, and the command still runs", () => { | |
| 63 | if (!probe.ok) return; | |
| 64 | const ok = mkdtempSync(join(tmpdir(), "ll-ok-")); | |
| 65 | const no = mkdtempSync(join(tmpdir(), "ll-no-")); | |
| 66 | try { | |
| 67 | const plan = landlockPlan(probe.abi, { writable: [ok] }); | |
| 68 | const run = Bun.spawnSync(landlockArgv(plan, ["/bin/sh", "-c", `echo yes > ${ok}/f; echo $? ; echo no > ${no}/f 2>/dev/null; echo $?`]), { stdout: "pipe", stderr: "pipe" }); | |
| 69 | const [a, b] = run.stdout.toString().trim().split("\n"); | |
| 70 | expect(a).toBe("0"); | |
| 71 | expect(b).not.toBe("0"); | |
| 72 | expect(readFileSync(join(ok, "f"), "utf8")).toBe("yes\n"); | |
| 73 | expect(() => readFileSync(join(no, "f"))).toThrow(); | |
| 74 | } finally { | |
| 75 | rmSync(ok, { recursive: true }); | |
| 76 | rmSync(no, { recursive: true }); | |
| 77 | } | |
| 78 | }); | |
| 79 | test("a plan the kernel refuses exits 126 and never runs the command", () => { | |
| 80 | const plan = { ...landlockPlan(1, { writable: [] }), handledFs: 1 << 30 }; | |
| 81 | const run = Bun.spawnSync(landlockArgv(plan, ["/bin/echo", "ran"]), { stdout: "pipe", stderr: "pipe" }); | |
| 82 | expect(run.exitCode).toBe(126); | |
| 83 | expect(run.stdout.toString()).toBe(""); | |
| 84 | }); | |
| 85 | }); | |
| 86 | ||
| 87 | describe("stacked under a cell", () => { | |
| 88 | test("floored wraps the cell's command at the probed ABI, writable only where the cell writes", async () => { | |
| 89 | const { floored } = await import("../src/apps/contain.ts"); | |
| 90 | const floor = { ok: true as const, abi: 5, note: "n" }; | |
| 91 | const argv = floored({ dir: "/w", home: "/w.home", writable: ["/x"] }, ["/bin/sh", "-c", "true"], floor); | |
| 92 | expect(argv.slice(-4)).toEqual(["--", "/bin/sh", "-c", "true"]); | |
| 93 | const plan = JSON.parse(argv[2]!); | |
| 94 | expect(plan.abi).toBe(5); | |
| 95 | expect(plan.writable).toEqual(["/w", "/w.home", "/x", "/tmp", "/dev", "/run/forge"]); | |
| 96 | expect(floored({ dir: "/w", home: "/h", writable: [] }, ["/bin/sh"], undefined)).toEqual(["/bin/sh"]); | |
| 97 | }); | |
| 98 | }); |
test/openai-real-cell.test.ts +2 −2
| @@ -13,7 +13,7 @@ import { afterAll, expect, test } from "bun:test"; | ||
| 13 | 13 | import { mkdtempSync, readFileSync, rmSync } from "node:fs"; |
| 14 | 14 | import { tmpdir } from "node:os"; |
| 15 | 15 | import { join } from "node:path"; |
| 16 | import { sandboxAvailable } from "../src/crew/sandbox.ts"; | |
| 16 | import { bwrapAvailable } from "../src/crew/sandbox.ts"; | |
| 17 | 17 | import { runOpenAI } from "../src/crew/openai_runner.ts"; |
| 18 | 18 | import type { AgentRun } from "../src/crew/agent_runner.ts"; |
| 19 | 19 | import { portInsteadOfSocket } from "../src/git/hook-address.ts"; |
| @@ -21,7 +21,7 @@ import { ANCHOR } from "./helpers/build-standin.ts"; | ||
| 21 | 21 | import { writeTemplate } from "./helpers/template-app.ts"; |
| 22 | 22 | import { scriptedEndpoint } from "./fixtures/openai-stub.ts"; |
| 23 | 23 | |
| 24 | const cells = portInsteadOfSocket() ? { ok: false as const, reason: "FORGE_TEST_SOCKET=port: no unix sockets" } : await sandboxAvailable(); | |
| 24 | const cells = portInsteadOfSocket() ? { ok: false as const, reason: "FORGE_TEST_SOCKET=port: no unix sockets" } : await bwrapAvailable(); | |
| 25 | 25 | if (!cells.ok) console.log(`SKIPPING: no real cell here (${cells.reason})`); |
| 26 | 26 | |
| 27 | 27 | const dirs: string[] = []; |
test/openai-runner-escape.test.ts +2 −2
| @@ -23,7 +23,7 @@ import { join } from "node:path"; | ||
| 23 | 23 | import type { AgentRun } from "../src/crew/agent_runner.ts"; |
| 24 | 24 | import { bashArgv, callTool, runOpenAI, runShell, shellEnv } from "../src/crew/openai_runner.ts"; |
| 25 | 25 | import { jailArgv, jailEgressPolicy, openJailEgress, socketBase } from "../src/crew/openai_jail.ts"; |
| 26 | import { installCacheEnv, sandboxAvailable, sandboxPolicy } from "../src/crew/sandbox.ts"; | |
| 26 | import { installCacheEnv, bwrapAvailable, sandboxPolicy } from "../src/crew/sandbox.ts"; | |
| 27 | 27 | import { sandboxCause, skipReason } from "../src/crew/sandbox_cause.ts"; |
| 28 | 28 | import { decide } from "../src/apps/egress.ts"; |
| 29 | 29 | import { parseDeclaration } from "../src/crew/grant.ts"; |
| @@ -101,7 +101,7 @@ describe("item 1: Bash is held to the run's sandbox policy", () => { | ||
| 101 | 101 | |
| 102 | 102 | // A real bubblewrap, and a Unix socket for the proxy: where either cannot be made (a crew run's own |
| 103 | 103 | // sandbox, FORGE_TEST_SOCKET), this part is skipped and says why; the forge's check runs it. |
| 104 | const probe = await sandboxAvailable(); | |
| 104 | const probe = await bwrapAvailable(); | |
| 105 | 105 | const realReason = !probe.ok ? skipReason(sandboxCause(probe.reason)) : process.env["FORGE_TEST_SOCKET"] ? "a Unix socket cannot be bound here (FORGE_TEST_SOCKET)" : undefined; |
| 106 | 106 | if (realReason !== undefined) console.warn(`skipped: test/openai-runner-escape.test.ts real bubblewrap: ${realReason}`); |
| 107 | 107 |
test/spawn-pipes.test.ts +1
| @@ -48,6 +48,7 @@ const PIPING: Record<string, { sites: string[]; reason: string }> = { | ||
| 48 | 48 | "src/release/boot.ts": { sites: ["stderr"], reason: "stderr read to its end in a background loop, awaited before the reason is read; stdout ignored" }, |
| 49 | 49 | "src/release/small_forge.ts": { sites: ["stderr", "stdout"], reason: "run() reads each git stderr to its end via Response.text() before the exit is awaited, stdout ignored; spawnSync buffers rev-parse stdout, stderr ignored" }, |
| 50 | 50 | "src/snapshot/kit.ts": { sites: ["stdout+stderr"], reason: "the restore child's stdout is read to its end for the restored snapshot id and stderr for the failure text, alongside the exit" }, |
| 51 | "src/sandbox/landlock_probe.ts": { sites: ["stdout+stderr"], reason: "the helper's --abi answer and its failure text are read to the end via Response.text() while the exit is awaited, under a kill deadline" }, | |
| 51 | 52 | "src/snapshot/boot.ts": { sites: ["stderr"], reason: "stderr read to its end in a background loop, awaited before the exit is read for a lost port; stdout ignored" }, |
| 52 | 53 | "src/release/checkout.ts": { sites: ["stdout+stderr"], reason: "stdout and stderr both read via Response.text()" }, |
| 53 | 54 | "src/checks/deepsec_tool.ts": { sites: ["stdout+stderr"], reason: "the deepsec install reads stdout and stderr to the end via Response.text() while the exit is awaited" }, |
test/spawn-sites.test.ts +2
| @@ -53,6 +53,8 @@ const SITES: Record<string, string> = { | ||
| 53 | 53 | "the planner binary with a fixed flag list; the issue text a person wrote is only the final prompt element, with tools disabled", |
| 54 | 54 | "src/crew/runner.ts": |
| 55 | 55 | "`lsof -t +D <dir>` on the workdir path the forge derived from validated agent, repo and number", |
| 56 | "src/sandbox/landlock_probe.ts": | |
| 57 | "runs this runtime on the repository's own Landlock helper with the fixed argv `--abi`; no text from a person reaches argv", | |
| 56 | 58 | "src/crew/sandbox.ts": |
| 57 | 59 | "probes bwrap with a fixed argv ending in /bin/true", |
| 58 | 60 | "src/crew/workdir.ts": |
test/timers-named.test.ts +1
| @@ -89,6 +89,7 @@ const ALLOWED: readonly Allowed[] = [ | ||
| 89 | 89 | ...allow("setTimeout", `a shell session's resize debounce, ${PER_CONNECTION}`, [["src/machines/shell.ts", "() => session.size === resize"]]), |
| 90 | 90 | ...allow("setTimeout", "the fork-offers list's size budget: one per page render, cleared when the render ends, resolves a promise and runs nothing", [["src/git/offer_size.ts", "done"]]), |
| 91 | 91 | ...allow("setTimeout", "the template-head wait's bound: one per page render, cleared when the reads land or the bound passes, resolves a promise and runs nothing", [["src/spawn/template_head.ts", "done"]]), |
| 92 | ...allow("setTimeout", "the Landlock probe's kill deadline: one per probe, a one-shot kill of one child, cleared when it exits", [["src/sandbox/landlock_probe.ts", "() => proc.kill("]]), | |
| 92 | 93 | ...allow("setTimeout", `an openai runner bash call's kill deadline, ${PER_CONNECTION}`, [["src/crew/openai_runner.ts", "() => { timedOut = true"]]), |
| 93 | 94 | ...allow("setTimeout", SLEEP, [["src/crew/openai_runner.ts", "r"]]), |
| 94 | 95 | ...allow("setTimeout", DEADLINE, [ |
new above
offline
Shared, forge-user state writable by an agent shell: ~/.bun, ~/.npm, ~/.cache and (above) CLAUDE_CONFIG_DIR. This allows persistence and code planting for later runs and the forge. Use per-run copies.