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

Forges sharing a machine each get a cgroup and a sandbox, so no neighbour starves or reads another #16938

Merged opened this

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

Merged

mason/forge:mason/16856-forges-sharing-a-machine-each-get-a-cgro → main 0 commits fork

  • Merged. mason/16856-forges-sharing-a-machine-each-get-a-cgro was merged into main as 1857b5e.

Review

Sign in to review this change.
9 files changed +245 −25
docs/features/landlock-floor.md +11 −2
@@ -21,8 +21,17 @@ holds the work instead, with no root and no namespace.
2121 `reads are not hidden`, and what that kernel did not enforce.
2222 - **Checks.** Under bubblewrap the step command is also wrapped in Landlock (stacked, inside the
2323 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.
24 a temp directory of its own (not the machine's `/tmp`); the log line names the ABI and says what
25 reads stay open. Its reads are held too: the forge's data directory (its database, its key, every
26 other check's checkout, a neighbour's files) is not readable, only the check's own directories
27 and the install cache under it. Landlock only adds rights, so the plan (`readRootsAround`) grants
28 every sibling along the way to the hidden path instead of `/`; a hidden path's parent cannot be
29 listed, a link is never granted, and hidden paths are planned by their real name (one that cannot
30 be resolved fails the plan). No other process's `/proc/<pid>` is readable (its environment and
31 open files are the forge's own); the step's own is. A check can write `/dev/null`. This holds
32 checks only: hosted child forges on a host with Landlock and no bubblewrap are not yet held this
33 way (`hide` and `keep` exist in the plan for it); under bubblewrap they are covered by the
34 mounts and cgroups.
2635 - **Never silent.** The kernel's ABI is probed; rights it lacks are dropped and named. UDP is never
2736 covered before ABI 10 and every record says so.
2837 - `FORGE_LANDLOCK=off` declines the floor on purpose.
src/apps/process.ts +3 −3
@@ -10,7 +10,7 @@
1010 * app, not to a shell that would swallow it.
1111 */
1212
13 import { landlockArgv, landlockPlan } from "../sandbox/landlock.ts";
13 import { type LandlockWant, landlockArgv, landlockPlan } from "../sandbox/landlock.ts";
1414 import type { AppManifest } from "./manifest.ts";
1515 import type { EnvName } from "./data.ts";
1616 import { envPull } from "./data.ts";
@@ -391,7 +391,7 @@ export async function runStep(
391391 * Where no cell can be made: the Landlock floor the plain child is exec-wrapped in (#16835).
392392 * Writable: its directory and `writable`; read-only elsewhere.
393393 */
394 floor?: { readonly abi: number; readonly writable: readonly string[] } | undefined;
394 floor?: (Pick<LandlockWant, "writable" | "hide" | "keep"> & { readonly abi: number }) | undefined;
395395 /**
396396 * Set for a build step (install, test): its limits. The time is the
397397 * step's bound, and a stop by any limit is one line saying which.
@@ -422,7 +422,7 @@ export async function runStep(
422422 let proc: ReturnType<typeof Bun.spawn<"ignore", "pipe", "pipe">>;
423423 try {
424424 const plain = ["/bin/sh", "-c", command];
425 const floored = options.floor === undefined ? plain : landlockArgv(landlockPlan(options.floor.abi, { writable: options.floor.writable }), plain);
425 const floored = options.floor === undefined ? plain : landlockArgv(landlockPlan(options.floor.abi, options.floor), plain);
426426 proc = Bun.spawn(backgroundArgv(cell?.argv(command) ?? floored), {
427427 cwd: options.cwd,
428428 env: cell?.env(options.env) ?? options.env,
src/checks/floor.ts added +16
@@ -0,0 +1,16 @@
1 /**
2 * What a check with no cell is held by: the Landlock floor around its own directories (#16856).
3 */
4 import { checkInstallCache } from "./install.ts";
5 import type { LandlockWant } from "../sandbox/landlock.ts";
6
7 /**
8 * The floor for a check run in `dir`: it writes its checkout, its home and a temp directory of its
9 * own (never the machine's /tmp, which other users share) and `/dev/null`, so `2>/dev/null` works.
10 * The forge's data (its database, its key, every other check's checkout) is not its to read; its
11 * own directories and the install cache stay.
12 */
13 export function checkFloor(abi: number, dir: string, dataDir: string, repoId: string): Pick<LandlockWant, "writable" | "hide" | "keep"> & { abi: number } {
14 const own = [dir, `${dir}.home`, `${dir}.tmp`];
15 return { abi, writable: [...own, "/dev/null"], hide: [dataDir], keep: [...own, checkInstallCache(dataDir, repoId)] };
16 }
src/checks/run_tier.ts +6 −7
@@ -1,5 +1,6 @@
11
2 import { CHECK_FLOOR_ENV, READS_OPEN } from "../sandbox/landlock.ts";
2 import { checkFloor } from "./floor.ts";
3 import { CHECK_FLOOR_ENV, READS_PARTLY } from "../sandbox/landlock.ts";
34 import { probeLandlock } from "../sandbox/landlock_probe.ts";
45 import { cellHides } from "../spawn/hosted-mark.ts";
56 import { forgeApiKey } from "../crew/runner_env.ts";
@@ -208,7 +209,7 @@ async function runTierOnce(lane: LaneState, x: Execution, sample: (green: LentGr
208209 write("placement: job skipped, this cluster names no egress gate for a Job (FORGE_CHECKS_EGRESS_GATE)");
209210 // A Job is its own boundary: no cell here, the cluster and its gate hold it.
210211 const cells = job === undefined ? await cellsAvailable() : undefined;
211 let floor: { abi: number; writable: string[] } | undefined;
212 let floor: ReturnType<typeof checkFloor> | undefined;
212213 if (cells !== undefined) {
213214 if (x.runId !== undefined)
214215 noteRunProgress(app.db, x.runId, {
@@ -219,10 +220,8 @@ async function runTierOnce(lane: LaneState, x: Execution, sample: (green: LentGr
219220 // (#16835).
220221 const held = await probeLandlock();
221222 if (held.ok) {
222 // The checkout, its home and a temp directory of this check's own: never the machine's
223 // /tmp, which other users share.
224 floor = { abi: held.abi, writable: [dir, `${dir}.home`, `${dir}.tmp`] };
225 const note = `${held.note}; ${READS_OPEN}`;
223 floor = checkFloor(held.abi, dir, app.config.dataDir, repo.id);
224 const note = `${held.note}; ${READS_PARTLY}`;
226225 if (x.runId !== undefined) noteRunProgress(app.db, x.runId, { sandbox: { enforced: true, note } });
227226 write(`no cell here: ${cells.reason}; the check step is held by ${note}`);
228227 } else write(`uncontained here: ${cells.reason}; ${held.reason}; the check runs unrestricted`);
@@ -262,7 +261,7 @@ async function runTierOnce(lane: LaneState, x: Execution, sample: (green: LentGr
262261 const cellCpus = resolveLimits("step", manifest.limits).cpus;
263262 const shardCpus = checkShardCpus(cellCpus);
264263 write(shardsLine(shardsInForce(app.db, shardCpus, x.tier === "verify")));
265 if (floor !== undefined) for (const path of floor.writable) mkdirSync(path, { recursive: true });
264 if (floor !== undefined) for (const path of floor.writable.filter((p) => !p.startsWith("/dev/"))) mkdirSync(path, { recursive: true });
266265 const env = childEnv({
267266 // The shard count an admin set (`core/capacity.ts`), else the
268267 // default sized to what this check's cell holds, never the pod's.
src/sandbox/landlock.ts +96 −5
@@ -13,6 +13,8 @@
1313 * arrived in ABI 10), so every run record says it is not.
1414 */
1515
16 import { lstatSync, readdirSync, realpathSync } from "node:fs";
17
1618 /** Filesystem access bits, by the ABI that introduced them (include/uapi/linux/landlock.h). */
1719 const FS_BITS: readonly (readonly [string, number, number])[] = [
1820 ["execute", 0, 1], ["write_file", 1, 1], ["read_file", 2, 1], ["read_dir", 3, 1],
@@ -31,6 +33,13 @@ export interface LandlockWant {
3133 readonly writable: readonly string[];
3234 /** TCP connect allowed to these ports only; undefined leaves TCP unconfined. */
3335 readonly connect?: readonly number[] | undefined;
36 /**
37 * Paths whose contents are not readable at all (a neighbour forge's data, the host's own). The
38 * rest of the machine stays readable, except `keep`: places under a hidden path that are shown
39 * again (a forge's own directory).
40 */
41 readonly hide?: readonly string[] | undefined;
42 readonly keep?: readonly string[] | undefined;
3443 }
3544
3645 export interface LandlockPlan {
@@ -43,12 +52,18 @@ export interface LandlockPlan {
4352 readonly writable: readonly string[];
4453 /** Allowed connect ports; meaningful only when `handledNet` is not 0. */
4554 readonly connect: readonly number[];
55 /**
56 * Where reads are allowed, when some path is hidden: Landlock only adds, so "everything but" is
57 * every sibling along the way to a hidden path. Empty means the whole filesystem (`/`).
58 */
59 readonly readRoots: readonly string[];
4660 /** What was asked for and the kernel cannot hold: never silent. */
4761 readonly stripped: readonly string[];
4862 }
4963
5064 /** The plan for `want` on a kernel of `abi`: what the kernel lacks is dropped and named. */
5165 export function landlockPlan(abi: number, want: LandlockWant): LandlockPlan {
66 if (!validWant(want)) throw new Error("landlock: unsafe request");
5267 const stripped: string[] = [];
5368 let handledFs = 0;
5469 for (const [, bit, since] of FS_BITS) if (abi >= since) handledFs |= 1 << bit;
@@ -62,12 +77,84 @@ export function landlockPlan(abi: number, want: LandlockWant): LandlockPlan {
6277 let scoped = 0;
6378 if (abi >= 6) scoped = SCOPE_ABSTRACT_UNIX | SCOPE_SIGNAL;
6479 else stripped.push("abstract-socket and signal scope (needs ABI 6)");
65 return { abi, handledFs, handledNet, scoped, writable: want.writable, connect: want.connect ?? [], stripped };
80 const hide = (want.hide ?? []).map(resolveHidden);
81 const readRoots = hide.length === 0 ? [] : readRootsAround(hide, (want.keep ?? []).flatMap(resolveKept));
82 return { abi, handledFs, handledNet, scoped, writable: want.writable, connect: want.connect ?? [], readRoots, stripped };
83 }
84
85 /**
86 * A hidden path by its real name: reached through a link (`/data` -> `/mnt/x`), the walk would
87 * grant the real place as an ordinary sibling. A path that cannot be resolved cannot be hidden, so
88 * it throws: the plan fails closed rather than quietly leaving it readable.
89 */
90 function resolveHidden(path: string): string {
91 try {
92 return realpathSync(path);
93 } catch {
94 throw new Error(`landlock: cannot resolve hidden path ${path}`);
95 }
96 }
97
98 /** A kept path by its real name; one that is not there grants nothing, so it is left out. */
99 function resolveKept(path: string): string[] {
100 try {
101 return [realpathSync(path)];
102 } catch {
103 return [];
104 }
105 }
106
107 const isLink = (path: string): boolean => {
108 try {
109 return lstatSync(path).isSymbolicLink();
110 } catch {
111 return true;
112 }
113 };
114
115 /** The entries of a directory, or none where it cannot be read. */
116 const listDir = (dir: string): string[] => {
117 try {
118 return readdirSync(dir);
119 } catch {
120 return [];
121 }
122 };
123
124 /**
125 * Every place to read so that nothing under `hide` can be: the siblings of each step on the way
126 * to a hidden path, then `keep`. A hidden directory's parent itself cannot be listed (only what is
127 * beneath its other entries), which is the price of a floor that has no mounts.
128 */
129 export function readRootsAround(hide: readonly string[], keep: readonly string[], list: (dir: string) => string[] = listDir, link: (path: string) => boolean = isLink): string[] {
130 const roots = new Set<string>();
131 descend("/", hide.map((h) => h.replace(/\/+$/, "")), roots, list, link);
132 for (const path of keep) roots.add(path);
133 return [...roots].sort();
134 }
135
136 /** Adds to `roots` each entry of `dir` that holds no hidden path, and descends into the ones that do. */
137 function descend(dir: string, rest: readonly string[], roots: Set<string>, list: (dir: string) => string[], link: (path: string) => boolean): void {
138 // `rest` are the hidden paths at or under `dir`.
139 for (const name of list(dir)) {
140 const path = dir === "/" ? `/${name}` : `${dir}/${name}`;
141 // Another process's /proc/<pid> (environ, cmdline, fd/) is the forge's own tokens and open
142 // files, same user: only what is not a process stays. The helper adds its own pid.
143 if (dir === "/proc" && /^\d+$/.test(name)) continue;
144 const below = rest.filter((h) => h === path || h.startsWith(`${path}/`));
145 // A link is never a root: its target is granted by its own place, and a link granted would
146 // open whatever it names, hidden or not.
147 if (below.length === 0) {
148 if (path === "/proc" && !link(path)) descend(path, [], roots, list, link);
149 else if (!link(path)) roots.add(path);
150 } else if (!below.includes(path)) descend(path, below, roots, list, link);
151 }
66152 }
67153
68154 /** The sentence a run records: the ABI that applied and what it does not cover. */
69155 export function landlockNote(plan: LandlockPlan): string {
70156 const held = ["filesystem read-only outside the workspace"];
157 if (plan.readRoots.length > 0) held.push("the host's and its neighbours' directories not readable");
71158 if (plan.handledNet !== 0) held.push(`tcp connect to port${plan.connect.length === 1 ? "" : "s"} ${plan.connect.join(",")} only`);
72159 if (plan.scoped !== 0) held.push("signals and abstract sockets scoped");
73160 const gaps = [...plan.stripped, "udp (not covered before ABI 10)"];
@@ -84,11 +171,15 @@ export const CHECK_FLOOR_ENV = "FORGE_CHECK_FLOOR";
84171 /** What a floor used alone, with no bubblewrap above it, leaves open: said wherever it is named. */
85172 export const READS_OPEN = "reads are not hidden (the whole filesystem stays readable) and tcp is not confined";
86173
174 /** What a floor that hides the forge's data leaves open: said wherever it is named. */
175 export const READS_PARTLY = "the forge's data is not readable, the rest of the machine stays readable, and tcp is not confined";
176
177 const absolute = (p: string): boolean => p.startsWith("/") && !p.includes("\0");
178 const realPort = (n: number): boolean => Number.isInteger(n) && n > 0 && n < 65536;
179
87180 /** Whether `want` is a safe request: absolute paths without NUL, real ports. */
88181 export function validWant(want: LandlockWant): boolean {
89 const path = (p: string): boolean => p.startsWith("/") && !p.includes("\0");
90 const port = (n: number): boolean => Number.isInteger(n) && n > 0 && n < 65536;
91 return want.writable.every(path) && (want.connect ?? []).every(port);
182 return want.writable.every(absolute) && (want.connect ?? []).every(realPort) && (want.hide ?? []).every(absolute) && (want.keep ?? []).every(absolute);
92183 }
93184
94185 /** The helper's own path, next to this module. */
@@ -99,6 +190,6 @@ export const HELPER = new URL("./landlock_helper.ts", import.meta.url).pathname;
99190 * is not safe throws, so a request is never turned into a weaker one.
100191 */
101192 export function landlockArgv(plan: LandlockPlan, argv: readonly string[], bun: string = process.execPath): string[] {
102 if (!validWant({ writable: plan.writable, connect: plan.connect })) throw new Error("landlock: unsafe plan");
193 if (![...plan.writable, ...plan.readRoots].every(absolute) || !plan.connect.every(realPort)) throw new Error("landlock: unsafe plan");
103194 return [bun, HELPER, JSON.stringify(plan), "--", ...argv];
104195 }
src/sandbox/landlock_helper.ts +6 −3
@@ -43,7 +43,7 @@ if (process.argv[2] === "--abi") {
4343 const split = process.argv.indexOf("--");
4444 if (split < 3 || split === process.argv.length - 1) die("usage: <plan> -- <command…>");
4545 const plan = JSON.parse(process.argv[2]!) as {
46 abi: number; handledFs: number; handledNet: number; scoped: number; writable: string[]; connect: number[];
46 abi: number; handledFs: number; handledNet: number; scoped: number; writable: string[]; connect: number[]; readRoots?: string[];
4747 };
4848 const command = process.argv.slice(split + 1);
4949
@@ -60,7 +60,7 @@ function allow(path: string, access: number): void {
6060 const fd = libc.open(ptr(cstr(path)), O_PATH_CLOEXEC);
6161 if (fd < 0) {
6262 // 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}`);
63 if (path === "/") die(`cannot open ${path}`);
6464 return;
6565 }
6666 // A file takes only the rights that mean something for one (the kernel refuses the rest).
@@ -75,7 +75,10 @@ function allow(path: string, access: number): void {
7575 // execute, write_file, read_file, truncate, ioctl_dev
7676 const FILE_RIGHTS = (1 << 0) | (1 << 1) | (1 << 2) | (1 << 14) | (1 << 15);
7777 const READ = (1 << 0) | (1 << 2) | (1 << 3);
78 allow("/", plan.handledFs & READ);
78 // Hidden paths leave no single root: each place that stays readable is its own rule.
79 for (const root of plan.readRoots?.length ? plan.readRoots : ["/"]) allow(root, plan.handledFs & READ);
80 // Where reads are narrowed, /proc is too: this process's own entry is read, no other's.
81 if (plan.readRoots?.length) allow(`/proc/${process.pid}`, plan.handledFs & READ);
7982 for (const path of plan.writable) allow(path, plan.handledFs);
8083 // struct landlock_net_port_attr: u64 allowed_access, u64 port.
8184 for (const port of plan.connect) {
test/check-floor.test.ts added +28
@@ -0,0 +1,28 @@
1 import { expect, test } from "bun:test";
2 import { checkFloor } from "../src/checks/floor.ts";
3 import { checkInstallCache } from "../src/checks/install.ts";
4 import { landlockPlan } from "../src/sandbox/landlock.ts";
5 import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
6 import { tmpdir } from "node:os";
7 import { join } from "node:path";
8
9 test("the floor a check with no cell is held by hides the forge's data and keeps its own places (#16856)", () => {
10 const floor = checkFloor(6, "/d/checks/x", "/d", "r.1");
11 expect(floor.hide).toEqual(["/d"]);
12 expect(floor.keep).toEqual(["/d/checks/x", "/d/checks/x.home", "/d/checks/x.tmp", checkInstallCache("/d", "r.1")]);
13 expect(floor.writable).toEqual(["/d/checks/x", "/d/checks/x.home", "/d/checks/x.tmp", "/dev/null"]);
14 });
15
16 test("that floor, handed to the plan runStep makes, narrows reads and keeps the check's directory", () => {
17 const data = mkdtempSync(join(tmpdir(), "floor-data-"));
18 try {
19 const dir = join(data, "checks", "x");
20 mkdirSync(dir, { recursive: true });
21 const plan = landlockPlan(6, checkFloor(6, dir, data, "r.1"));
22 expect(plan.readRoots).toContain(dir);
23 expect(plan.readRoots).not.toContain(data);
24 expect(plan.readRoots.some((r) => r.startsWith("/proc/") && /^\/proc\/\d+$/.test(r))).toBe(false);
25 } finally {
26 rmSync(data, { recursive: true });
27 }
28 });
test/landlock-real.test.ts +3 −3
@@ -47,16 +47,16 @@ describe("stacked under a real cell", () => {
4747 describe("a check with no cell is held by the floor", () => {
4848 const f = checksForge("forge-floor-");
4949 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 () => {
50 test.skipIf(!kernel.ok)("it writes its checkout and temp, is refused elsewhere, and the log says what reads stay open", async () => {
5151 const was = { cells: process.env["FORGE_CELLS"], landlock: process.env["FORGE_LANDLOCK"] };
5252 process.env["FORGE_CELLS"] = "off";
5353 delete process.env["FORGE_LANDLOCK"];
5454 try {
5555 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`;
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; if sh -c 'cat ${f.dataDir}/forge.db' >/dev/null 2>&1; then exit 5; fi; if sh -c 'cat /proc/${process.pid}/environ' >/dev/null 2>&1; then exit 6; fi`;
5757 const made = await f.slowCheck(command, "floor check");
5858 const run = await f.settled((r) => r.id === made);
59 expect(readRunLog(f.dataDir, run.id).lines.join("\n")).toContain("reads are not hidden");
59 expect(readRunLog(f.dataDir, run.id).lines.join("\n")).toContain("the forge's data is not readable");
6060 expect(run.state).toBe("ok");
6161 expect(existsSync(join(outside, "f"))).toBe(false);
6262 } finally {
test/landlock.test.ts +76 −2
@@ -1,8 +1,8 @@
11 import { describe, expect, test } from "bun:test";
2 import { mkdtempSync, readFileSync, rmSync } from "node:fs";
2 import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
33 import { tmpdir } from "node:os";
44 import { join } from "node:path";
5 import { NET_CONNECT_TCP, SCOPE_SIGNAL, landlockArgv, landlockNote, landlockPlan, validWant } from "../src/sandbox/landlock.ts";
5 import { NET_CONNECT_TCP, SCOPE_SIGNAL, landlockArgv, landlockNote, landlockPlan, readRootsAround, validWant } from "../src/sandbox/landlock.ts";
66 import { parseAbi, probeLandlock } from "../src/sandbox/landlock_probe.ts";
77
88 describe("landlockPlan", () => {
@@ -31,6 +31,47 @@ describe("landlockPlan", () => {
3131 });
3232 });
3333
34 describe("reads around a hidden path", () => {
35 const tree: Record<string, string[]> = { "/": ["usr", "data", "etc"], "/data": ["forge.db", "children"], "/data/children": ["a", "b"] };
36 const list = (dir: string): string[] => tree[dir] ?? [];
37 test("every sibling on the way to it is a root, it and its keep are not, unless kept", () => {
38 expect(readRootsAround(["/data"], [], list, () => false)).toEqual(["/etc", "/usr"]);
39 expect(readRootsAround(["/data"], ["/data/children/a"], list, () => false)).toEqual(["/data/children/a", "/etc", "/usr"]);
40 expect(readRootsAround(["/data/children"], ["/data/children/a"], list, () => false)).toEqual(["/data/children/a", "/data/forge.db", "/etc", "/usr"]);
41 });
42 test("a link is never a root: it would open whatever it names", () => {
43 expect(readRootsAround(["/data"], [], list, (path) => path === "/etc")).toEqual(["/usr"]);
44 });
45 test("a plan without a hidden path reads the whole filesystem, and says so in the note only when it hides", () => {
46 expect(landlockPlan(6, { writable: [] }).readRoots).toEqual([]);
47 expect(landlockNote(landlockPlan(6, { writable: [], hide: [tmpdir()] }))).toContain("neighbours' directories not readable");
48 expect(validWant({ writable: [], hide: ["rel"] })).toBe(false);
49 });
50 });
51
52 describe("/proc and hidden paths that cannot be resolved", () => {
53 test("no other process's /proc entry is a read root; what is not a process stays", () => {
54 const tree: Record<string, string[]> = { "/": ["usr", "proc", "data"], "/proc": ["1", "4242", "sys", "cpuinfo", "self"] };
55 const roots = readRootsAround(["/data"], [], (dir) => tree[dir] ?? [], (path) => path === "/proc/self");
56 expect(roots).toEqual(["/proc/cpuinfo", "/proc/sys", "/usr"]);
57 });
58 test("a hidden path that is not there fails the plan instead of leaving it readable", () => {
59 expect(() => landlockPlan(6, { writable: [], hide: ["/nonexistent-forge-data"] })).toThrow("cannot resolve hidden path");
60 });
61 test("a hidden path reached through a link is planned by its real name", () => {
62 const base = mkdtempSync(join(tmpdir(), "ll-link-"));
63 try {
64 mkdirSync(join(base, "real", "kept"), { recursive: true });
65 symlinkSync(join(base, "real"), join(base, "alias"));
66 const plan = landlockPlan(6, { writable: [], hide: [join(base, "alias")], keep: [join(base, "alias", "kept")] });
67 expect(plan.readRoots).toContain(join(realpathSync(base), "real", "kept"));
68 expect(plan.readRoots.some((r) => r.endsWith("/alias"))).toBe(false);
69 } finally {
70 rmSync(base, { recursive: true });
71 }
72 });
73 });
74
3475 describe("landlockArgv", () => {
3576 test("puts the plan and the command behind the helper", () => {
3677 const argv = landlockArgv(landlockPlan(6, { writable: ["/w"] }), ["sh", "-c", "true"], "bun");
@@ -59,6 +100,22 @@ test("parseAbi takes a positive integer only", () => {
59100 // The kernel is the judge: skipped (and so named) where this host has no Landlock.
60101 const probe = process.platform === "linux" ? await probeLandlock({}) : { ok: false as const, reason: "not linux" };
61102 describe.skipIf(!probe.ok)("on this kernel", () => {
103 test("a hidden data directory reached through a link stays hidden, and no other process's environ is readable", () => {
104 if (!probe.ok) return;
105 const base = mkdtempSync(join(tmpdir(), "ll-alias-"));
106 try {
107 mkdirSync(join(base, "real"));
108 writeFileSync(join(base, "real", "forge.db"), "db\n");
109 symlinkSync(join(base, "real"), join(base, "data"));
110 const plan = landlockPlan(probe.abi, { writable: ["/dev/null"], hide: [join(base, "data")] });
111 const read = (path: string): string => `cat ${path} >/dev/null 2>&1 && echo open || echo refused`;
112 const script = [read(join(base, "data", "forge.db")), read(join(base, "real", "forge.db")), read(`/proc/${process.pid}/environ`), read("/proc/$$/environ"), read("/proc/sys/kernel/ostype")].join("; ");
113 const run = Bun.spawnSync(landlockArgv(plan, ["/bin/sh", "-c", script]), { stdout: "pipe", stderr: "pipe" });
114 expect(run.stdout.toString().split("\n")).toEqual(["refused", "refused", "refused", "open", "open", ""]);
115 } finally {
116 rmSync(base, { recursive: true });
117 }
118 });
62119 test("the helper writes where allowed, is refused elsewhere, and the command still runs", () => {
63120 if (!probe.ok) return;
64121 const ok = mkdtempSync(join(tmpdir(), "ll-ok-"));
@@ -76,6 +133,23 @@ describe.skipIf(!probe.ok)("on this kernel", () => {
76133 rmSync(no, { recursive: true });
77134 }
78135 });
136 test("a forge's floor reads its own directory and not its neighbour's, nor the parent's files", () => {
137 if (!probe.ok) return;
138 const parent = mkdtempSync(join(tmpdir(), "ll-parent-"));
139 try {
140 const [mine, theirs] = [join(parent, "children", "alpha"), join(parent, "children", "beta")];
141 for (const dir of [mine, theirs]) mkdirSync(dir, { recursive: true });
142 writeFileSync(join(mine, "f"), "alpha\n");
143 writeFileSync(join(theirs, "f"), "beta\n");
144 writeFileSync(join(parent, "secret.key"), "key\n");
145 const plan = landlockPlan(probe.abi, { writable: [mine], hide: [parent], keep: [mine] });
146 const read = (path: string): string => `cat ${path} 2>&1 | sed "s/^cat: .*Permission denied/refused/"`;
147 const run = Bun.spawnSync(landlockArgv(plan, ["/bin/sh", "-c", [read(join(mine, "f")), read(join(theirs, "f")), read(join(parent, "secret.key"))].join("; ")]), { stdout: "pipe", stderr: "pipe" });
148 expect(run.stdout.toString().split("\n")).toEqual(["alpha", "refused", "refused", ""]);
149 } finally {
150 rmSync(parent, { recursive: true });
151 }
152 });
79153 test("a plan the kernel refuses exits 126 and never runs the command", () => {
80154 const plan = { ...landlockPlan(1, { writable: [] }), handledFs: 1 << 30 };
81155 const run = Bun.spawnSync(landlockArgv(plan, ["/bin/echo", "ran"]), { stdout: "pipe", stderr: "pipe" });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs