From bc81b0cee855640a12120c0bc3f492721cc8cb1c Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 3 Nov 2026 00:56:26 +0000 Subject: [PATCH 1/5] test: characterize every containment resolver and predicate before sharing them (#2506) Each package gets a table-driven test of its current rows of the resolver and containment-predicate matrices, against a fixture tree with escapes via .., a sibling prefix, symlinked parents of new files, dangling links, a symlink cycle, an out-and-back link pair, scratch links, a symlinked root, a missing root and a directory swapped for an escaping link between calls. The module-private predicates are exported so the tests can reach them. Refs #2506 Co-Authored-By: Claude Opus 5.5 --- packages/core/tests/containment-rows.test.ts | 119 +++++++++++++ .../ui-sdk/src/server/bridge-tools/mask.ts | 2 +- .../src/server/maintenance-env-masks.ts | 2 +- .../src/server/native-reference-pool.ts | 2 +- .../ui-sdk/src/server/worker-file-observer.ts | 2 +- packages/ui-sdk/src/server/worker-launcher.ts | 2 +- packages/ui-sdk/src/server/worker-rtk.ts | 2 +- .../ui-sdk/src/server/worker-turn-temp.ts | 2 +- .../ui-sdk/tests/containment-rows.test.ts | 165 +++++++++++++++++ packages/ui-server/src/brain/host-boundary.ts | 2 +- .../ui-server/src/brain/operational-state.ts | 2 +- packages/ui-server/src/brain/sync-mirror.ts | 2 +- packages/ui-server/src/core-queries.ts | 2 +- packages/ui-server/src/storage/process.ts | 2 +- .../ui-server/tests/containment-rows.test.ts | 167 ++++++++++++++++++ 15 files changed, 463 insertions(+), 12 deletions(-) create mode 100644 packages/core/tests/containment-rows.test.ts create mode 100644 packages/ui-sdk/tests/containment-rows.test.ts create mode 100644 packages/ui-server/tests/containment-rows.test.ts diff --git a/packages/core/tests/containment-rows.test.ts b/packages/core/tests/containment-rows.test.ts new file mode 100644 index 0000000000..0c56cd9600 --- /dev/null +++ b/packages/core/tests/containment-rows.test.ts @@ -0,0 +1,119 @@ +/** + * core's row of the resolver matrix (#2506): `safeResolve(root, rel)` is + * synchronous, returns the canonical path or `null`, accepts an absolute path + * that lies inside the root, accepts `..` while the result stays inside, + * follows a dangling link whose target stays inside, and refuses everything + * when the root's realpath fails. Written against the copy core carried + * before the shared `@schlessera/brain-common/internal/safe-path`, and kept + * unchanged across the move. + */ +import { afterAll, describe, expect, test } from "bun:test"; +import { mkdirSync, mkdtempSync, realpathSync, renameSync, rmSync, symlinkSync, writeFileSync } from "fs"; +import { tmpdir } from "os"; +import { join, relative } from "path"; + +import { SCRATCH_DIR } from "../src/lib/scratch"; +import { safeResolve } from "../src/lib/safe-path"; + +const base = realpathSync(mkdtempSync(join(tmpdir(), "brain-kit-containment-rows-"))); +afterAll(() => rmSync(base, { recursive: true, force: true })); +const root = join(base, "brain"); +const outside = join(base, "brain-other"); + +mkdirSync(join(root, "notes/sub"), { recursive: true }); +mkdirSync(outside); +mkdirSync(join(root, ".brain/scratch"), { recursive: true }); +writeFileSync(join(root, "notes/a.md"), "a"); +writeFileSync(join(root, "file.md"), "f"); +writeFileSync(join(outside, "secret.md"), "s"); +writeFileSync(join(root, ".brain/scratch/s.txt"), "s"); +symlinkSync("notes", join(root, "link-in")); +symlinkSync(outside, join(root, "link-out")); +symlinkSync("notes/missing", join(root, "dangling-in")); +symlinkSync(join(outside, "missing"), join(root, "dangling-out")); +symlinkSync("cycle-b", join(root, "cycle-a")); +symlinkSync("cycle-a", join(root, "cycle-b")); +symlinkSync(outside, join(root, "bounce")); +symlinkSync(join(root, "notes"), join(outside, "back")); +symlinkSync("../../notes", join(root, ".brain/scratch/link")); +symlinkSync(root, join(base, "root-link")); + +/** The answer relative to the fixture base, or `refused`. */ +const answer = (path: string | null) => (path === null ? "refused" : relative(base, path) || "."); + +describe("core safeResolve(root, rel): its resolver row", () => { + const rows: [string, string][] = [ + ["notes/a.md", "brain/notes/a.md"], + ["notes/new.md", "brain/notes/new.md"], + ["a/b/c.md", "brain/a/b/c.md"], + ["", "brain"], + [".", "brain"], + ["./notes/a.md", "brain/notes/a.md"], + ["notes//a.md", "brain/notes/a.md"], + ["notes/a.md/", "brain/notes/a.md"], + ["file.md/x", "brain/file.md/x"], + // `..` is accepted while the result stays inside. + ["notes/../notes/a.md", "brain/notes/a.md"], + ["notes/../../x", "refused"], + // Sibling prefix: `brain-other` starts with `brain`. + ["../brain-other/secret.md", "refused"], + // Absolute: accepted only inside the root. + [join(root, "notes/a.md"), "brain/notes/a.md"], + ["/etc/passwd", "refused"], + // Windows syntax is not checked. + ["a:b", "brain/a:b"], + ["a\\b", "brain/a\\b"], + ["a\0b", "refused"], + // Links: canonical answers, escapes refused, including for a file that + // does not exist yet under a symlinked parent. + ["link-in/a.md", "brain/notes/a.md"], + ["link-in/new.md", "brain/notes/new.md"], + ["link-out/secret.md", "refused"], + ["link-out/new.md", "refused"], + // A dangling link is followed to its target, which must stay inside. + ["dangling-in", "brain/notes/missing"], + ["dangling-in/x", "brain/notes/missing/x"], + ["dangling-out", "refused"], + ["cycle-a", "refused"], + ["cycle-a/x", "refused"], + // Only the final path must be inside: out through one link and back + // through another is accepted. + ["bounce/back/a.md", "brain/notes/a.md"], + // Scratch is not special to the resolver. + [".brain", "brain/.brain"], + [".brain/scratch/s.txt", "brain/.brain/scratch/s.txt"], + [".brain/scratch/link", "brain/notes"], + [".brain/scratch/link/a.md", "brain/notes/a.md"], + ]; + for (const [rel, expected] of rows) { + test(`${JSON.stringify(rel.startsWith(base) ? "/" + relative(base, rel) : rel)} -> ${expected}`, () => { + expect(answer(safeResolve(root, rel))).toBe(expected); + }); + } + + test("a root that is itself a symlink resolves against its target", () => { + expect(answer(safeResolve(join(base, "root-link"), "notes/a.md"))).toBe("brain/notes/a.md"); + }); + + test("a root whose realpath fails refuses everything", () => { + expect(safeResolve(join(base, "nope"), "notes/a.md")).toBeNull(); + expect(safeResolve(join(root, "dangling-in"), "x")).toBeNull(); + expect(safeResolve(join(root, "file.md/x"), "x")).toBeNull(); + }); + + test("each call reads the filesystem again: a directory swapped for an escaping link is refused", () => { + const swap = join(root, "swap"); + mkdirSync(swap); + expect(answer(safeResolve(root, "swap/new.md"))).toBe("brain/swap/new.md"); + renameSync(swap, join(base, "swapped-away")); + symlinkSync(outside, swap); + expect(safeResolve(root, "swap/new.md")).toBeNull(); + rmSync(swap); + renameSync(join(base, "swapped-away"), swap); + expect(answer(safeResolve(root, "swap/new.md"))).toBe("brain/swap/new.md"); + }); +}); + +test("core's scratch area is .brain/scratch", () => { + expect(SCRATCH_DIR).toBe(".brain/scratch"); +}); diff --git a/packages/ui-sdk/src/server/bridge-tools/mask.ts b/packages/ui-sdk/src/server/bridge-tools/mask.ts index 7eeaa51f42..3f6633ba21 100644 --- a/packages/ui-sdk/src/server/bridge-tools/mask.ts +++ b/packages/ui-sdk/src/server/bridge-tools/mask.ts @@ -123,7 +123,7 @@ export async function handleRequestImageMask( */ const SCRATCH_DIR = ".brain/scratch"; -const under = (dir: string, path: string) => path === dir || path.startsWith(dir + sep); +export const under = (dir: string, path: string) => path === dir || path.startsWith(dir + sep); function isSymlink(path: string): boolean { try { diff --git a/packages/ui-sdk/src/server/maintenance-env-masks.ts b/packages/ui-sdk/src/server/maintenance-env-masks.ts index 7e5b9e9aab..75f6c9d6bb 100644 --- a/packages/ui-sdk/src/server/maintenance-env-masks.ts +++ b/packages/ui-sdk/src/server/maintenance-env-masks.ts @@ -6,7 +6,7 @@ import { isEnvName } from "./protected-paths.js"; export type EnvMaskMetadata = { kind: "directory" | "file" | "symlink" | "other"; target?: string }; export type EnvMaskQuery = { operation: "list" | "stat"; path: string }; type Reply = string[] | EnvMaskMetadata | undefined; -const within = (dir: string, path: string) => path === dir || path.startsWith(`${dir}/`); +export const within = (dir: string, path: string) => path === dir || path.startsWith(`${dir}/`); /** No contents are read. Queries preserve the worker's names through held input aliases. */ export function* maintenanceEnvMaskQueries(source: string, brain: string, diff --git a/packages/ui-sdk/src/server/native-reference-pool.ts b/packages/ui-sdk/src/server/native-reference-pool.ts index e81c0cfd6b..fc37df1d02 100644 --- a/packages/ui-sdk/src/server/native-reference-pool.ts +++ b/packages/ui-sdk/src/server/native-reference-pool.ts @@ -58,7 +58,7 @@ export interface NativeReferencePoolConfig { export type QualifiedReferencePoolConfig = Required> & { headroomLedgerPath?: string }; const fixedPath = (path: unknown) => typeof path === "string" && isAbsolute(path) && !path.includes("\0") && !path.split("/").includes("..") && path.length > 1; -const inside = (child: string, parent: string) => child === parent || child.startsWith(parent.endsWith("/") ? parent : parent + "/"); +export const inside = (child: string, parent: string) => child === parent || child.startsWith(parent.endsWith("/") ? parent : parent + "/"); const page = (value: unknown): value is number => Number.isSafeInteger(value) && (value as number) > 0 && (value as number) % 4096 === 0; export function validateNativeReferencePoolConfig(pool: NativeReferencePoolConfig, store: { storePath: string; fsid: string; socketPath: string }): QualifiedReferencePoolConfig { diff --git a/packages/ui-sdk/src/server/worker-file-observer.ts b/packages/ui-sdk/src/server/worker-file-observer.ts index 253a645b77..44010cce9d 100644 --- a/packages/ui-sdk/src/server/worker-file-observer.ts +++ b/packages/ui-sdk/src/server/worker-file-observer.ts @@ -6,7 +6,7 @@ import { nativeFileVersionFromFd, type NativeFileVersion } from "./native-file-v export interface ObservedWorkerFile { key: string; version: NativeFileVersion } interface Source { worker: string; host: string; rel: string } -const within = (path: string, root: string) => path === root || path.startsWith(root + "/"); +export const within = (path: string, root: string) => path === root || path.startsWith(root + "/"); const EMPTY: NativeFileVersion = { status: "known", hash: createHash("sha256").update("").digest("hex") }; /** Sources come only from the launcher's resolved mounts, and live only until worker exit. */ diff --git a/packages/ui-sdk/src/server/worker-launcher.ts b/packages/ui-sdk/src/server/worker-launcher.ts index 76b8e3691f..00460fa02c 100644 --- a/packages/ui-sdk/src/server/worker-launcher.ts +++ b/packages/ui-sdk/src/server/worker-launcher.ts @@ -725,7 +725,7 @@ export function workerCommand(input: WorkerLaunch): string[] { } /** Whether `path` is `dir` or lies below it. */ -const within = (dir: string, path: string) => path === dir || path.startsWith(`${dir}/`); +export const within = (dir: string, path: string) => path === dir || path.startsWith(`${dir}/`); /** Resolve aliases even when the final installed entry is not present yet. */ function runtimeCanonicalName(requested: string): string { diff --git a/packages/ui-sdk/src/server/worker-rtk.ts b/packages/ui-sdk/src/server/worker-rtk.ts index ee44c88ad7..c9e3f31f95 100644 --- a/packages/ui-sdk/src/server/worker-rtk.ts +++ b/packages/ui-sdk/src/server/worker-rtk.ts @@ -18,7 +18,7 @@ export function registerWorkerRtk(worker: LaunchedWorker, pid: number, input: Wo void worker.exited.then(() => { view.alive = false; }, () => { view.alive = false; }); } catch { /* An unreadable worker cannot authorize an optional rewrite. */ } } -function within(root: string, path: string): boolean { return path === root || path.startsWith(root + "/"); } +export function within(root: string, path: string): boolean { return path === root || path.startsWith(root + "/"); } /** ELF64 native static executables, including dependency-free static PIE. */ export function isStaticNativeElf(path: string): boolean { const bytes = readFileSync(path); diff --git a/packages/ui-sdk/src/server/worker-turn-temp.ts b/packages/ui-sdk/src/server/worker-turn-temp.ts index 5097b6183d..868a94b0cc 100644 --- a/packages/ui-sdk/src/server/worker-turn-temp.ts +++ b/packages/ui-sdk/src/server/worker-turn-temp.ts @@ -45,7 +45,7 @@ const LINK_MAX_CHARS = 2000; const COPY_CHUNK = 1024 * 1024; /** Whether `path` is `dir` or lies below it. */ -const within = (dir: string, path: string) => path === dir || path.startsWith(dir.endsWith("/") ? dir : `${dir}/`); +export const within = (dir: string, path: string) => path === dir || path.startsWith(dir.endsWith("/") ? dir : `${dir}/`); /** * A server-side path that opens the directory a held descriptor names. diff --git a/packages/ui-sdk/tests/containment-rows.test.ts b/packages/ui-sdk/tests/containment-rows.test.ts new file mode 100644 index 0000000000..c847b959e0 --- /dev/null +++ b/packages/ui-sdk/tests/containment-rows.test.ts @@ -0,0 +1,165 @@ +/** + * The ui-sdk's rows of the containment matrices (#2506). `resolveInRepo(root, + * rel)` is core's resolver except that it refuses an absolute `rel`; the + * predicates each keep their own argument order, equality, root `/` and + * trailing-separator answers. Written against the copies the SDK carried + * before the shared `@schlessera/brain-common/internal/safe-path`, and kept + * unchanged across the move. + */ +import { afterAll, describe, expect, test } from "bun:test"; +import { mkdirSync, mkdtempSync, realpathSync, renameSync, rmSync, symlinkSync, writeFileSync } from "fs"; +import { tmpdir } from "os"; +import { join, relative } from "path"; + +import { maskInScratch, under as maskUnder } from "../src/server/bridge-tools/mask"; +import { resolveInRepo } from "../src/server/bridge-tools/resolve-in-repo"; +import { within as envMasksWithin } from "../src/server/maintenance-env-masks"; +import { inside as poolInside } from "../src/server/native-reference-pool"; +import { within as observerWithin } from "../src/server/worker-file-observer"; +import { within as launcherWithin } from "../src/server/worker-launcher"; +import { within as rtkWithin } from "../src/server/worker-rtk"; +import { within as turnTempWithin } from "../src/server/worker-turn-temp"; + +const base = realpathSync(mkdtempSync(join(tmpdir(), "brain-kit-containment-rows-"))); +afterAll(() => rmSync(base, { recursive: true, force: true })); +const root = join(base, "brain"); +const outside = join(base, "brain-other"); + +mkdirSync(join(root, "notes/sub"), { recursive: true }); +mkdirSync(outside); +mkdirSync(join(root, ".brain/scratch"), { recursive: true }); +writeFileSync(join(root, "notes/a.md"), "a"); +writeFileSync(join(root, "file.md"), "f"); +writeFileSync(join(outside, "secret.md"), "s"); +writeFileSync(join(root, ".brain/scratch/s.txt"), "s"); +symlinkSync("notes", join(root, "link-in")); +symlinkSync(outside, join(root, "link-out")); +symlinkSync("notes/missing", join(root, "dangling-in")); +symlinkSync(join(outside, "missing"), join(root, "dangling-out")); +symlinkSync("cycle-b", join(root, "cycle-a")); +symlinkSync("cycle-a", join(root, "cycle-b")); +symlinkSync(outside, join(root, "bounce")); +symlinkSync(join(root, "notes"), join(outside, "back")); +symlinkSync("../../notes", join(root, ".brain/scratch/link")); +symlinkSync(root, join(base, "root-link")); + +/** The answer relative to the fixture base, or `refused`. */ +const answer = (path: string | null) => (path === null ? "refused" : relative(base, path) || "."); + +describe("ui-sdk resolveInRepo(root, rel): its resolver row", () => { + const rows: [string, string][] = [ + ["notes/a.md", "brain/notes/a.md"], + ["notes/new.md", "brain/notes/new.md"], + ["a/b/c.md", "brain/a/b/c.md"], + ["", "brain"], + [".", "brain"], + ["./notes/a.md", "brain/notes/a.md"], + ["notes//a.md", "brain/notes/a.md"], + ["notes/a.md/", "brain/notes/a.md"], + ["file.md/x", "brain/file.md/x"], + // `..` is accepted while the result stays inside. + ["notes/../notes/a.md", "brain/notes/a.md"], + ["notes/../../x", "refused"], + // Sibling prefix: `brain-other` starts with `brain`. + ["../brain-other/secret.md", "refused"], + // Absolute: refused even inside the root (core accepts it). + [join(root, "notes/a.md"), "refused"], + ["/etc/passwd", "refused"], + // Windows syntax is not checked. + ["a:b", "brain/a:b"], + ["a\\b", "brain/a\\b"], + ["a\0b", "refused"], + ["link-in/a.md", "brain/notes/a.md"], + ["link-in/new.md", "brain/notes/new.md"], + ["link-out/secret.md", "refused"], + ["link-out/new.md", "refused"], + ["dangling-in", "brain/notes/missing"], + ["dangling-in/x", "brain/notes/missing/x"], + ["dangling-out", "refused"], + ["cycle-a", "refused"], + ["cycle-a/x", "refused"], + ["bounce/back/a.md", "brain/notes/a.md"], + [".brain", "brain/.brain"], + [".brain/scratch/s.txt", "brain/.brain/scratch/s.txt"], + [".brain/scratch/link", "brain/notes"], + [".brain/scratch/link/a.md", "brain/notes/a.md"], + ]; + for (const [rel, expected] of rows) { + test(`${JSON.stringify(rel.startsWith(base) ? "/" + relative(base, rel) : rel)} -> ${expected}`, () => { + expect(answer(resolveInRepo(root, rel))).toBe(expected); + }); + } + + test("a root that is itself a symlink resolves against its target", () => { + expect(answer(resolveInRepo(join(base, "root-link"), "notes/a.md"))).toBe("brain/notes/a.md"); + }); + + test("a root whose realpath fails refuses everything", () => { + expect(resolveInRepo(join(base, "nope"), "notes/a.md")).toBeNull(); + expect(resolveInRepo(join(root, "dangling-in"), "x")).toBeNull(); + expect(resolveInRepo(join(root, "file.md/x"), "x")).toBeNull(); + }); + + test("each call reads the filesystem again: a directory swapped for an escaping link is refused", () => { + const swap = join(root, "swap"); + mkdirSync(swap); + expect(answer(resolveInRepo(root, "swap/new.md"))).toBe("brain/swap/new.md"); + renameSync(swap, join(base, "swapped-away")); + symlinkSync(outside, swap); + expect(resolveInRepo(root, "swap/new.md")).toBeNull(); + rmSync(swap); + renameSync(join(base, "swapped-away"), swap); + expect(answer(resolveInRepo(root, "swap/new.md"))).toBe("brain/swap/new.md"); + }); + + test("the mask's scratch area is .brain/scratch, separator-bounded", () => { + const rootReal = realpathSync(root); + expect(maskInScratch(rootReal, ".brain/scratch/m.png", join(rootReal, "notes/m.png"))).toBe(true); + expect(maskInScratch(rootReal, "notes/m.png", join(rootReal, ".brain/scratch/m.png"))).toBe(true); + expect(maskInScratch(rootReal, ".brain/scratchy/m.png", join(rootReal, ".brain/scratchy/m.png"))).toBe(false); + expect(maskInScratch(rootReal, ".brain/m.png", join(rootReal, ".brain/m.png"))).toBe(false); + }); +}); + +/** + * Each predicate as `(root, path) -> answer`, whatever its own argument order. + * Columns: equality, child, sibling prefix, parent, root `/` (absolute, + * itself, relative), trailing separator on the root, a trailing separator or + * unnormalised segment on the path. + */ +const PREDICATE_CASES: [string, string][] = [ + ["/a/b", "/a/b"], ["/a/b", "/a/b/c"], ["/a/b", "/a/bc"], ["/a/b", "/a"], + ["/", "/x"], ["/", "/"], ["/", "x"], + ["/a/b/", "/a/b/c"], ["/a/b/", "/a/b"], + ["/a/b", "/a/b/"], ["/a/b", "/a/b/../c"], ["/a/b", "/a/b/..c"], ["/a/b", "/a/b//c"], +]; +// = c sp pa /x / rel tr trE p/ .. ..c // +const LITERAL_SLASH = "T T - - - T - - - T T T T"; +const TRAILING_TOLERATED = "T T - - T T - T - T T T T"; + +const rows: [string, (root: string, path: string) => boolean, string][] = [ + ["worker-launcher within(dir, path)", launcherWithin, LITERAL_SLASH], + ["worker-rtk within(root, path)", rtkWithin, LITERAL_SLASH], + ["worker-file-observer within(path, root)", (root, path) => observerWithin(path, root), LITERAL_SLASH], + ["maintenance-env-masks within(dir, path)", envMasksWithin, LITERAL_SLASH], + ["worker-turn-temp within(dir, path)", turnTempWithin, TRAILING_TOLERATED], + ["bridge-tools/mask under(dir, path)", maskUnder, LITERAL_SLASH], + ["native-reference-pool inside(child, parent)", (root, path) => poolInside(path, root), TRAILING_TOLERATED], +]; + +describe("ui-sdk containment predicates: their matrix rows", () => { + for (const [name, predicate, expected] of rows) { + test(name, () => { + expect(PREDICATE_CASES.map(([root, path]) => (predicate(root, path) ? "T" : "-")).join(" ")).toBe(expected); + }); + } + + test("argument order matters: each predicate is asymmetric in the order it declares", () => { + expect(launcherWithin("/a", "/a/b")).toBe(true); + expect(launcherWithin("/a/b", "/a")).toBe(false); + expect(observerWithin("/a/b", "/a")).toBe(true); + expect(observerWithin("/a", "/a/b")).toBe(false); + expect(poolInside("/a/b", "/a")).toBe(true); + expect(poolInside("/a", "/a/b")).toBe(false); + }); +}); diff --git a/packages/ui-server/src/brain/host-boundary.ts b/packages/ui-server/src/brain/host-boundary.ts index 50c6ea79f4..74788e6784 100644 --- a/packages/ui-server/src/brain/host-boundary.ts +++ b/packages/ui-server/src/brain/host-boundary.ts @@ -172,7 +172,7 @@ const TURN_EGRESS_INACTIVE = "This host has no managed native storage, so govern /** Whether the brain CLI's paid providers are relayed (#1673): where provider keys live on this host. */ const PROVIDERS_RELAYED = "The brain CLI's Gemini, Anthropic and OpenAI image providers go through a metered host relay, in turn and maintenance workers alike: the host holds their keys, records each request's usage and counts it toward the budgets."; const PROVIDERS_NOT_RELAYED = "The brain CLI's providers are not relayed here: governed and strict turn workers report them unavailable, and maintenance workers still receive the provider keys, so their spend is unmetered."; -const within = (dir: string, path: string) => path === dir || path.startsWith(`${dir}/`); +export const within = (dir: string, path: string) => path === dir || path.startsWith(`${dir}/`); const real = (path: string) => { try { return realpathSync(path); } catch { return resolve(path); } }; /** Whether `governed` can run for this server and brain, and if not, why. */ diff --git a/packages/ui-server/src/brain/operational-state.ts b/packages/ui-server/src/brain/operational-state.ts index 67a2daca6e..0c008b4c56 100644 --- a/packages/ui-server/src/brain/operational-state.ts +++ b/packages/ui-server/src/brain/operational-state.ts @@ -29,7 +29,7 @@ function canonical(path: string, links = 0): string { } return current; } -const within = (root: string, path: string) => root === "/" || path === root || path.startsWith(`${root}/`); +export const within = (root: string, path: string) => root === "/" || path === root || path.startsWith(`${root}/`); /** An outside name does not move an inode out of the brain if another name or a bind mount remains there. */ function hasBrainAlias(brain: string, path: string, descendants = false): boolean { diff --git a/packages/ui-server/src/brain/sync-mirror.ts b/packages/ui-server/src/brain/sync-mirror.ts index 9b0eb74464..96fe70df66 100644 --- a/packages/ui-server/src/brain/sync-mirror.ts +++ b/packages/ui-server/src/brain/sync-mirror.ts @@ -26,7 +26,7 @@ const MIRROR_CONFIG = `[core] \tfsckObjects = true `; const CREDENTIAL_HELPER = '!f() { printf "username=x-access-token\\npassword=%s\\n" "$BRAIN_SYNC_TOKEN"; }; f'; -const within = (root: string, path: string) => path === root || path.startsWith(`${root}/`); +export const within = (root: string, path: string) => path === root || path.startsWith(`${root}/`); const mirrorLocks = createKeyedLock(); /** One host-private mirror per brain/database; standalone clients get private temporary state. */ diff --git a/packages/ui-server/src/core-queries.ts b/packages/ui-server/src/core-queries.ts index 50e098a3bf..16005fce91 100644 --- a/packages/ui-server/src/core-queries.ts +++ b/packages/ui-server/src/core-queries.ts @@ -136,7 +136,7 @@ type Resolved = | { ok: true; entry: Record } | { ok: false; reason: CoreQueriesUnavailableReason; version?: string }; -function inside(dir: string, file: string): boolean { +export function inside(dir: string, file: string): boolean { const rel = relative(dir, file); return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel); } diff --git a/packages/ui-server/src/storage/process.ts b/packages/ui-server/src/storage/process.ts index 9f66cde46e..53c5dd6a90 100644 --- a/packages/ui-server/src/storage/process.ts +++ b/packages/ui-server/src/storage/process.ts @@ -3,7 +3,7 @@ import { fileURLToPath } from "node:url"; import { dirname, relative, isAbsolute } from "node:path"; import { realpathSync, readFileSync } from "node:fs"; import type { MetadataRoot, MetadataResult } from "./metadata.js"; -const inside = (root: string, path: string) => { const rel = relative(root, path); return !rel || (!isAbsolute(rel) && rel !== ".." && !rel.startsWith("../")); }; +export const inside = (root: string, path: string) => { const rel = relative(root, path); return !rel || (!isAbsolute(rel) && rel !== ".." && !rel.startsWith("../")); }; /** Verify the installed public reader, never code or executables from content. */ export function coreReader(brainPath: string, subpath: "storage" | "queries"): string { const manifestPath = realpathSync(fileURLToPath(import.meta.resolve("@schlessera/brain/package.json"))); diff --git a/packages/ui-server/tests/containment-rows.test.ts b/packages/ui-server/tests/containment-rows.test.ts new file mode 100644 index 0000000000..d53fa9703d --- /dev/null +++ b/packages/ui-server/tests/containment-rows.test.ts @@ -0,0 +1,167 @@ +/** + * ui-server's rows of the containment matrices (#2506). `safeResolve(rel, + * root)` is asynchronous and throws `PathEscapeError`; it refuses absolute + * paths, `..` anywhere, `:` or `\\` in a segment and dangling links; every + * existing component must stay inside, not only the final path; a missing + * root falls back to the lexical root; it answers the lexical path, not the + * canonical one; and under `.brain` a scratch request follows no link. The + * predicates each keep their own argument order, equality, root `/` and + * normalisation answers. Written against the copies ui-server carried before + * the shared `@schlessera/brain-common/internal/safe-path`. + */ +import { afterAll, describe, expect, test } from "bun:test"; +import { mkdirSync, mkdtempSync, realpathSync, renameSync, rmSync, symlinkSync, writeFileSync } from "fs"; +import { tmpdir } from "os"; +import { join, relative } from "path"; + +import { inside as coreQueriesInside } from "../src/core-queries"; +import { within as hostBoundaryWithin } from "../src/brain/host-boundary"; +import { within as operationalStateWithin } from "../src/brain/operational-state"; +import { within as syncMirrorWithin } from "../src/brain/sync-mirror"; +import { isScratchPath, safeResolve } from "../src/files/walker"; +import { inside as processInside } from "../src/storage/process"; + +const base = realpathSync(mkdtempSync(join(tmpdir(), "brain-kit-containment-rows-"))); +afterAll(() => rmSync(base, { recursive: true, force: true })); +const root = join(base, "brain"); +const outside = join(base, "brain-other"); + +mkdirSync(join(root, "notes/sub"), { recursive: true }); +mkdirSync(outside); +mkdirSync(join(root, ".brain/scratch"), { recursive: true }); +writeFileSync(join(root, "notes/a.md"), "a"); +writeFileSync(join(root, "file.md"), "f"); +writeFileSync(join(outside, "secret.md"), "s"); +writeFileSync(join(root, ".brain/scratch/s.txt"), "s"); +symlinkSync("notes", join(root, "link-in")); +symlinkSync(outside, join(root, "link-out")); +symlinkSync("notes/missing", join(root, "dangling-in")); +symlinkSync(join(outside, "missing"), join(root, "dangling-out")); +symlinkSync("cycle-b", join(root, "cycle-a")); +symlinkSync("cycle-a", join(root, "cycle-b")); +symlinkSync(outside, join(root, "bounce")); +symlinkSync(join(root, "notes"), join(outside, "back")); +symlinkSync("../../notes", join(root, ".brain/scratch/link")); +symlinkSync(root, join(base, "root-link")); + +/** The answer relative to the fixture base, `refused` for a path escape, or the error's code. */ +async function answer(rel: string, at = root): Promise { + try { + return relative(base, await safeResolve(rel, at)) || "."; + } catch (error) { + if ((error as Error).name === "PathEscapeError") return "refused"; + return `error ${(error as NodeJS.ErrnoException).code}`; + } +} + +describe("ui-server safeResolve(rel, root): its resolver row", () => { + const rows: [string, string][] = [ + ["notes/a.md", "brain/notes/a.md"], + ["notes/new.md", "brain/notes/new.md"], + ["a/b/c.md", "brain/a/b/c.md"], + ["", "brain"], + [".", "brain"], + ["./notes/a.md", "brain/notes/a.md"], + ["notes//a.md", "brain/notes/a.md"], + ["notes/a.md/", "brain/notes/a.md"], + ["file.md/x", "brain/file.md/x"], + // `..` is refused anywhere, even when the result stays inside. + ["notes/../notes/a.md", "refused"], + ["notes/../../x", "refused"], + ["../brain-other/secret.md", "refused"], + // Absolute is refused, even inside the root. + [join(root, "notes/a.md"), "refused"], + ["/etc/passwd", "refused"], + ["\\etc", "refused"], + // Windows syntax and NUL are refused. + ["a:b", "refused"], + ["a\\b", "refused"], + ["a\0b", "refused"], + // The answer is the lexical path; links stay as written. + ["link-in/a.md", "brain/link-in/a.md"], + ["link-in/new.md", "brain/link-in/new.md"], + ["link-out/secret.md", "refused"], + ["link-out/new.md", "refused"], + // A dangling link is refused even when its target would be inside. + ["dangling-in", "refused"], + ["dangling-in/x", "refused"], + ["dangling-out", "refused"], + // A symlink cycle is accepted: the path resolves nowhere. + ["cycle-a", "brain/cycle-a"], + ["cycle-a/x", "brain/cycle-a/x"], + // Every existing component must stay inside: out and back is refused. + ["bounce/back/a.md", "refused"], + // `.brain` is a scratch request (`isScratchPath`): no link under it is followed. + [".brain", "brain/.brain"], + [".brain/scratch/s.txt", "brain/.brain/scratch/s.txt"], + [".brain/scratch/link", "refused"], + [".brain/scratch/link/a.md", "refused"], + ]; + for (const [rel, expected] of rows) { + test(`${JSON.stringify(rel.startsWith(base) ? "/" + relative(base, rel) : rel)} -> ${expected}`, async () => { + expect(await answer(rel)).toBe(expected); + }); + } + + test("a root that is itself a symlink resolves against its target", async () => { + expect(await answer("notes/a.md", join(base, "root-link"))).toBe("brain/notes/a.md"); + }); + + test("a missing root falls back to the lexical root; a dangling or unreadable one does not", async () => { + expect(await answer("notes/a.md", join(base, "nope"))).toBe("nope/notes/a.md"); + expect(await answer("x", join(root, "dangling-in"))).toBe("refused"); + expect(await answer("x", join(root, "file.md/x"))).toBe("error ENOTDIR"); + }); + + test("each call reads the filesystem again: a directory swapped for an escaping link is refused", async () => { + const swap = join(root, "swap"); + mkdirSync(swap); + expect(await answer("swap/new.md")).toBe("brain/swap/new.md"); + renameSync(swap, join(base, "swapped-away")); + symlinkSync(outside, swap); + expect(await answer("swap/new.md")).toBe("refused"); + rmSync(swap); + renameSync(join(base, "swapped-away"), swap); + expect(await answer("swap/new.md")).toBe("brain/swap/new.md"); + }); + + test("isScratchPath covers .brain itself as well as the scratch area", () => { + expect(isScratchPath(".brain")).toBe(true); + expect(isScratchPath(".brain/")).toBe(true); + expect(isScratchPath("./.brain/scratch")).toBe(true); + expect(isScratchPath(".brain/scratch/x/y")).toBe(true); + expect(isScratchPath(".brain/other")).toBe(false); + expect(isScratchPath(".brain/scratchy")).toBe(false); + expect(isScratchPath(".brainy/scratch")).toBe(false); + expect(isScratchPath("notes/.brain/scratch")).toBe(false); + }); +}); + +/** As in the ui-sdk test: `(root, path)` cases and their `T`/`-` answers. */ +const PREDICATE_CASES: [string, string][] = [ + ["/a/b", "/a/b"], ["/a/b", "/a/b/c"], ["/a/b", "/a/bc"], ["/a/b", "/a"], + ["/", "/x"], ["/", "/"], ["/", "x"], + ["/a/b/", "/a/b/c"], ["/a/b/", "/a/b"], + ["/a/b", "/a/b/"], ["/a/b", "/a/b/../c"], ["/a/b", "/a/b/..c"], ["/a/b", "/a/b//c"], +]; +// = c sp pa /x / rel tr trE p/ .. ..c // +const LITERAL_SLASH = "T T - - - T - - - T T T T"; + +const rows: [string, (root: string, path: string) => boolean, string][] = [ + // relative()-based: both sides resolved; the root itself is excluded. + ["core-queries inside(dir, file)", coreQueriesInside, "- T - - T - T T - - - - T"], + // relative()-based: both sides resolved; the root itself is included. + ["storage/process inside(root, path)", processInside, "T T - - T T T T T T - T T"], + // Literal, except that root `/` holds everything. + ["operational-state within(root, path)", operationalStateWithin, "T T - - T T T - - T T T T"], + ["sync-mirror within(root, path)", syncMirrorWithin, LITERAL_SLASH], + ["host-boundary within(dir, path)", hostBoundaryWithin, LITERAL_SLASH], +]; + +describe("ui-server containment predicates: their matrix rows", () => { + for (const [name, predicate, expected] of rows) { + test(name, () => { + expect(PREDICATE_CASES.map(([root, path]) => (predicate(root, path) ? "T" : "-")).join(" ")).toBe(expected); + }); + } +}); From 673304f604df5b876a497b4bcdb9a8cce7a12082 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 3 Nov 2026 02:05:06 +0000 Subject: [PATCH 2/5] refactor(common): hold symlink-safe path containment once (#2506) core, the ui-sdk and ui-server each carried their own symlink-safe resolver and their own containment predicates, and the copies already disagreed. The new @schlessera/brain-common/internal/safe-path entry holds: - isWithin(root, path, rule), the containment primitive. Its answers for equality, the separator, a root that already ends in a separator, and normalisation are explicit parameters. - one canonicalisation algorithm, written as a generator of filesystem queries so the sync and async variants run the same steps. It resolves under the root's realpath and canonicalises the nearest existing ancestor. The caller's policy sets how a missing root, a dangling link and the per-component check are handled, and whether a link is refused at a given component. core's safeResolve, the SDK's resolveInRepo and ui-server's safeResolve are now thin wrappers. Each keeps its own request refusals, error type and policy. The twelve named predicates are calls to isWithin with their row's parameters. The scratch-directory copies read BRAIN_SCRATCH_DIR, and isScratchPath still covers .brain itself. Two answers change, and each has a named test: - ui-server's safeResolve refuses a path through a symlink cycle. Its copy accepted it, while core and the SDK already refused it. - core-queries' inside() no longer refuses a child whose name starts with "..". It is inside the package. Doc citations into the files whose lines moved are updated. Refs #2506 Co-Authored-By: Claude Opus 5.5 --- .changeset/safe-path-once.md | 8 + api-report/common.txt | 9 + docs/decisions/container-fresh-proc.md | 6 +- docs/decisions/design-kit/links.md | 2 +- docs/decisions/governed-writable-workers.md | 40 +-- docs/decisions/index-query-api.md | 2 +- docs/decisions/managed-worktrees.md | 4 +- docs/decisions/policy-write-boundary.md | 6 +- docs/decisions/public-export-boundary.md | 8 +- docs/decisions/reference-pool-accounting.md | 4 +- docs/decisions/worker-writable-areas.md | 12 +- docs/hosting/agent-workers.md | 4 +- docs/plans/module-renderers.md | 2 +- docs/plans/storage-accounting.md | 4 +- docs/plans/storage-lifecycle.md | 6 +- packages/common/README.md | 1 + packages/common/package.json | 5 + packages/common/src/safe-path.ts | 255 ++++++++++++++++++ packages/common/tests/safe-path.test.ts | 170 ++++++++++++ packages/core/src/lib/safe-path.ts | 82 +----- packages/core/src/lib/scratch.ts | 8 +- .../ui-sdk/src/server/bridge-tools/mask.ts | 14 +- .../server/bridge-tools/resolve-in-repo.ts | 68 +---- .../src/server/maintenance-env-masks.ts | 3 +- .../src/server/native-reference-pool.ts | 4 +- .../ui-sdk/src/server/worker-file-observer.ts | 4 +- packages/ui-sdk/src/server/worker-launcher.ts | 3 +- packages/ui-sdk/src/server/worker-rtk.ts | 3 +- .../ui-sdk/src/server/worker-turn-temp.ts | 3 +- packages/ui-server/src/brain/host-boundary.ts | 3 +- .../ui-server/src/brain/operational-state.ts | 8 +- packages/ui-server/src/brain/sync-mirror.ts | 3 +- packages/ui-server/src/core-queries.ts | 7 +- packages/ui-server/src/files/walker.ts | 116 +++----- packages/ui-server/src/storage/process.ts | 6 +- .../ui-server/tests/containment-rows.test.ts | 14 +- tests/allowed-edges.ts | 5 +- 37 files changed, 619 insertions(+), 283 deletions(-) create mode 100644 .changeset/safe-path-once.md create mode 100644 packages/common/src/safe-path.ts create mode 100644 packages/common/tests/safe-path.test.ts diff --git a/.changeset/safe-path-once.md b/.changeset/safe-path-once.md new file mode 100644 index 0000000000..b7ed39f57a --- /dev/null +++ b/.changeset/safe-path-once.md @@ -0,0 +1,8 @@ +--- +"@schlessera/brain-common": patch +"@schlessera/brain": patch +"@schlessera/brain-ui-sdk": patch +"@schlessera/brain-ui-server": patch +--- + +Symlink-safe path containment now has one implementation, in the new internal entry `@schlessera/brain-common/internal/safe-path` (#2506). It holds `isWithin`, the containment primitive whose equality, separator, trailing-separator and normalisation answers are explicit parameters, and one canonicalisation algorithm with a synchronous and an asynchronous variant. core's `safeResolve`, the SDK's `resolveInRepo` and the server's `safeResolve` are thin wrappers over it, and the scratch-directory copies read the shared `BRAIN_SCRATCH_DIR`. Each caller keeps its own answers, with two exceptions: the server's `safeResolve` now refuses a path through a symlink cycle, as core and the SDK already did, instead of answering a path that resolves nowhere; and the server's check that core's query entry lies inside its package no longer refuses a directory whose name starts with `..`. `safeResolve` and `SCRATCH_DIR` stay exported from `@schlessera/brain/module` with their signatures and answers unchanged. The new entry is internal and carries no compatibility promise. diff --git a/api-report/common.txt b/api-report/common.txt index 4668773343..155e0b5d5a 100644 --- a/api-report/common.txt +++ b/api-report/common.txt @@ -86,6 +86,15 @@ export "./internal/provider-unavailable" (./src/provider-unavailable.ts) providerUnavailableNotice withheldKeys +export "./internal/safe-path" (./src/safe-path.ts) + type ContainedPath + type ContainmentPolicy + type ContainmentRefusal + type WithinRule + isWithin + resolveContained + resolveContainedSync + export "./internal/worker-areas" (./src/worker-areas.ts) BRAIN_SCRATCH_DIR BRAIN_WORKSPACES_DIR diff --git a/docs/decisions/container-fresh-proc.md b/docs/decisions/container-fresh-proc.md index c890dde85a..dcc1664f36 100644 --- a/docs/decisions/container-fresh-proc.md +++ b/docs/decisions/container-fresh-proc.md @@ -1,7 +1,7 @@ # A fresh /proc for agent workers in a container The agent worker launcher gives every worker its own user and PID namespaces -and a fresh procfs (`workerCommand`, `packages/ui-sdk/src/server/worker-launcher.ts:509-689`). +and a fresh procfs (`workerCommand`, `packages/ui-sdk/src/server/worker-launcher.ts:510-690`). Under Docker's default masked `/proc` paths the kernel refuses that procfs mount, so every turn on such a host refuses with `bwrap: Can't mount proc on /newroot/proc: Operation not permitted` (#1622, @@ -22,7 +22,7 @@ does not change. /proc because the parent /proc has masked or covered paths; in Docker, run the container with --security-opt systempaths=unconfined", followed by bubblewrap's own line. Every other launch failure keeps the generic list - (`FRESH_PROC_REFUSED`, `packages/ui-sdk/src/server/worker-launcher.ts:1635`). + (`FRESH_PROC_REFUSED`, `packages/ui-sdk/src/server/worker-launcher.ts:1636`). The match is on bubblewrap's literal message, not a guess from the environment: a host that refuses for another reason is not told to change Docker options. @@ -145,7 +145,7 @@ most host-global `/proc` files check only the file mode, not a capability. **Ruling on #1629 (2026-10-11): a root-run server's worker gets its whole `/proc` read-only. Root servers still qualify.** `workerCommand` adds `--remount-ro /proc` after `--proc /proc` when the server's uid or effective -uid is 0 (`rootProcCover`, `packages/ui-sdk/src/server/worker-launcher.ts:334-336`). +uid is 0 (`rootProcCover`, `packages/ui-sdk/src/server/worker-launcher.ts:335-337`). Measured as container root with `systempaths=unconfined` and the seccomp profile above, with bubblewrap `0.9.0` from the image and the host's `0.12.0`, each in the ordinary and the restricted mode: diff --git a/docs/decisions/design-kit/links.md b/docs/decisions/design-kit/links.md index 0bb6ba1d07..910cb6a57d 100644 --- a/docs/decisions/design-kit/links.md +++ b/docs/decisions/design-kit/links.md @@ -108,7 +108,7 @@ found, and what the ruling did not say: (`LINK_BLOCK_SCHEMA`, `packages/ui-sdk/src/tool-contracts/blocks.ts:429-449`) mirrors the props. `classifyLink` (`classifyLink`, `packages/render-template/src/links.ts:252-311`) is pure. The edge table records the new dependency - (`"@schlessera/brain-ui-sdk"`, `tests/allowed-edges.ts:75`), and ui-kit now + (`"@schlessera/brain-ui-sdk"`, `tests/allowed-edges.ts:76`), and ui-kit now builds and publishes ahead of ui-sdk. At that point the kit's own row was unchanged. #558 later moved the pure classifier to the template's `./links` leaf and added the kit-to-template edge; D13's purity gate still holds. diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index a0f3ead01a..1880faa293 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -509,7 +509,7 @@ stage (`createScratchIgnoreQuery`, directory is not ignored. Launch failure, another exit or timeout means the rule could not be verified; the mask remains refused without forwarding worker stderr or claiming that the ignore file needs repair (`assertScratchMaskAsync`, -`packages/ui-sdk/src/server/bridge-tools/mask.ts:224-235`). +`packages/ui-sdk/src/server/bridge-tools/mask.ts:228-239`). **Credentials never reach a process that evaluates repository inputs.** A read-only host does not stop sandboxed code from stealing a credential it was @@ -543,7 +543,7 @@ maintenance worker no longer receives the keys the provider relay carries (`GEMINI_API_KEY`, `ANTHROPIC_API_KEY`, `OPENAI_API_KEY` and keys the operator lists for it), and the brain's `.env*` files are masked as they are for a credential-free worker. Its `brain` CLI reaches those providers through its own -relay (`providerRelayFor`, `packages/ui-server/src/brain/host-boundary.ts:420-427`). +relay (`providerRelayFor`, `packages/ui-server/src/brain/host-boundary.ts:421-428`). What remains is narrower and stated in the status: keys the relay does not carry (the `jev` reranker's, a `brain sync` agent runner's login) and every key on a host without managed native storage, where there is no relay. @@ -596,7 +596,7 @@ lists the keys each first-party command reads. The launcher withholds every provider credential in the subprocess descriptor from a governed or strict turn worker, except what its backend declares for its own inference and what an operator admits (`const turnProfile`, -`packages/ui-sdk/src/server/worker-launcher.ts:680-690`). A relayed turn keeps no +`packages/ui-sdk/src/server/worker-launcher.ts:681-691`). A relayed turn keeps no key. An unrelayed one keeps only its runtime's own inference credential, under the 2026-10-22 ruling that hosts without managed native storage keep today's inference credentials; pi resolves its own credentials there, so it keeps all @@ -1027,7 +1027,7 @@ worker's command starts, the server opens that tmpfs from outside through the sandbox's `/proc//root`. It waits until the path is a tmpfs of exactly the allowance on another device than the server's own `/tmp`, and keeps the descriptor -(`function* openPrivateTurnTempSteps`, `packages/ui-sdk/src/server/worker-launcher.ts:1136-1164`). +(`function* openPrivateTurnTempSteps`, `packages/ui-sdk/src/server/worker-launcher.ts:1137-1165`). Every later read goes through that descriptor, after the worker's namespace is gone as well, and never enters another mount, so runtime state below `/tmp` is never read as turn temp. The allowance (256 MiB by default, @@ -1035,14 +1035,14 @@ is gone as well, and never enters another mount, so runtime state below against its own budget, and a turn that cannot reserve it is refused as `worker_state_busy` (docs/hosting/agent-workers.md). The `turn_temp` tool reports usage and purges paths through the same descriptor -(`export function purgeTurnTemp`, `packages/ui-sdk/src/server/worker-turn-temp.ts:450-458`). +(`export function purgeTurnTemp`, `packages/ui-sdk/src/server/worker-turn-temp.ts:451-459`). The restricted envelope gets the same sized `/tmp` and promotes nothing. After the worker exits, the backend rewrites the answer text the turn appended to its saved transcript, and only that text. It looks at Markdown link and image destinations and reference definitions outside code. A file is promoted once per turn however often it is linked, up to 128 MiB per file, 256 MiB and 64 files per turn -(`export function createTurnTempPromoter`, `packages/ui-sdk/src/server/worker-turn-temp.ts:124-135`). +(`export function createTurnTempPromoter`, `packages/ui-sdk/src/server/worker-turn-temp.ts:125-136`). The copy goes to `.brain/scratch/turns//` under a name the reader's file links accept, so the rewritten link is brain-relative and is pinned like any other scratch link. Each result reaches the server as a `promotion` or @@ -1065,10 +1065,10 @@ Live blocks still use streamed-text offsets; the client and server share the span rebasing function and discard ambiguous overlaps as plain Markdown. **Pinning.** A link into `.brain/scratch/` pins the target. Prune skips pinned -files (`export function pruneScratch`, `packages/core/src/lib/scratch.ts:641`). +files (`export function pruneScratch`, `packages/core/src/lib/scratch.ts:645`). A pin is released when every conversation that links the file is deleted or falls out of retention. If the scratch area still exceeds its size limit -(`SCRATCH_MAX_BYTES`, `scratch.ts:58`) after unpinned files are pruned, the +(`SCRATCH_MAX_BYTES`, `scratch.ts:62`) after unpinned files are pruned, the overage is reported. Pinned files are never deleted. A writer that prunes after writing into scratch also passes the paths it just produced, protected for that one call (`pinnedPaths`), so retained pins over the cap cannot make it @@ -1352,7 +1352,7 @@ external editor throughout a native tool's execution. The parent observes the worker's resolved mount sources, including strict startup copies and writable area aliases; it does not substitute newer canonical bytes for a frozen view (`createWorkerFileObserver`, -`packages/ui-sdk/src/server/worker-file-observer.ts:13`). A failed or changing +`packages/ui-sdk/src/server/worker-file-observer.ts:15`). A failed or changing read cannot establish a new version. Claude's native `file_unchanged` response also preserves the previous observation: it supplied no new bytes (`const finishNativeFile`, @@ -2186,7 +2186,7 @@ a filesystem socket that is visible through the read-only host root: a Docker socket, a session bus, an SSH agent or a host proxy. Each of those is an unrecorded way out, and some reach privileged host effects. The launcher already masks `.git` in restricted workers for exactly this reason -(`function maskedGit`, `packages/ui-sdk/src/server/worker-launcher.ts:226`). +(`function maskedGit`, `packages/ui-sdk/src/server/worker-launcher.ts:227`). `governed` and `strict` workers therefore mask the host's runtime and state directories with empty read-only tmpfs mounts. Maintenance workers share the @@ -2204,7 +2204,7 @@ The worker's private `/tmp` and the other host masks remain in place. After the masks, the launcher re-binds only the explicit runtime inputs the worker needs, read-only, with the same resolution the restricted envelope uses -(`export function restrictedReadPaths`, `packages/ui-sdk/src/server/worker-launcher.ts:1910`): +(`export function restrictedReadPaths`, `packages/ui-sdk/src/server/worker-launcher.ts:1911`): - the Bun executable; - the backend entry's package, its `node_modules` chains and linked workspace @@ -2228,7 +2228,7 @@ such ancestor with empty tmpfs instead; it never binds that ancestor's real contents. Search permission uses the helper's primary shared group class when that group owns the directory, including when only the other class has execute permission. Existing canonical aliases and nested masks fold into that cover -(`maintenanceMounts`, `packages/ui-sdk/src/server/worker-launcher.ts:385-444`). +(`maintenanceMounts`, `packages/ui-sdk/src/server/worker-launcher.ts:386-445`). This supports disjoint private-state layouts, including a nested operational database below a server-owned `0700` parent. New ancestor coverage that would @@ -2304,9 +2304,9 @@ and subdirectories through retained aliases. It does not restore unrelated host-temp siblings or make runtime bytes writable. The concrete checks and mounts are in (`validateRuntimePlacement`, -`packages/ui-sdk/src/server/worker-launcher.ts:609-615`), -(`temporaryRuntimeMounts`, `packages/ui-sdk/src/server/worker-launcher.ts:636-675`) -and (`runtimeMaskOverlays`, `packages/ui-sdk/src/server/worker-launcher.ts:791-809`). +`packages/ui-sdk/src/server/worker-launcher.ts:610-616`), +(`temporaryRuntimeMounts`, `packages/ui-sdk/src/server/worker-launcher.ts:637-676`) +and (`runtimeMaskOverlays`, `packages/ui-sdk/src/server/worker-launcher.ts:792-810`). Alias restoration recognizes names already supplied by a read-only bind or an explicit system-view symlink. It does not mount a canonical executable over an existing alias such as `/bin/sh`; missing owned temporary paths still receive @@ -3337,7 +3337,7 @@ before mounting them: both belong to the server, helper mode uses its primary GID and exact `0750`/`0660` modes, and no-helper mode retains exact `0700`/`0600`. Missing endpoints, aliases, non-sockets, foreign ownership and wider modes refuse before payload execution -(`function restrictedMounts`, `packages/ui-sdk/src/server/worker-launcher.ts:250-284`). +(`function restrictedMounts`, `packages/ui-sdk/src/server/worker-launcher.ts:251-285`). This compatibility check does not change default autonomous admission or add another route. @@ -3475,11 +3475,11 @@ An ordinary group-shared directory was accessible, but the worker's private mount and namespace links through `/proc/` were denied. Changing the private directory to `0770` did not remove that process-access barrier. The current launcher opens mounts directly (`function openPrivateState`, -`packages/ui-sdk/src/server/worker-launcher.ts:1099-1127`; +`packages/ui-sdk/src/server/worker-launcher.ts:1100-1128`; `function* openPrivateTurnTempSteps`, -`packages/ui-sdk/src/server/worker-launcher.ts:1136-1162`) before population and +`packages/ui-sdk/src/server/worker-launcher.ts:1137-1163`) before population and start-gate release (`function* launchAgentWorkerSteps`, -`packages/ui-sdk/src/server/worker-launcher.ts:1325-1413`). Group modes and a uid +`packages/ui-sdk/src/server/worker-launcher.ts:1326-1414`). Group modes and a uid switch alone therefore cannot implement the selected cross-uid lifecycle. **Authority and launch.** One trusted external supervisor owns each worker @@ -3914,7 +3914,7 @@ files, `.claude/`, `.agents/`, `.pi/`, `.mcp.json`, and - The core CLI loads `brain.config.ts` or `brain.config.json` at the canonical brain cwd (`loadUserConfig`, `packages/core/src/lib/config.ts:594-628`). Host commands bind that cwd to the selected brain (`function hostSpawn`, - `packages/ui-server/src/brain/host-boundary.ts:511-522`). + `packages/ui-server/src/brain/host-boundary.ts:512-523`). - Bun startup uses root `bunfig.toml` and `package.json`; retained literal preload/module inputs can identify a nested module's nearest package scope. The inventory walks parent directories only within the originating journal diff --git a/docs/decisions/index-query-api.md b/docs/decisions/index-query-api.md index 74886b6add..56f558816e 100644 --- a/docs/decisions/index-query-api.md +++ b/docs/decisions/index-query-api.md @@ -118,7 +118,7 @@ neither justified a service or configurable query-provider seam. > **2026-10-05 — Implementation context (#697).** UI-server now declares the > optional peer and resolves the entry lazily, once per app -> (`createCoreQueryAccess`, `packages/ui-server/src/core-queries.ts:192-227`). The +> (`createCoreQueryAccess`, `packages/ui-server/src/core-queries.ts:193-228`). The > source-backed range is `>=0.40.0 <1.0.0`: the published 0.40.0 manifest is the > first to export `./queries`, its declarations name all nine operations and its > query source matches the source the server was migrated against; 0.39.0 has no diff --git a/docs/decisions/managed-worktrees.md b/docs/decisions/managed-worktrees.md index 3194de6862..c1265b08e3 100644 --- a/docs/decisions/managed-worktrees.md +++ b/docs/decisions/managed-worktrees.md @@ -98,7 +98,7 @@ Each governed or strict turn whose journal is recording opens one worker generation, and every worker of that turn binds the generation's root-owned directory whole at `/tmp/brain-worktrees`, inside the turn's own `/tmp` (`// Managed worktrees (#2430): a journaled turn's workers bind one empty generation.`, `packages/ui-server/src/ws/run-session.ts:570-582`; -`// Managed worktrees (#2430): the whole access generation`, `packages/ui-sdk/src/server/worker-launcher.ts:852-863`). +`// Managed worktrees (#2430): the whole access generation`, `packages/ui-sdk/src/server/worker-launcher.ts:853-864`). A granted worktree appears there as `/tmp/brain-worktrees//` on the worker's next path lookup; the worker cannot create entries beside it, and a restricted worker never binds a generation. Nothing returns a host path to the @@ -212,7 +212,7 @@ nothing. **Shared source is read through views.** Each such turn's workers bind the public view and their principal's private view whole and read-only at `/tmp/brain-reference/public` and `/tmp/brain-reference/private` -(`// Shared reference source (#2432)`, `packages/ui-sdk/src/server/worker-launcher.ts:864-875`). +(`// Shared reference source (#2432)`, `packages/ui-sdk/src/server/worker-launcher.ts:865-876`). A view the domain has not published to yet is opened empty first, so the turn sees its own first acquisition (`async bindable(principalId: string`, `packages/ui-server/src/brain/reference-source.ts:741-753`). diff --git a/docs/decisions/policy-write-boundary.md b/docs/decisions/policy-write-boundary.md index 3fe86900e3..2ca54a82af 100644 --- a/docs/decisions/policy-write-boundary.md +++ b/docs/decisions/policy-write-boundary.md @@ -497,13 +497,13 @@ sessions. before the runtime starts and read it after the worker is gone, while the tmpfs is reachable only inside the worker. The launcher does both from the host (`function* launchAgentWorkerSteps`, -`packages/ui-sdk/src/server/worker-launcher.ts:1325-1580`): +`packages/ui-sdk/src/server/worker-launcher.ts:1326-1581`): 1. It finds the sandbox's first process from the kernel's record of bubblewrap's only child, then opens the tmpfs root through `/proc//root` and keeps that directory descriptor (`function openPrivateState`, - `packages/ui-sdk/src/server/worker-launcher.ts:1099-1123`). bubblewrap's + `packages/ui-sdk/src/server/worker-launcher.ts:1100-1124`). bubblewrap's process exists before its mounts do, so the open is accepted only once the path is its own mount (a device other than its parent's), a tmpfs of exactly the allowance, and empty; until then it would name the host's @@ -513,7 +513,7 @@ host (`function* launchAgentWorkerSteps`, code: the absolute `/bin/sh` reads one line from the worker's stdin with its `read` builtin, which only the server writes, and then becomes the command; closed stdin or any other line ends the worker unstarted - (`const STATE_GATE`, `packages/ui-sdk/src/server/worker-launcher.ts:56`). + (`const STATE_GATE`, `packages/ui-sdk/src/server/worker-launcher.ts:57`). The gate runs no `PATH` lookup, so nothing in the worker's environment or the brain can stand in for it, and the shell reads a pipe a byte at a time, so the runtime's own input is untouched. The server copies the snapshot in diff --git a/docs/decisions/public-export-boundary.md b/docs/decisions/public-export-boundary.md index 09a16600ad..2f9f8d42d7 100644 --- a/docs/decisions/public-export-boundary.md +++ b/docs/decisions/public-export-boundary.md @@ -290,15 +290,17 @@ its watch implementation and CLI remain implementation details. An internal-only package (#1396): `@schlessera/brain-common` has no root entry. Its entries, `./internal/env`, `./internal/frontmatter` and `./internal/worker-areas`, `./internal/protected-paths`, -`./internal/governance-policy` and `./internal/claude-subscription`, follow -the internal-entry rule above. +`./internal/governance-policy`, `./internal/claude-subscription` and +`./internal/safe-path`, follow the internal-entry rule above. The policy helper (#1744) serves both core and the server without requiring the server’s optional core peer; it adds no supported extension interface. The first two replace byte-identical copies of `env-core.ts` and `frontmatter-parse.ts` that the packages carried; the third (#1693) holds the worker write-area rules that the ui-sdk's sandbox note and core's CLI refusal both state. The subscription billing guard (#2493) replaces the copies core's CLI runner and -the chat backend carried. A name a +the chat backend carried. Symlink-safe containment (#2506) replaces the +resolvers core, the ui-sdk and ui-server carried and their hand-written +containment predicates. A name a public entry re-exports from it, such as core's `DynamicEnvReadSpec` and `readEnvVar`, stays part of that package's supported surface and is recorded in that package's report. diff --git a/docs/decisions/reference-pool-accounting.md b/docs/decisions/reference-pool-accounting.md index 76858e1b86..25b09c9aed 100644 --- a/docs/decisions/reference-pool-accounting.md +++ b/docs/decisions/reference-pool-accounting.md @@ -8,7 +8,7 @@ actual allocated disk. That decision left the mechanism to implementation. This record names the mechanism, the primary sources it relies on and the native observations that qualified it. The pool is managed by the existing host-only native manager -(`createNativeReferencePool`, `packages/ui-sdk/src/server/native-reference-pool.ts:270-962`). +(`createNativeReferencePool`, `packages/ui-sdk/src/server/native-reference-pool.ts:272-964`). No consumer uses it yet. ## A separate volume, not another subvolume of the brain store @@ -224,7 +224,7 @@ directory its intent records. Sealing also makes the root's top directory `roots/` and `views/` join the mandatory worker masks. A worker sees reference source only through a view bound for it, and other domains' views stay invisible. `poolView` (#2432) opens a view's directory before its first -publication (`function viewOpen`, `packages/ui-sdk/src/server/native-reference-pool.ts:938-941`), +publication (`function viewOpen`, `packages/ui-sdk/src/server/native-reference-pool.ts:940-943`), so a worker that binds it at its start sees the domain's first publication on a later lookup ([agent tools](managed-worktrees.md#agent-tools)). diff --git a/docs/decisions/worker-writable-areas.md b/docs/decisions/worker-writable-areas.md index 773ca521ef..118fd68354 100644 --- a/docs/decisions/worker-writable-areas.md +++ b/docs/decisions/worker-writable-areas.md @@ -81,7 +81,7 @@ on the transcript persist path and is not part of this record. **One resolution, two consumers.** `prepareWorkerSandbox` resolves the areas and per-turn XDG layout once per worker -(`export function prepareWorkerSandbox`, `packages/ui-sdk/src/server/worker-launcher.ts:901-942`). +(`export function prepareWorkerSandbox`, `packages/ui-sdk/src/server/worker-launcher.ts:902-943`). The backend passes the result both to the launcher, which turns it into bubblewrap arguments, and to `workerSandboxNote`, which renders the agent's note (`export function workerSandboxNote`, `packages/ui-sdk/src/server/worker-sandbox.ts:592-657`). @@ -89,7 +89,7 @@ The launcher re-checks the resolved layout against the actual launch: the same brain and envelope, each writable area still a real directory at its own path in the brain. The backend selects runtime HOME separately. A mismatch refuses the launch instead of binding something the note does not -describe (`function sandboxMounts`, `packages/ui-sdk/src/server/worker-launcher.ts:823-853`). +describe (`function sandboxMounts`, `packages/ui-sdk/src/server/worker-launcher.ts:824-854`). A launch without a resolved layout keeps the 0.41 view: only the per-turn scratch is writable. @@ -153,7 +153,7 @@ through the roadblock path. This is a worker write boundary, not an immutable view: host-side changes to that directory remain visible. A backend may select a different runtime HOME as described below; it does not make the host home writable. `prepareWorkerSandbox` resolves this same XDG mode on every eligible host (`export function prepareWorkerSandbox`, -`packages/ui-sdk/src/server/worker-launcher.ts:901-942`). Host-backed overlay +`packages/ui-sdk/src/server/worker-launcher.ts:902-943`). Host-backed overlay uppers cannot live on the worker's private tmpfs; keeping them would leave an unbounded write area. Tools reading XDG config see the per-turn directory, while direct reads of real HOME retain the read-only host view. @@ -267,17 +267,17 @@ The `read_only_brain` code and its **Serving.** The file routes refuse any symlink at or below `.brain` for a scratch path, and a scratch listing omits links -(`const scratchRequest`, `packages/ui-server/src/files/walker.ts:115`). +(`const policy: ContainmentPolicy = isScratchPath(rel)`, `packages/ui-server/src/files/walker.ts:97-99`). Elsewhere in the brain an in-brain link resolves as before. Those checks run before the open, so a file whose requested or resolved path lies in `.brain/scratch/` or `workspaces/` is then read once, from its resolved path, through descriptors that never follow a link (each directory from the brain root opened with `O_NOFOLLOW | O_DIRECTORY` through the previous one, the file with `O_NOFOLLOW`), and the route serves that snapshot; the size cap bounds it -(`export function readAnchoredSnapshot`, `packages/ui-server/src/files/walker.ts:157-193`). +(`export function readAnchoredSnapshot`, `packages/ui-server/src/files/walker.ts:116-152`). Core's prune reads every entry with `lstat`, and on Linux removes each file and emptied directory through its parent's descriptor in the same way -(`function anchored`, `packages/core/src/lib/scratch.ts:513-543`), because a +(`function anchored`, `packages/core/src/lib/scratch.ts:517-547`), because a hosted agent can swap a scratch directory for a link while the host prunes. ## Measurements diff --git a/docs/hosting/agent-workers.md b/docs/hosting/agent-workers.md index f69970cf33..0c97221d98 100644 --- a/docs/hosting/agent-workers.md +++ b/docs/hosting/agent-workers.md @@ -91,7 +91,7 @@ owner-only `0700`/`0600` modes. Before mounting the proxy, the launcher checks canonical paths, server ownership, the expected helper group, exact modes and socket type. Missing entries, symlinks and widened permissions refuse before the payload starts (`if (input.egress)`, -`packages/ui-sdk/src/server/worker-launcher.ts:552-567`). This does not select +`packages/ui-sdk/src/server/worker-launcher.ts:553-568`). This does not select the ordinary inference route or enable the proxy by default. Native output stages use the existing manager's active stage identity. The @@ -1273,7 +1273,7 @@ its working directory. No first-party code reads `.env` any other way. The launcher binds `/dev/null` over every present `.env*` name at the brain root, and over the file an `.env*` link leads to, after every other mount, so no later bind can restore it (`maintenanceEnvMasks`, -`packages/ui-sdk/src/server/maintenance-env-masks.ts:66-70`). The worker cannot +`packages/ui-sdk/src/server/maintenance-env-masks.ts:67-71`). The worker cannot open them: a read fails with `EACCES`, so Bun loads nothing and `cat .env` prints nothing. A new `.env*` name is a protected tier A path, so a turn cannot create one in the brain either. diff --git a/docs/plans/module-renderers.md b/docs/plans/module-renderers.md index 2fbb6dab9a..6ed484352b 100644 --- a/docs/plans/module-renderers.md +++ b/docs/plans/module-renderers.md @@ -181,7 +181,7 @@ reach the app through `![](x.svg)`: - **An `.svg` file must open as an image.** Today it opens as source, because the byte sniff in `export function classifyKind`, - `packages/ui-server/src/files/walker.ts:347` classifies UTF-8 SVG as text. + `packages/ui-server/src/files/walker.ts:303` classifies UTF-8 SVG as text. - **SVG images must print light.** Measured: a host `@media print { :root { color-scheme: light } }` makes an `` SVG take its light palette. diff --git a/docs/plans/storage-accounting.md b/docs/plans/storage-accounting.md index f90b09c73c..89bfce463f 100644 --- a/docs/plans/storage-accounting.md +++ b/docs/plans/storage-accounting.md @@ -69,14 +69,14 @@ Source anchors, checked against the reviewed commit: thinning (`thin`, `packages/core/src/lib/stats-history.ts:232-244`). - D: effective path/journal resolution (`createApp`, `packages/ui-server/src/app.ts:301-337`), WAL store (`createUiDb`, `packages/ui-server/src/db/client.ts:27-44`), and - private locations (`statePaths`, `packages/ui-server/src/brain/operational-state.ts:108-114`). + private locations (`statePaths`, `packages/ui-server/src/brain/operational-state.ts:114-120`). - E: live/archive paths (`transcriptPaths`, `packages/ui-backend-claude/src/transcript-archive.ts:30-39`). - F: session location (`piSessionDirectory`, `packages/ui-backend-pi/src/session-storage.ts:8-28`). - G: staging location (`shareStagingRoot`, `packages/ui-server/src/share/staging.ts:143-145`) and settlement-aware cleanup (`function claim`, `packages/ui-server/src/inbox/lifecycle-writes.ts:42-61`). [#807](https://github.com/schlessera/brain-kit/issues/807) supplies live-work and settlement protection for staging cleanup. -- H: scratch defaults (`SCRATCH_DIR`, `packages/core/src/lib/scratch.ts:52-61`), +- H: scratch defaults (`SCRATCH_DIR`, `packages/core/src/lib/scratch.ts:56-65`), scheduled prune (`startScratchPrune`, `packages/ui-server/src/cron/scratch-prune.ts:41-49`), and the [writable-area decision](../decisions/worker-writable-areas.md). [#1656](https://github.com/schlessera/brain-kit/issues/1656) supplies retained diff --git a/docs/plans/storage-lifecycle.md b/docs/plans/storage-lifecycle.md index b0295ec76e..2aa8b12251 100644 --- a/docs/plans/storage-lifecycle.md +++ b/docs/plans/storage-lifecycle.md @@ -76,9 +76,9 @@ Source foundations for the matrix: - Staging eligibility, removal and acknowledgment are separate (`export function createInboxCleanup`, `packages/ui-server/src/inbox/cleanup.ts:18-82`). - Scratch pin loading and per-entry revalidation sit inside pruning - (`export function pruneScratch`, `packages/core/src/lib/scratch.ts:641-722`); + (`export function pruneScratch`, `packages/core/src/lib/scratch.ts:645-726`); explicit clean is different - (`export function cleanScratch`, `packages/core/src/lib/scratch.ts:725-743`). + (`export function cleanScratch`, `packages/core/src/lib/scratch.ts:729-747`). Server refresh refuses incomplete enumeration and confirms missing histories before releasing links (`function openScratchPins`, `packages/ui-server/src/cron/scratch-pins.ts:72-195`). - Claude publishes and verifies cold copies before deleting the live source @@ -90,7 +90,7 @@ Source foundations for the matrix: Object copies reserve temporary bytes before writing (`async putFileAsync`, `packages/ui-server/src/brain/journal-objects.ts:95-150`). - Turn-temp purge has its own scope and measured result - (`export function purgeTurnTemp`, `packages/ui-sdk/src/server/worker-turn-temp.ts:450-533`), + (`export function purgeTurnTemp`, `packages/ui-sdk/src/server/worker-turn-temp.ts:451-534`), and tool validation/recording (`export function handleTurnTemp`, `packages/ui-sdk/src/server/bridge-tools/turn-temp.ts:19-41`). [Operational recovery](../inbox-recovery.md) specifies backup consistency and diff --git a/packages/common/README.md b/packages/common/README.md index 0bbc577d31..c004c6cba3 100644 --- a/packages/common/README.md +++ b/packages/common/README.md @@ -16,6 +16,7 @@ one; it arrives as their dependency. | `@schlessera/brain-common/internal/governance-policy` | Data-only policy schema, defaults, parsing and anchored reads shared by the core CLI and hosted server (#1744). The server can read policy without installing its optional core peer. | | `@schlessera/brain-common/internal/index-location` | Where the disposable search index lives: the `.brain-index/` directory holding `brain.db` and its SQLite sidecars, and the legacy root-level names a brain migrates away from by rebuilding (#1668). | | `@schlessera/brain-common/internal/claude-subscription` | The subscription billing guard both Claude runners apply: the cleared credential variables, the neutralised flag settings, the settings refusal and the account verdict. core's CLI runner and the chat backend import it, so a newly found credential or routing variable is added once (#2493). | +| `@schlessera/brain-common/internal/safe-path` | Symlink-safe path containment: `isWithin`, the containment primitive whose equality, separator, trailing-separator and normalisation answers are explicit parameters, and `resolveContained`/`resolveContainedSync`, one canonicalisation algorithm that resolves a request under the root's realpath through its nearest existing ancestor. core's `safeResolve`, the SDK's `resolveInRepo` and the server's `safeResolve` are thin wrappers that each keep their own request refusals and policy, so a hardening fix lands once (#2506). | Nothing else belongs here. A further helper needs its own issue and a reason it cannot live in the package that uses it. diff --git a/packages/common/package.json b/packages/common/package.json index 006737a9a6..314678be3e 100644 --- a/packages/common/package.json +++ b/packages/common/package.json @@ -75,6 +75,11 @@ "bun": "./src/claude-subscription.ts", "types": "./dist/claude-subscription.d.ts", "default": "./dist/claude-subscription.js" + }, + "./internal/safe-path": { + "bun": "./src/safe-path.ts", + "types": "./dist/safe-path.d.ts", + "default": "./dist/safe-path.js" } }, "files": [ diff --git a/packages/common/src/safe-path.ts b/packages/common/src/safe-path.ts new file mode 100644 index 0000000000..f9b3fba908 --- /dev/null +++ b/packages/common/src/safe-path.ts @@ -0,0 +1,255 @@ +/** + * Symlink-safe path containment, held once for core, the ui-sdk and ui-server + * (#2506). Two parts: + * + * - {@link isWithin}, the string question "is this path the root or below + * it?". The callers' answers differ on equality, the separator, a root + * ending in a separator and normalisation, so those are parameters + * ({@link WithinRule}) rather than hidden choices. + * - {@link resolveContained} and {@link resolveContainedSync}, one + * canonicalisation algorithm: resolve the request under the root's + * realpath, canonicalise its nearest existing ancestor, and check the + * canonical result against the root. A dangling link is either followed + * to its target, which must stay inside, or refused. The algorithm is a + * generator of filesystem queries, so the synchronous and asynchronous + * variants run the same steps. + * + * What a caller accepts as a request (absolute paths, `..`, Windows syntax) + * and how it reports a refusal stay in that caller: they are its policy, and + * the resolver rows of #2506 differ on them. Everything after the request is + * accepted is decided here. + */ +import { lstatSync, readlinkSync, realpathSync } from "node:fs"; +import { lstat, readlink, realpath } from "node:fs/promises"; +import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path"; + +/** How {@link isWithin} answers the cases its callers disagree on. */ +export interface WithinRule { + /** Whether the root itself counts as within. Default `true`. */ + readonly includeRoot?: boolean; + /** The separator that must follow the root. Default `/`. */ + readonly separator?: string; + /** + * A root already ending in the separator: `"append"` (default) appends + * another, so `/` and `/a/` hold nothing below them; `"boundary"` takes the + * root's own separator as the boundary, so `/` holds every absolute path. + */ + readonly trailingSeparator?: "append" | "boundary"; + /** + * Resolve both paths against the working directory first, as + * `path.relative` does, so `/a/b/../c` is not within `/a/b`. Default + * `false`: the comparison is on the strings as given. + */ + readonly resolvePaths?: boolean; +} + +/** Whether `path` is `root` or below it, under `rule`. The argument order is fixed: root first. */ +export function isWithin(root: string, path: string, rule: WithinRule = {}): boolean { + if (rule.resolvePaths) { + root = resolve(root); + path = resolve(path); + } + if (path === root) return rule.includeRoot ?? true; + const separator = rule.separator ?? "/"; + const prefix = rule.trailingSeparator === "boundary" && root.endsWith(separator) ? root : root + separator; + return path.startsWith(prefix); +} + +/** The platform-separator rule the resolvers check canonical paths with. */ +const CANONICAL: WithinRule = { separator: sep }; + +/** What a caller decides about the filesystem it resolves through. */ +export interface ContainmentPolicy { + /** + * A root whose realpath fails. `"refuse"`: nothing resolves. `"lexical"`: + * a root that does not exist yet contains the lexical path; a dangling + * link in its place is refused and any other failure is an error. + */ + readonly missingRoot: "refuse" | "lexical"; + /** + * A symlink whose target cannot be resolved. `"follow"`: re-check its + * target, which must stay inside, so a write through it lands inside. + * `"refuse"`: refuse it, wherever it points. + */ + readonly danglingLinks: "follow" | "refuse"; + /** + * `"final"`: only the canonical path must stay inside, so a request may + * leave through one link and come back through another. `"every"`: each + * existing component on the way must stay inside too. + */ + readonly components: "final" | "every"; + /** + * Refuse a symlink at this lexical component without following it; `root` + * is the root's realpath. Only consulted with `components: "every"`, + * which visits each component. + */ + readonly refuseLinkAt?: (path: string, root: string) => boolean; +} + +/** Why a request was refused. */ +export type ContainmentRefusal = "nul" | "missing-root" | "escape" | "dangling" | "link-budget" | "refused-link"; + +export type ContainedPath = + | { + readonly ok: true; + /** The root's realpath (its lexical path when a missing root is allowed). */ + readonly root: string; + /** The request resolved under {@link root}, links as written. */ + readonly lexical: string; + /** The request with every existing link followed; the missing tail as written. */ + readonly canonical: string; + } + | { readonly ok: false; readonly reason: ContainmentRefusal } + /** A filesystem failure that is neither absence nor a refusal (EIO, ...). */ + | { readonly ok: false; readonly reason: "error"; readonly error: NodeJS.ErrnoException }; + +/** + * Codes that mean "this component cannot be resolved": the lookup stops + * there and what follows is treated as not existing yet. Any other code is + * an error, never an acceptance. + */ +const UNRESOLVABLE = new Set(["ENOENT", "ENOTDIR", "ENAMETOOLONG", "ELOOP", "EACCES", "EPERM"]); + +/** The kernel's symlink budget for one lookup. */ +const MAX_LINK_HOPS = 40; + +type FsQuery = + | { readonly op: "realpath" | "readlink"; readonly path: string } + | { readonly op: "lstat"; readonly path: string }; +type FsReply = + | { readonly ok: true; readonly value: string; readonly link: boolean } + | { readonly ok: false; readonly error: NodeJS.ErrnoException }; +type Steps = Generator; + +const failed = (error: unknown): FsReply => ({ ok: false, error: error as NodeJS.ErrnoException }); +const unresolvable = (reply: FsReply) => !reply.ok && UNRESOLVABLE.has(reply.error.code ?? ""); + +function querySync(query: FsQuery): FsReply { + try { + if (query.op === "lstat") return { ok: true, value: query.path, link: lstatSync(query.path).isSymbolicLink() }; + return { ok: true, value: query.op === "realpath" ? realpathSync(query.path) : readlinkSync(query.path), link: false }; + } catch (error) { + return failed(error); + } +} + +async function queryAsync(query: FsQuery): Promise { + try { + if (query.op === "lstat") return { ok: true, value: query.path, link: (await lstat(query.path)).isSymbolicLink() }; + return { ok: true, value: query.op === "realpath" ? await realpath(query.path) : await readlink(query.path), link: false }; + } catch (error) { + return failed(error); + } +} + +/** + * Canonicalise `path` (lexically inside `root`, a realpath): realpath its + * nearest existing ancestor and re-append the missing tail. A purely lexical + * fallback would let a symlinked parent smuggle a not-yet-created file + * outside the root. A dangling link is not "missing": a write through it is + * created at its target, so it is followed and re-checked, or refused. + */ +function* canonicalise(root: string, path: string, policy: ContainmentPolicy): Steps { + let existing = path; + let tail: string[] = []; + let hops = 0; + for (;;) { + const real = yield { op: "realpath", path: existing }; + if (real.ok) { + const candidate = tail.length > 0 ? join(real.value, ...tail) : real.value; + if (!isWithin(root, candidate, CANONICAL)) return { ok: false, reason: "escape" }; + return { ok: true, root, lexical: path, canonical: candidate }; + } + if (!unresolvable(real)) return { ok: false, reason: "error", error: real.error }; + const entry = yield { op: "lstat", path: existing }; + if (entry.ok && entry.link) { + // A link whose realpath fails: dangling, a cycle, or unreadable. + if (policy.danglingLinks === "refuse") return { ok: false, reason: "dangling" }; + if (++hops > MAX_LINK_HOPS) return { ok: false, reason: "link-budget" }; + const target = yield { op: "readlink", path: existing }; + if (!target.ok) return { ok: false, reason: "error", error: target.error }; + const resolved = isAbsolute(target.value) ? resolve(target.value) : resolve(dirname(existing), target.value); + const rejoined = tail.length > 0 ? join(resolved, ...tail) : resolved; + if (!isWithin(root, rejoined, CANONICAL)) return { ok: false, reason: "escape" }; + existing = rejoined; + tail = []; + continue; + } + if (!entry.ok && !unresolvable(entry)) return { ok: false, reason: "error", error: entry.error }; + // Not there (yet), or there but not resolvable as a whole: canonicalise + // what is above it. The walk ends at the root, which resolved. + tail.unshift(basename(existing)); + const parent = dirname(existing); + if (parent === existing) return { ok: false, reason: "escape" }; + existing = parent; + } +} + +function* containedSteps(root: string, rel: string, policy: ContainmentPolicy): Steps { + // A NUL would make the later fs call throw: a containment failure, not a + // deferred TypeError. + if (rel.includes("\0")) return { ok: false, reason: "nul" }; + const lexicalRoot = resolve(root); + const rootReal = yield { op: "realpath", path: lexicalRoot }; + if (!rootReal.ok) { + if (policy.missingRoot === "refuse") return { ok: false, reason: "missing-root" }; + if (rootReal.error.code !== "ENOENT") return { ok: false, reason: "error", error: rootReal.error }; + // Present but unresolvable means a dangling link stands in its place. + const entry = yield { op: "lstat", path: lexicalRoot }; + if (entry.ok) return { ok: false, reason: "dangling" }; + if (!unresolvable(entry)) return { ok: false, reason: "error", error: entry.error }; + const lexical = resolve(lexicalRoot, rel); + if (!isWithin(lexicalRoot, lexical, CANONICAL)) return { ok: false, reason: "escape" }; + // Nothing below a missing root exists to be followed. + return { ok: true, root: lexicalRoot, lexical, canonical: lexical }; + } + const absRoot = rootReal.value; + const lexical = resolve(absRoot, rel); + if (!isWithin(absRoot, lexical, CANONICAL)) return { ok: false, reason: "escape" }; + if (policy.components === "final") { + const contained = yield* canonicalise(absRoot, lexical, policy); + return contained.ok ? { ...contained, lexical } : contained; + } + // Each component in order, from the root down: a link refused here is + // refused before it is followed, and every existing prefix must canonicalise + // inside, not only the whole path. + let prefix = absRoot; + const prefixes = [absRoot]; + for (const segment of relative(absRoot, lexical).split(sep)) { + if (!segment) continue; + prefix = join(prefix, segment); + prefixes.push(prefix); + } + let canonical = absRoot; + for (const path of prefixes) { + if (policy.refuseLinkAt?.(path, absRoot)) { + const entry = yield { op: "lstat", path }; + if (entry.ok && entry.link) return { ok: false, reason: "refused-link" }; + } + const contained = yield* canonicalise(absRoot, path, policy); + if (!contained.ok) return contained; + canonical = contained.canonical; + } + return { ok: true, root: absRoot, lexical, canonical }; +} + +/** {@link resolveContained}, synchronously. */ +export function resolveContainedSync(root: string, rel: string, policy: ContainmentPolicy): ContainedPath { + const steps = containedSteps(root, rel, policy); + let step = steps.next(); + while (!step.done) step = steps.next(querySync(step.value)); + return step.value; +} + +/** + * Resolve `rel` under `root` and check that it stays inside, following + * symlinks, under the caller's {@link ContainmentPolicy}. Each call reads the + * filesystem again: the answer describes the moment of the call, so a + * caller that opens the path later still owns the race between the two. + */ +export async function resolveContained(root: string, rel: string, policy: ContainmentPolicy): Promise { + const steps = containedSteps(root, rel, policy); + let step = steps.next(); + while (!step.done) step = steps.next(await queryAsync(step.value)); + return step.value; +} diff --git a/packages/common/tests/safe-path.test.ts b/packages/common/tests/safe-path.test.ts new file mode 100644 index 0000000000..72f4d7f1c2 --- /dev/null +++ b/packages/common/tests/safe-path.test.ts @@ -0,0 +1,170 @@ +import { afterAll, describe, expect, test } from "bun:test"; +import { mkdirSync, mkdtempSync, realpathSync, renameSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, relative, sep } from "node:path"; + +import { + isWithin, + resolveContained, + resolveContainedSync, + type ContainedPath, + type ContainmentPolicy, + type WithinRule, +} from "../src/safe-path"; + +describe("isWithin(root, path, rule)", () => { + // Columns: equality, child, sibling prefix, parent, root `/` (absolute, + // itself, relative), trailing separator on the root, unnormalised paths. + const CASES: [string, string][] = [ + ["/a/b", "/a/b"], ["/a/b", "/a/b/c"], ["/a/b", "/a/bc"], ["/a/b", "/a"], + ["/", "/x"], ["/", "/"], ["/", "x"], + ["/a/b/", "/a/b/c"], ["/a/b/", "/a/b"], + ["/a/b", "/a/b/"], ["/a/b", "/a/b/../c"], ["/a/b", "/a/b/..c"], ["/a/b", "/a/b//c"], + ]; + const row = (rule?: WithinRule) => CASES.map(([root, path]) => (isWithin(root, path, rule) ? "T" : "-")).join(" "); + + // Every combination a caller uses (#2506), each written out. + test("the default: root included, `/` appended to any root, strings as given", () => { + expect(row()).toBe("T T - - - T - - - T T T T"); + expect(row({ includeRoot: true, separator: "/", trailingSeparator: "append", resolvePaths: false })).toBe(row()); + }); + + test("a trailing separator on the root is its boundary, so `/` holds every absolute path", () => { + expect(row({ trailingSeparator: "boundary" })).toBe("T T - - T T - T - T T T T"); + }); + + test("resolved first, root included (relative()-based callers)", () => { + expect(row({ resolvePaths: true, separator: sep, trailingSeparator: "boundary" })).toBe("T T - - T T T T T T - T T"); + }); + + test("resolved first, root excluded", () => { + expect(row({ includeRoot: false, resolvePaths: true, separator: sep, trailingSeparator: "boundary" })) + .toBe("- T - - T - T T - - - T T"); + }); + + test("the separator is a parameter", () => { + expect(isWithin("C:\\a", "C:\\a\\b", { separator: "\\" })).toBe(true); + expect(isWithin("C:\\a", "C:\\ab", { separator: "\\" })).toBe(false); + expect(isWithin("C:\\a", "C:\\a/b", { separator: "\\" })).toBe(false); + expect(isWithin("/a", "/a\\b", { separator: "\\" })).toBe(true); + }); + + test("the sibling prefix is never within, under any rule", () => { + for (const rule of [{}, { trailingSeparator: "boundary" }, { resolvePaths: true }, { includeRoot: false }] as WithinRule[]) { + expect(isWithin("/srv/brain", "/srv/brain-other/x", rule)).toBe(false); + expect(isWithin("/srv/brain", "/srv/brainx", rule)).toBe(false); + } + }); + + test("the argument order is root first", () => { + expect(isWithin("/a", "/a/b")).toBe(true); + expect(isWithin("/a/b", "/a")).toBe(false); + }); +}); + +const base = realpathSync(mkdtempSync(join(tmpdir(), "brain-common-safe-path-"))); +afterAll(() => rmSync(base, { recursive: true, force: true })); +const root = join(base, "brain"); +const outside = join(base, "brain-other"); +mkdirSync(join(root, "notes"), { recursive: true }); +mkdirSync(join(root, ".brain/scratch"), { recursive: true }); +mkdirSync(outside); +writeFileSync(join(root, "notes/a.md"), "a"); +writeFileSync(join(outside, "secret.md"), "s"); +symlinkSync("notes", join(root, "link-in")); +symlinkSync(outside, join(root, "link-out")); +symlinkSync("notes/missing", join(root, "dangling-in")); +symlinkSync(join(outside, "missing"), join(root, "dangling-out")); +symlinkSync("cycle-b", join(root, "cycle-a")); +symlinkSync("cycle-a", join(root, "cycle-b")); +symlinkSync(outside, join(root, "bounce")); +symlinkSync(join(root, "notes"), join(outside, "back")); +symlinkSync("../../notes", join(root, ".brain/scratch/link")); +symlinkSync(root, join(base, "root-link")); + +const FINAL_FOLLOW: ContainmentPolicy = { missingRoot: "refuse", danglingLinks: "follow", components: "final" }; +const EVERY_REFUSE: ContainmentPolicy = { missingRoot: "lexical", danglingLinks: "refuse", components: "every" }; + +/** `canonical` (and `lexical` when it differs) relative to the fixture base, or the refusal. */ +function show(result: ContainedPath): string { + if (!result.ok) return result.reason === "error" ? `error ${result.error.code}` : `refused ${result.reason}`; + const canonical = relative(base, result.canonical); + const lexical = relative(base, result.lexical); + return canonical === lexical ? canonical : `${canonical} (as ${lexical})`; +} + +/** Both variants, which must agree. */ +async function both(at: string, rel: string, policy: ContainmentPolicy): Promise { + const sync = show(resolveContainedSync(at, rel, policy)); + expect(show(await resolveContained(at, rel, policy))).toBe(sync); + return sync; +} + +describe("resolveContained: one algorithm, sync and async", () => { + const rows: [string, string, string][] = [ + // rel, final + follow, every + refuse + ["notes/a.md", "brain/notes/a.md", "brain/notes/a.md"], + ["notes/new.md", "brain/notes/new.md", "brain/notes/new.md"], + ["a/b/c.md", "brain/a/b/c.md", "brain/a/b/c.md"], + ["", "brain", "brain"], + ["../brain-other/secret.md", "refused escape", "refused escape"], + ["notes/../../brain-other", "refused escape", "refused escape"], + ["a\0b", "refused nul", "refused nul"], + ["link-in/a.md", "brain/notes/a.md (as brain/link-in/a.md)", "brain/notes/a.md (as brain/link-in/a.md)"], + // A symlinked parent of a file that does not exist yet. + ["link-out/new.md", "refused escape", "refused escape"], + ["link-in/new.md", "brain/notes/new.md (as brain/link-in/new.md)", "brain/notes/new.md (as brain/link-in/new.md)"], + ["dangling-in", "brain/notes/missing (as brain/dangling-in)", "refused dangling"], + ["dangling-in/x", "brain/notes/missing/x (as brain/dangling-in/x)", "refused dangling"], + ["dangling-out", "refused escape", "refused dangling"], + // A dangling cycle: followed, it runs out of the link budget. + ["cycle-a", "refused link-budget", "refused dangling"], + ["cycle-a/x", "refused link-budget", "refused dangling"], + // Out through one link and back through another. + ["bounce/back/a.md", "brain/notes/a.md (as brain/bounce/back/a.md)", "refused escape"], + ]; + for (const [rel, finalFollow, everyRefuse] of rows) { + test(JSON.stringify(rel), async () => { + expect(await both(root, rel, FINAL_FOLLOW)).toBe(finalFollow); + expect(await both(root, rel, EVERY_REFUSE)).toBe(everyRefuse); + }); + } + + test("an absolute request is resolved like any other: inside is accepted", async () => { + expect(await both(root, join(root, "notes/a.md"), FINAL_FOLLOW)).toBe("brain/notes/a.md"); + expect(await both(root, "/etc/passwd", FINAL_FOLLOW)).toBe("refused escape"); + }); + + test("a root that is itself a symlink resolves against its target", async () => { + expect(await both(join(base, "root-link"), "notes/a.md", FINAL_FOLLOW)).toBe("brain/notes/a.md"); + expect(await both(join(base, "root-link"), "link-out/x", EVERY_REFUSE)).toBe("refused escape"); + }); + + test("a missing root: refused, or the lexical path; never through a dangling link or a file", async () => { + expect(await both(join(base, "nope"), "notes/a.md", FINAL_FOLLOW)).toBe("refused missing-root"); + expect(await both(join(base, "nope"), "notes/a.md", EVERY_REFUSE)).toBe("nope/notes/a.md"); + expect(await both(join(base, "nope"), "../brain/notes", EVERY_REFUSE)).toBe("refused escape"); + expect(await both(join(root, "dangling-in"), "x", EVERY_REFUSE)).toBe("refused dangling"); + writeFileSync(join(base, "file"), ""); + expect(await both(join(base, "file/x"), "y", EVERY_REFUSE)).toBe("error ENOTDIR"); + }); + + test("refuseLinkAt refuses a link at a chosen component before following it", async () => { + const policy: ContainmentPolicy = { ...EVERY_REFUSE, refuseLinkAt: (path, absRoot) => isWithin(join(absRoot, ".brain"), path) }; + expect(await both(root, ".brain/scratch/link/a.md", policy)).toBe("refused refused-link"); + expect(await both(root, ".brain/scratch/link/a.md", EVERY_REFUSE)).toBe("brain/notes/a.md (as brain/.brain/scratch/link/a.md)"); + expect(await both(root, "link-in/a.md", policy)).toBe("brain/notes/a.md (as brain/link-in/a.md)"); + // Only the component walk consults it. + expect(await both(root, ".brain/scratch/link/a.md", { ...FINAL_FOLLOW, refuseLinkAt: () => true })).toBe("brain/notes/a.md (as brain/.brain/scratch/link/a.md)"); + }); + + test("each call reads the filesystem again: a directory swapped for an escaping link is refused", async () => { + const swap = join(root, "swap"); + mkdirSync(swap); + expect(await both(root, "swap/new.md", FINAL_FOLLOW)).toBe("brain/swap/new.md"); + renameSync(swap, join(base, "swapped-away")); + symlinkSync(outside, swap); + expect(await both(root, "swap/new.md", FINAL_FOLLOW)).toBe("refused escape"); + expect(await both(root, "swap/new.md", EVERY_REFUSE)).toBe("refused escape"); + }); +}); diff --git a/packages/core/src/lib/safe-path.ts b/packages/core/src/lib/safe-path.ts index 4dd66513dd..27e162362b 100644 --- a/packages/core/src/lib/safe-path.ts +++ b/packages/core/src/lib/safe-path.ts @@ -1,82 +1,26 @@ import { randomBytes } from "crypto"; -import { closeSync, fchmodSync, linkSync, lstatSync, mkdirSync, openSync, realpathSync, readlinkSync, renameSync, rmSync, writeSync } from "fs"; +import { resolveContainedSync, type ContainmentPolicy } from "@schlessera/brain-common/internal/safe-path"; +import { closeSync, fchmodSync, linkSync, lstatSync, mkdirSync, openSync, realpathSync, renameSync, rmSync, writeSync } from "fs"; import type { Stats } from "fs"; -import { basename, dirname, isAbsolute, join, resolve, sep } from "path"; +import { basename, dirname, join } from "path"; + +const CORE_CONTAINMENT: ContainmentPolicy = { missingRoot: "refuse", danglingLinks: "follow", components: "final" }; /** * Resolve a relative path and verify it stays inside `root`, following * symlinks (realpath) so a symlink inside the repo can't escape it. - * The trailing-slash comparison rejects sibling-prefix paths like - * `../brain-other/x.md` that a bare startsWith(root) would accept. * Returns the canonical absolute path, or null if the path escapes (or the * root itself does not exist). + * + * core's row of the shared resolver (`@schlessera/brain-common/internal/safe-path`, + * #2506): synchronous, `null` for every refusal, an absolute path accepted + * when it lies inside the root, `..` accepted while the result stays inside, + * a dangling link followed to a target that must stay inside, and only the + * final path checked, not each component on the way. */ export function safeResolve(root: string, relPath: string): string | null { - // A NUL byte would make the later fs call throw ERR_INVALID_ARG_VALUE — - // reject it as a containment failure, not a deferred TypeError. - if (relPath.includes("\0")) return null; - - let rootReal: string; - try { - rootReal = realpathSync(resolve(root)); - } catch { - return null; - } - // Separator-aware containment check (backslash paths on Windows). - const contains = (p: string) => p === rootReal || p.startsWith(rootReal + sep); - const fullPath = resolve(rootReal, relPath); - if (!contains(fullPath)) return null; - // Canonicalize through symlinks. When the target (or a stretch of its - // parents) doesn't exist yet, canonicalize the nearest EXISTING ancestor and - // re-append the missing tail — a purely lexical fallback would let a - // symlinked parent directory smuggle a to-be-created file outside the root. - let existing = fullPath; - const tail: string[] = []; - // Symlink-hop budget: a dangling-link CYCLE (a→b, b→a) throws in realpath - // but resolves link-by-link here — bound it like the kernel does. - let hops = 0; - for (;;) { - let real: string; - try { - real = realpathSync(existing); - } catch { - // realpath failed: either the entry is genuinely absent, or it is a - // DANGLING symlink (exists, target missing). The two are different - // security cases — a write through a dangling link is created AT THE - // LINK TARGET, so it must be resolved and re-checked, never treated as - // "doesn't exist yet". - let linkTarget: string | null = null; - try { - if (lstatSync(existing).isSymbolicLink()) { - linkTarget = readlinkSync(existing); - } - } catch { - // lstat failed too → the entry really doesn't exist. - } - if (linkTarget !== null) { - if (++hops > 40) return null; - const resolvedTarget = isAbsolute(linkTarget) - ? resolve(linkTarget) - : resolve(dirname(existing), linkTarget); - // Re-enter containment checking with the link's target substituted in. - const rejoined = tail.length > 0 ? join(resolvedTarget, ...tail) : resolvedTarget; - if (!contains(rejoined)) return null; - existing = rejoined; - tail.length = 0; - continue; - } - tail.unshift(basename(existing)); - const parent = dirname(existing); - // The loop always terminates at rootReal (it exists), but guard the - // filesystem root anyway. - if (parent === existing) return null; - existing = parent; - continue; - } - const candidate = tail.length > 0 ? join(real, ...tail) : real; - if (!contains(candidate)) return null; - return candidate; - } + const contained = resolveContainedSync(root, relPath, CORE_CONTAINMENT); + return contained.ok ? contained.canonical : null; } /** diff --git a/packages/core/src/lib/scratch.ts b/packages/core/src/lib/scratch.ts index 3fff9f8cfc..02cd405c1b 100644 --- a/packages/core/src/lib/scratch.ts +++ b/packages/core/src/lib/scratch.ts @@ -46,10 +46,14 @@ import { import type { Stats } from "fs"; import { tmpdir } from "os"; import { basename, dirname, join, relative, resolve, sep } from "path"; +import { BRAIN_SCRATCH_DIR } from "@schlessera/brain-common/internal/worker-areas"; import { modeOf, WriteRefusedError, writeExclusive, writeFileSafely } from "./safe-path.js"; -/** Repo-relative scratch directory. Every mechanism that needs it reads this. */ -export const SCRATCH_DIR = ".brain/scratch"; +/** + * Repo-relative scratch directory. Every mechanism that needs it reads this; + * the value is the one the SDK and server share (`BRAIN_SCRATCH_DIR`, #2506). + */ +export const SCRATCH_DIR = BRAIN_SCRATCH_DIR; /** Files older than this are pruned. */ export const SCRATCH_TTL_MS = 7 * 24 * 60 * 60 * 1000; diff --git a/packages/ui-sdk/src/server/bridge-tools/mask.ts b/packages/ui-sdk/src/server/bridge-tools/mask.ts index 3f6633ba21..d76c82eef8 100644 --- a/packages/ui-sdk/src/server/bridge-tools/mask.ts +++ b/packages/ui-sdk/src/server/bridge-tools/mask.ts @@ -8,6 +8,8 @@ import type { RequestImageMaskInput, } from "../../tool-contracts/index.js"; import type { BackendBridge } from "../backend.js"; +import { isWithin } from "@schlessera/brain-common/internal/safe-path"; +import { BRAIN_SCRATCH_DIR } from "@schlessera/brain-common/internal/worker-areas"; import { resolveInRepo } from "./resolve-in-repo.js"; import { brainGitSteps } from "../maintenance-worker.js"; import { runWorkerStepsAsync, runWorkerStepsSync, type WorkerSteps } from "../worker-steps.js"; @@ -117,13 +119,15 @@ export async function handleRequestImageMask( * excluded by git. The write itself goes to a temporary sibling and is * renamed onto its name, and the host's prune runs after it. * - * Kept in lockstep with `packages/core/src/lib/scratch.ts` (`SCRATCH_DIR`, - * `scratchIgnored`, `scratchDir`, `writeScratchFile`): the SDK ports the rule, - * as it does for `resolveInRepo`, instead of depending on `@schlessera/brain`. + * The directory is the shared `BRAIN_SCRATCH_DIR` (#2506). The rules are + * core's (`packages/core/src/lib/scratch.ts`: `scratchIgnored`, `scratchDir`, + * `writeScratchFile`), applied here through descriptors and the maintenance + * worker, since the SDK does not depend on `@schlessera/brain`. */ -const SCRATCH_DIR = ".brain/scratch"; +const SCRATCH_DIR = BRAIN_SCRATCH_DIR; -export const under = (dir: string, path: string) => path === dir || path.startsWith(dir + sep); +/** Whether `path` is `dir` or below it, by the platform separator. */ +export const under = (dir: string, path: string) => isWithin(dir, path, { separator: sep }); function isSymlink(path: string): boolean { try { diff --git a/packages/ui-sdk/src/server/bridge-tools/resolve-in-repo.ts b/packages/ui-sdk/src/server/bridge-tools/resolve-in-repo.ts index ab97c4f404..7b2da28def 100644 --- a/packages/ui-sdk/src/server/bridge-tools/resolve-in-repo.ts +++ b/packages/ui-sdk/src/server/bridge-tools/resolve-in-repo.ts @@ -1,64 +1,18 @@ -import { lstatSync, realpathSync, readlinkSync } from "fs"; -import { basename, dirname, isAbsolute, join, resolve, sep } from "path"; +import { resolveContainedSync, type ContainmentPolicy } from "@schlessera/brain-common/internal/safe-path"; +import { isAbsolute } from "path"; + +const SDK_CONTAINMENT: ContainmentPolicy = { missingRoot: "refuse", danglingLinks: "follow", components: "final" }; /** * Resolve a repo-relative path without allowing a symlink to escape the repo. * - * Keep these semantics in lockstep with the reference implementation at - * `packages/core/src/lib/safe-path.ts` (`safeResolve`). The SDK deliberately - * ports that implementation instead of depending on `@schlessera/brain`. + * The SDK's row of the shared resolver (`@schlessera/brain-common/internal/safe-path`, + * #2506): core's (`safeResolve`), except that an absolute path is refused + * even when it lies inside the root. Synchronous, `null` for every refusal, + * the canonical path on success. */ export function resolveInRepo(root: string, relPath: string): string | null { - if (relPath.includes("\0") || isAbsolute(relPath)) return null; - - let rootReal: string; - try { - rootReal = realpathSync(resolve(root)); - } catch { - return null; - } - - const contains = (path: string) => - path === rootReal || path.startsWith(rootReal + sep); - const fullPath = resolve(rootReal, relPath); - if (!contains(fullPath)) return null; - - let existing = fullPath; - const tail: string[] = []; - let hops = 0; - for (;;) { - let real: string; - try { - real = realpathSync(existing); - } catch { - let linkTarget: string | null = null; - try { - if (lstatSync(existing).isSymbolicLink()) { - linkTarget = readlinkSync(existing); - } - } catch { - // lstat failed too: this entry is genuinely absent. - } - if (linkTarget !== null) { - if (++hops > 40) return null; - const resolvedTarget = isAbsolute(linkTarget) - ? resolve(linkTarget) - : resolve(dirname(existing), linkTarget); - const rejoined = - tail.length > 0 ? join(resolvedTarget, ...tail) : resolvedTarget; - if (!contains(rejoined)) return null; - existing = rejoined; - tail.length = 0; - continue; - } - tail.unshift(basename(existing)); - const parent = dirname(existing); - if (parent === existing) return null; - existing = parent; - continue; - } - const candidate = tail.length > 0 ? join(real, ...tail) : real; - if (!contains(candidate)) return null; - return candidate; - } + if (isAbsolute(relPath)) return null; + const contained = resolveContainedSync(root, relPath, SDK_CONTAINMENT); + return contained.ok ? contained.canonical : null; } diff --git a/packages/ui-sdk/src/server/maintenance-env-masks.ts b/packages/ui-sdk/src/server/maintenance-env-masks.ts index 75f6c9d6bb..23c43be0ea 100644 --- a/packages/ui-sdk/src/server/maintenance-env-masks.ts +++ b/packages/ui-sdk/src/server/maintenance-env-masks.ts @@ -1,4 +1,5 @@ /** One alias resolver, driven synchronously by the host or asynchronously by its owned stage. */ +import { isWithin } from "@schlessera/brain-common/internal/safe-path"; import { lstatSync, readdirSync, readlinkSync } from "node:fs"; import { dirname, isAbsolute } from "node:path"; import { isEnvName } from "./protected-paths.js"; @@ -6,7 +7,7 @@ import { isEnvName } from "./protected-paths.js"; export type EnvMaskMetadata = { kind: "directory" | "file" | "symlink" | "other"; target?: string }; export type EnvMaskQuery = { operation: "list" | "stat"; path: string }; type Reply = string[] | EnvMaskMetadata | undefined; -export const within = (dir: string, path: string) => path === dir || path.startsWith(`${dir}/`); +export const within = (dir: string, path: string) => isWithin(dir, path); /** No contents are read. Queries preserve the worker's names through held input aliases. */ export function* maintenanceEnvMaskQueries(source: string, brain: string, diff --git a/packages/ui-sdk/src/server/native-reference-pool.ts b/packages/ui-sdk/src/server/native-reference-pool.ts index fc37df1d02..ff61e92cf6 100644 --- a/packages/ui-sdk/src/server/native-reference-pool.ts +++ b/packages/ui-sdk/src/server/native-reference-pool.ts @@ -15,6 +15,7 @@ * allocate before work starts. Measured use replaces that reservation as it * materializes; sealing converts the rest to measured allocation. */ +import { isWithin } from "@schlessera/brain-common/internal/safe-path"; import { constants, closeSync, existsSync, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, readlinkSync, renameSync, rmdirSync, statSync, symlinkSync, unlinkSync, writeFileSync, ftruncateSync, chownSync, chmodSync, realpathSync } from "node:fs"; import { randomUUID } from "node:crypto"; @@ -58,7 +59,8 @@ export interface NativeReferencePoolConfig { export type QualifiedReferencePoolConfig = Required> & { headroomLedgerPath?: string }; const fixedPath = (path: unknown) => typeof path === "string" && isAbsolute(path) && !path.includes("\0") && !path.split("/").includes("..") && path.length > 1; -export const inside = (child: string, parent: string) => child === parent || child.startsWith(parent.endsWith("/") ? parent : parent + "/"); +/** Child first: `inside(a, b)` reads as "a is inside b". */ +export const inside = (child: string, parent: string) => isWithin(parent, child, { trailingSeparator: "boundary" }); const page = (value: unknown): value is number => Number.isSafeInteger(value) && (value as number) > 0 && (value as number) % 4096 === 0; export function validateNativeReferencePoolConfig(pool: NativeReferencePoolConfig, store: { storePath: string; fsid: string; socketPath: string }): QualifiedReferencePoolConfig { diff --git a/packages/ui-sdk/src/server/worker-file-observer.ts b/packages/ui-sdk/src/server/worker-file-observer.ts index 44010cce9d..f2f3575fb4 100644 --- a/packages/ui-sdk/src/server/worker-file-observer.ts +++ b/packages/ui-sdk/src/server/worker-file-observer.ts @@ -1,4 +1,5 @@ /** Read the actual host-owned mount sources; never evaluates repository code. */ +import { isWithin } from "@schlessera/brain-common/internal/safe-path"; import { createHash } from "node:crypto"; import { closeSync, constants, fstatSync, openSync, readlinkSync } from "node:fs"; import { isAbsolute, relative, resolve } from "node:path"; @@ -6,7 +7,8 @@ import { nativeFileVersionFromFd, type NativeFileVersion } from "./native-file-v export interface ObservedWorkerFile { key: string; version: NativeFileVersion } interface Source { worker: string; host: string; rel: string } -export const within = (path: string, root: string) => path === root || path.startsWith(root + "/"); +/** Path first: it reads as "this path is within that root" at each call site. */ +export const within = (path: string, root: string) => isWithin(root, path); const EMPTY: NativeFileVersion = { status: "known", hash: createHash("sha256").update("").digest("hex") }; /** Sources come only from the launcher's resolved mounts, and live only until worker exit. */ diff --git a/packages/ui-sdk/src/server/worker-launcher.ts b/packages/ui-sdk/src/server/worker-launcher.ts index 00460fa02c..6f1a5e77a7 100644 --- a/packages/ui-sdk/src/server/worker-launcher.ts +++ b/packages/ui-sdk/src/server/worker-launcher.ts @@ -1,3 +1,4 @@ +import { isWithin } from "@schlessera/brain-common/internal/safe-path"; import { maintenanceEnvMasks } from "./maintenance-env-masks.js"; import { registerWorkerRtk } from "./worker-rtk.js"; import { createWorkerStatusPipe, createWorkerStatusPipeSteps } from "./worker-status.js"; @@ -725,7 +726,7 @@ export function workerCommand(input: WorkerLaunch): string[] { } /** Whether `path` is `dir` or lies below it. */ -export const within = (dir: string, path: string) => path === dir || path.startsWith(`${dir}/`); +export const within = (dir: string, path: string) => isWithin(dir, path); /** Resolve aliases even when the final installed entry is not present yet. */ function runtimeCanonicalName(requested: string): string { diff --git a/packages/ui-sdk/src/server/worker-rtk.ts b/packages/ui-sdk/src/server/worker-rtk.ts index c9e3f31f95..4daf8220b8 100644 --- a/packages/ui-sdk/src/server/worker-rtk.ts +++ b/packages/ui-sdk/src/server/worker-rtk.ts @@ -1,4 +1,5 @@ /** Optional installed RTK evidence belongs to one kernel-observed live worker. */ +import { isWithin } from "@schlessera/brain-common/internal/safe-path"; import { accessSync, constants, readFileSync, realpathSync, statSync } from "node:fs"; import { dirname, isAbsolute, resolve } from "node:path"; import { rewriteInstalledRtk } from "./rtk.js"; @@ -18,7 +19,7 @@ export function registerWorkerRtk(worker: LaunchedWorker, pid: number, input: Wo void worker.exited.then(() => { view.alive = false; }, () => { view.alive = false; }); } catch { /* An unreadable worker cannot authorize an optional rewrite. */ } } -export function within(root: string, path: string): boolean { return path === root || path.startsWith(root + "/"); } +export function within(root: string, path: string): boolean { return isWithin(root, path); } /** ELF64 native static executables, including dependency-free static PIE. */ export function isStaticNativeElf(path: string): boolean { const bytes = readFileSync(path); diff --git a/packages/ui-sdk/src/server/worker-turn-temp.ts b/packages/ui-sdk/src/server/worker-turn-temp.ts index 868a94b0cc..abde5d03a8 100644 --- a/packages/ui-sdk/src/server/worker-turn-temp.ts +++ b/packages/ui-sdk/src/server/worker-turn-temp.ts @@ -20,6 +20,7 @@ * while it is copied. The destination is opened the same way below * `.brain/scratch/turns//`. */ +import { isWithin } from "@schlessera/brain-common/internal/safe-path"; import { hasIdentityReadRoot, prepareRecoveredWorkerFile, recoveredWorkerFile } from "./worker-identity-reader.js"; import { closeSync, constants, fstatSync, lstatSync, mkdirSync, openSync, readdirSync, readSync, realpathSync, rmdirSync, statfsSync, unlinkSync, writeSync } from "node:fs"; @@ -45,7 +46,7 @@ const LINK_MAX_CHARS = 2000; const COPY_CHUNK = 1024 * 1024; /** Whether `path` is `dir` or lies below it. */ -export const within = (dir: string, path: string) => path === dir || path.startsWith(dir.endsWith("/") ? dir : `${dir}/`); +export const within = (dir: string, path: string) => isWithin(dir, path, { trailingSeparator: "boundary" }); /** * A server-side path that opens the directory a held descriptor names. diff --git a/packages/ui-server/src/brain/host-boundary.ts b/packages/ui-server/src/brain/host-boundary.ts index 74788e6784..7163beafa4 100644 --- a/packages/ui-server/src/brain/host-boundary.ts +++ b/packages/ui-server/src/brain/host-boundary.ts @@ -21,6 +21,7 @@ * only ever written through the server's own routes, as before 0.42. That * legacy host path is refused while a provider folder policy is active (#2284). */ +import { isWithin } from "@schlessera/brain-common/internal/safe-path"; import { brainWorkerPath } from "@schlessera/brain-common/internal/worker-areas"; import { existsSync, realpathSync } from "node:fs"; import { isAbsolute, join, resolve } from "node:path"; @@ -172,7 +173,7 @@ const TURN_EGRESS_INACTIVE = "This host has no managed native storage, so govern /** Whether the brain CLI's paid providers are relayed (#1673): where provider keys live on this host. */ const PROVIDERS_RELAYED = "The brain CLI's Gemini, Anthropic and OpenAI image providers go through a metered host relay, in turn and maintenance workers alike: the host holds their keys, records each request's usage and counts it toward the budgets."; const PROVIDERS_NOT_RELAYED = "The brain CLI's providers are not relayed here: governed and strict turn workers report them unavailable, and maintenance workers still receive the provider keys, so their spend is unmetered."; -export const within = (dir: string, path: string) => path === dir || path.startsWith(`${dir}/`); +export const within = (dir: string, path: string) => isWithin(dir, path); const real = (path: string) => { try { return realpathSync(path); } catch { return resolve(path); } }; /** Whether `governed` can run for this server and brain, and if not, why. */ diff --git a/packages/ui-server/src/brain/operational-state.ts b/packages/ui-server/src/brain/operational-state.ts index 0c008b4c56..6ca73fc2a8 100644 --- a/packages/ui-server/src/brain/operational-state.ts +++ b/packages/ui-server/src/brain/operational-state.ts @@ -2,6 +2,7 @@ import { closeSync, constants, fstatSync, lstatSync, openSync, readdirSync, readlinkSync } from "node:fs"; import { tmpdir } from "node:os"; import { dirname, isAbsolute, join, resolve } from "node:path"; +import { isWithin } from "@schlessera/brain-common/internal/safe-path"; import { mountPointsUnder, workerIdentityHelper } from "@schlessera/brain-ui-sdk/internal"; import type { GovernedUnavailableReason } from "@schlessera/brain-ui-sdk/protocol"; import { journalDatabasePath } from "../db/journal-database.js"; @@ -29,7 +30,12 @@ function canonical(path: string, links = 0): string { } return current; } -export const within = (root: string, path: string) => root === "/" || path === root || path.startsWith(`${root}/`); +/** + * A deny check: a brain at `/` holds every path, so all state counts as + * inside it. Every other root ends at `/` with nothing appended to a + * trailing one, as `canonical` never yields one. + */ +export const within = (root: string, path: string) => root === "/" || isWithin(root, path); /** An outside name does not move an inode out of the brain if another name or a bind mount remains there. */ function hasBrainAlias(brain: string, path: string, descendants = false): boolean { diff --git a/packages/ui-server/src/brain/sync-mirror.ts b/packages/ui-server/src/brain/sync-mirror.ts index 96fe70df66..9cdab8545c 100644 --- a/packages/ui-server/src/brain/sync-mirror.ts +++ b/packages/ui-server/src/brain/sync-mirror.ts @@ -8,6 +8,7 @@ import { createHash } from "node:crypto"; import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, realpathSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { dirname, join, resolve } from "node:path"; +import { isWithin } from "@schlessera/brain-common/internal/safe-path"; import { runMaintenanceWorker, prepareNativeWorkerStartupView, type MaintenanceCommand } from "@schlessera/brain-ui-sdk/internal"; import { createKeyedLock } from "@schlessera/brain-ui-sdk/server"; import { prepareMaintenanceOutput } from "./maintenance-output.js"; @@ -26,7 +27,7 @@ const MIRROR_CONFIG = `[core] \tfsckObjects = true `; const CREDENTIAL_HELPER = '!f() { printf "username=x-access-token\\npassword=%s\\n" "$BRAIN_SYNC_TOKEN"; }; f'; -export const within = (root: string, path: string) => path === root || path.startsWith(`${root}/`); +export const within = (root: string, path: string) => isWithin(root, path); const mirrorLocks = createKeyedLock(); /** One host-private mirror per brain/database; standalone clients get private temporary state. */ diff --git a/packages/ui-server/src/core-queries.ts b/packages/ui-server/src/core-queries.ts index 16005fce91..edd2c4cff1 100644 --- a/packages/ui-server/src/core-queries.ts +++ b/packages/ui-server/src/core-queries.ts @@ -20,8 +20,9 @@ * fallback. Native connections stay inside core, opened and closed per call. */ import type { Logger } from "@opentelemetry/api-logs"; +import { isWithin } from "@schlessera/brain-common/internal/safe-path"; import { createRequire } from "module"; -import { dirname, relative, isAbsolute } from "path"; +import { dirname, sep } from "path"; import type { GraphMaintenanceResponse, GraphMetaResponse, @@ -136,9 +137,9 @@ type Resolved = | { ok: true; entry: Record } | { ok: false; reason: CoreQueriesUnavailableReason; version?: string }; +/** Strictly below `dir`, both resolved first: the package directory itself is not its entry. */ export function inside(dir: string, file: string): boolean { - const rel = relative(dir, file); - return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel); + return isWithin(dir, file, { includeRoot: false, resolvePaths: true, separator: sep, trailingSeparator: "boundary" }); } function resolveEntry(loader: CoreModuleLoader): Resolved { diff --git a/packages/ui-server/src/files/walker.ts b/packages/ui-server/src/files/walker.ts index fc14387b41..3363b7252c 100644 --- a/packages/ui-server/src/files/walker.ts +++ b/packages/ui-server/src/files/walker.ts @@ -1,7 +1,9 @@ import { closeSync, constants, fstatSync, openSync, readSync, realpathSync } from "node:fs"; -import { lstat, readdir, readFile, stat, realpath } from "node:fs/promises"; +import { readdir, readFile, stat, realpath } from "node:fs/promises"; import { join, relative, resolve, sep, posix, dirname } from "node:path"; import ignore, { type Ignore } from "ignore"; +import { isWithin, resolveContained, type ContainmentPolicy } from "@schlessera/brain-common/internal/safe-path"; +import { BRAIN_SCRATCH_DIR, BRAIN_WORKSPACES_DIR } from "@schlessera/brain-common/internal/worker-areas"; import type { FileEntry, FileContentKind } from "@schlessera/brain-ui-sdk/protocol"; import { FILE_SIZE_CAP_BYTES } from "@schlessera/brain-ui-sdk/protocol"; @@ -25,15 +27,6 @@ const HARD_EXCLUDE_FILE_NAMES = new Set( ].map((n) => n.toLowerCase()) ); -const UNRESOLVABLE_PATH_CODES = new Set([ - "ENOENT", - "ENOTDIR", - "ENAMETOOLONG", - "ELOOP", - "EACCES", - "EPERM", -]); - export class PathEscapeError extends Error { constructor(rel: string) { super(`path_escape: ${rel}`); @@ -55,93 +48,59 @@ export class TooLargeError extends Error { } } +const [BRAIN_AREA, SCRATCH_NAME] = BRAIN_SCRATCH_DIR.split("/"); + /** - * Whether a normalized repo-relative path names `.brain`, the scratch area - * (core's `SCRATCH_DIR`, `.brain/scratch`) or something in it. ui-server does - * not depend on core (tests/allowed-edges.ts). + * Whether a normalized repo-relative path names `.brain` itself, the scratch + * area (`BRAIN_SCRATCH_DIR`, `.brain/scratch`) or something in it. Wider than + * the scratch area on purpose: `.brain` is included, so `safeResolve` follows + * no link anywhere on a path into scratch and the walker lists no link there. */ export function isScratchPath(rel: string): boolean { const parts = rel.split("/").filter((part) => part && part !== "."); - return parts[0] === ".brain" && (parts.length === 1 || parts[1] === "scratch"); + return parts[0] === BRAIN_AREA && (parts.length === 1 || parts[1] === SCRATCH_NAME); } +/** + * ui-server's row of the shared resolver (`@schlessera/brain-common/internal/safe-path`, + * #2506): every existing component, not only the final path, stays inside; + * a dangling link is refused wherever it points; and a root that does not + * exist yet contains the lexical path (the server resolves into a brain it + * may create). + */ +const SERVER_CONTAINMENT = { missingRoot: "lexical", danglingLinks: "refuse", components: "every" } as const satisfies ContainmentPolicy; + /** * Resolve a repo-relative path to an absolute path, rejecting any escape * outside the brain root (including via symlinks). + * + * The request is refused before resolving when it is absolute, holds a NUL, + * `:` or `\\` in a segment, or a `..` segment anywhere, even one whose result + * would stay inside. The answer is the lexical path under the root's + * realpath, links as written, not the canonical one. A refusal throws + * `PathEscapeError`; any other filesystem failure throws as it is. */ export async function safeResolve(rel: string, root: string): Promise { if (typeof rel !== "string") throw new PathEscapeError(String(rel)); const requestSegments = rel.split("/"); - // Reject absolute paths, null bytes, and Windows path syntax before resolving. if ( rel.startsWith("/") || rel.startsWith("\\") || rel.includes("\0") || - requestSegments.some((segment) => segment.includes(":") || segment.includes("\\")) + requestSegments.some((segment) => segment === ".." || segment.includes(":") || segment.includes("\\")) ) { throw new PathEscapeError(rel); } - // Normalize separators; reject ".." segments anywhere - const normalized = rel.replace(/\\/g, "/"); - for (const seg of normalized.split("/")) { - if (seg === "..") throw new PathEscapeError(rel); - } - const lexicalRoot = resolve(root); - let absRoot: string; - try { - absRoot = await realpath(lexicalRoot); - } catch (err) { - if ((err as NodeJS.ErrnoException).code !== "ENOENT") throw err; - absRoot = lexicalRoot; - } - const abs = resolve(absRoot, normalized); - if (abs !== absRoot && !abs.startsWith(absRoot + sep)) { - throw new PathEscapeError(rel); - } - // Canonicalize every existing component. Stopping at the first genuinely - // missing component permits callers to create a new path, while lstat - // distinguishes that case from a dangling symlink, which must fail closed. - let candidate = absRoot; - const candidates = [candidate]; - for (const segment of relative(absRoot, abs).split(sep)) { - if (!segment || segment === ".") continue; - candidate = join(candidate, segment); - candidates.push(candidate); - } - // The scratch area is agent-writable in a hosted worker (#1626), so nothing // under `.brain/` is followed through a link: a scratch symlink cannot make // the server serve, preview or list another file under a scratch path. - const scratchRequest = isScratchPath(normalized); - for (const existing of candidates) { - let entry; - try { - entry = await lstat(existing); - } catch (err) { - const code = (err as NodeJS.ErrnoException).code; - if (code && UNRESOLVABLE_PATH_CODES.has(code)) break; - throw err; - } - if (scratchRequest && entry.isSymbolicLink() && existing.startsWith(join(absRoot, ".brain"))) { - throw new PathEscapeError(rel); - } - - let real: string; - try { - real = await realpath(existing); - } catch (err) { - const code = (err as NodeJS.ErrnoException).code; - if (code === "ENOENT" || code === "ENOTDIR") { - throw new PathEscapeError(rel); - } - if (code && UNRESOLVABLE_PATH_CODES.has(code)) break; - throw err; - } - if (real !== absRoot && !real.startsWith(absRoot + sep)) { - throw new PathEscapeError(rel); - } - } - return abs; + const policy: ContainmentPolicy = isScratchPath(rel) + ? { ...SERVER_CONTAINMENT, refuseLinkAt: (path, absRoot) => isWithin(join(absRoot, BRAIN_AREA!), path, { separator: sep }) } + : SERVER_CONTAINMENT; + const result = await resolveContained(root, rel, policy); + if (result.ok) return result.lexical; + if (result.reason === "error") throw result.error; + throw new PathEscapeError(rel); } /** @@ -197,7 +156,7 @@ async function canonicalRoot(root: string): Promise { } /** Directories a hosted agent can write (#1626): `.brain/scratch` and `workspaces`. */ -const AGENT_WRITABLE = [".brain/scratch", "workspaces"]; +const AGENT_WRITABLE = [BRAIN_SCRATCH_DIR, BRAIN_WORKSPACES_DIR]; /** * When the requested path or the file it resolves to lies in an @@ -210,14 +169,11 @@ const AGENT_WRITABLE = [".brain/scratch", "workspaces"]; async function areaSnapshot(rel: string, abs: string, root: string) { if (process.platform !== "linux") return null; const absRoot = await canonicalRoot(root); - const inArea = (path: string) => AGENT_WRITABLE.some((area) => { - const dir = join(absRoot, area); - return path === dir || path.startsWith(dir + sep); - }); + const inArea = (path: string) => AGENT_WRITABLE.some((area) => isWithin(join(absRoot, area), path, { separator: sep })); let real: string; try { real = await realpath(abs); } catch { throw new NotFoundError(rel); } if (!inArea(abs) && !inArea(real) && !isScratchPath(rel)) return null; - if (real !== absRoot && !real.startsWith(absRoot + sep)) throw new PathEscapeError(rel); + if (!isWithin(absRoot, real, { separator: sep })) throw new PathEscapeError(rel); return { real, ...readAnchoredSnapshot(real, absRoot, rel)! }; } diff --git a/packages/ui-server/src/storage/process.ts b/packages/ui-server/src/storage/process.ts index 53c5dd6a90..4dd0dde539 100644 --- a/packages/ui-server/src/storage/process.ts +++ b/packages/ui-server/src/storage/process.ts @@ -1,9 +1,11 @@ import { processStart } from "../brain/writer-gate.js"; +import { isWithin } from "@schlessera/brain-common/internal/safe-path"; import { fileURLToPath } from "node:url"; -import { dirname, relative, isAbsolute } from "node:path"; +import { dirname, sep } from "node:path"; import { realpathSync, readFileSync } from "node:fs"; import type { MetadataRoot, MetadataResult } from "./metadata.js"; -export const inside = (root: string, path: string) => { const rel = relative(root, path); return !rel || (!isAbsolute(rel) && rel !== ".." && !rel.startsWith("../")); }; +/** `root` or below it, both resolved first. */ +export const inside = (root: string, path: string) => isWithin(root, path, { resolvePaths: true, separator: sep, trailingSeparator: "boundary" }); /** Verify the installed public reader, never code or executables from content. */ export function coreReader(brainPath: string, subpath: "storage" | "queries"): string { const manifestPath = realpathSync(fileURLToPath(import.meta.resolve("@schlessera/brain/package.json"))); diff --git a/packages/ui-server/tests/containment-rows.test.ts b/packages/ui-server/tests/containment-rows.test.ts index d53fa9703d..6381f63cf5 100644 --- a/packages/ui-server/tests/containment-rows.test.ts +++ b/packages/ui-server/tests/containment-rows.test.ts @@ -86,9 +86,11 @@ describe("ui-server safeResolve(rel, root): its resolver row", () => { ["dangling-in", "refused"], ["dangling-in/x", "refused"], ["dangling-out", "refused"], - // A symlink cycle is accepted: the path resolves nowhere. - ["cycle-a", "brain/cycle-a"], - ["cycle-a/x", "brain/cycle-a/x"], + // A symlink cycle is refused (#2506). The copy ui-server carried accepted + // it, answering a path that resolves nowhere; core and the SDK refused it, + // and the shared resolver keeps that stricter answer. + ["cycle-a", "refused"], + ["cycle-a/x", "refused"], // Every existing component must stay inside: out and back is refused. ["bounce/back/a.md", "refused"], // `.brain` is a scratch request (`isScratchPath`): no link under it is followed. @@ -148,8 +150,10 @@ const PREDICATE_CASES: [string, string][] = [ const LITERAL_SLASH = "T T - - - T - - - T T T T"; const rows: [string, (root: string, path: string) => boolean, string][] = [ - // relative()-based: both sides resolved; the root itself is excluded. - ["core-queries inside(dir, file)", coreQueriesInside, "- T - - T - T T - - - - T"], + // relative()-based: both sides resolved; the root itself is excluded. A + // child named `..c` is inside (#2506): the copy refused it, reading any + // relative path that starts with `..` as an escape. + ["core-queries inside(dir, file)", coreQueriesInside, "- T - - T - T T - - - T T"], // relative()-based: both sides resolved; the root itself is included. ["storage/process inside(root, path)", processInside, "T T - - T T T T T T - T T"], // Literal, except that root `/` holds everything. diff --git a/tests/allowed-edges.ts b/tests/allowed-edges.ts index 5b0213d4ed..5d8789d823 100644 --- a/tests/allowed-edges.ts +++ b/tests/allowed-edges.ts @@ -26,8 +26,9 @@ export const ALLOWED_EDGES: Record = { // byte-identical copies each package carried, plus the worker write-area // rules core and the ui-sdk both state (#1693). It depends on no internal // package. #1744 also shares data-only governance parsing between core - // and server, preserving the server’s optional core peer. Further helpers - // still need their own issue. + // and server, preserving the server’s optional core peer. #2493 adds the + // Claude subscription billing guard and #2506 symlink-safe path + // containment, each with its own issue. Further helpers still need theirs. "@schlessera/brain-common": { dependencies: [], optionalPeers: [] }, // core owns the render template (the CLI's `brain render` uses it); the // Puppeteer renderer is heavyweight and optional, so it may never be hard. From 6124dc852a7c88fa6b19212abe35b02e8affa9e7 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 3 Nov 2026 02:06:47 +0000 Subject: [PATCH 3/5] refactor(ui-server): read the scratch and workspaces names from worker-areas (#2506) Two more literal copies of the scratch directory name, in the scratch ignore query and the storage roots, now read BRAIN_SCRATCH_DIR, and the storage roots read BRAIN_WORKSPACES_DIR. Refs #2506 Co-Authored-By: Claude Opus 5.5 --- docs/decisions/governed-writable-workers.md | 2 +- packages/ui-server/src/brain/scratch-mask-query.ts | 3 ++- packages/ui-server/src/storage/collect.ts | 3 ++- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index 1880faa293..00f6649886 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -505,7 +505,7 @@ before application-lock admission, acquires its own complete native checkpoint asynchronously and runs a credential-free, read-only Git query. It releases that input after the worker drains, without creating or publishing a writable stage (`createScratchIgnoreQuery`, -`packages/ui-server/src/brain/scratch-mask-query.ts:7-43`). Exit 1 means the +`packages/ui-server/src/brain/scratch-mask-query.ts:8-44`). Exit 1 means the directory is not ignored. Launch failure, another exit or timeout means the rule could not be verified; the mask remains refused without forwarding worker stderr or claiming that the ignore file needs repair (`assertScratchMaskAsync`, diff --git a/packages/ui-server/src/brain/scratch-mask-query.ts b/packages/ui-server/src/brain/scratch-mask-query.ts index 242563ae9a..1fa9d6c268 100644 --- a/packages/ui-server/src/brain/scratch-mask-query.ts +++ b/packages/ui-server/src/brain/scratch-mask-query.ts @@ -1,6 +1,7 @@ /** One read-only Git query; no stage publication or repository execution on the host. */ import { existsSync, lstatSync, realpathSync } from "node:fs"; import { dirname, join } from "node:path"; +import { BRAIN_SCRATCH_DIR } from "@schlessera/brain-common/internal/worker-areas"; import { prepareNativeWorkerStartupView, runMaintenanceWorker, type MaintenanceHost } from "@schlessera/brain-ui-sdk/internal"; import type { KeyedLock } from "@schlessera/brain-ui-sdk/server"; @@ -27,7 +28,7 @@ export function createScratchIgnoreQuery(input: { if (dir === "/") break; } const safe = ["-c", `safe.directory=${brain}`, ...(parent ? ["-c", `safe.directory=${parent}`] : [])]; - const args = [...safe, "check-ignore", "-q", "--no-index", "--", ".brain/scratch"]; + const args = [...safe, "check-ignore", "-q", "--no-index", "--", BRAIN_SCRATCH_DIR]; const command = existsSync(join(brain, ".git")) || parent ? [git, ...args] : ["/bin/sh", "-c", 'r=/tmp/brain-mask-empty-repository; "$0" init -q --bare "$r" >/dev/null 2>&1 && exec "$0" --git-dir="$r" --work-tree=. "$@"', git, ...args]; const view = await prepareNativeWorkerStartupView(brain, input.nativeManager, signal); diff --git a/packages/ui-server/src/storage/collect.ts b/packages/ui-server/src/storage/collect.ts index f08961bd3d..8ed8b11286 100644 --- a/packages/ui-server/src/storage/collect.ts +++ b/packages/ui-server/src/storage/collect.ts @@ -1,6 +1,7 @@ import { createHmac } from "node:crypto"; import { basename, dirname, resolve } from "node:path"; import { INDEX_DIR } from "@schlessera/brain-common/internal/index-location"; +import { BRAIN_SCRATCH_DIR, BRAIN_WORKSPACES_DIR } from "@schlessera/brain-common/internal/worker-areas"; import { z } from "zod"; import type { StorageFileEntry, StorageRoot, StorageSnapshot, StorageOwner, StorageBytes } from "@schlessera/brain-ui-sdk/protocol"; import { SHARE_STAGING_DIR } from "@schlessera/brain-ui-sdk/protocol"; @@ -76,7 +77,7 @@ export async function collectStorage(options: StorageCollectOptions, id: string, } if (view.id === brain.id) { for (const [prefix, label, category, owner] of [ - [".git", "Git metadata", "git", "brain"], [SHARE_STAGING_DIR, "Upload staging", "staging", "app"], [".brain/scratch", "Scratch", "scratch", "brain"], ["workspaces", "Workspaces", "workspace", "brain"], + [".git", "Git metadata", "git", "brain"], [SHARE_STAGING_DIR, "Upload staging", "staging", "app"], [BRAIN_SCRATCH_DIR, "Scratch", "scratch", "brain"], [BRAIN_WORKSPACES_DIR, "Workspaces", "workspace", "brain"], ] as const) if (path === prefix || path.startsWith(`${prefix}/`)) { view = root(prefix, label, category, owner); sources.set(view.id, { root: view, path: resolve(options.brainPath, prefix), recursive: false, optional: true }); path = path.slice(prefix.length).replace(/^\//, ""); break; } if (view.id === brain.id && (path === INDEX_DIR || path.startsWith(`${INDEX_DIR}/`))) { view = root("index", "Content index", "index", "brain"); From aa1672f2f597f187cb55e34b081cb691793f27cd Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 3 Nov 2026 02:21:18 +0000 Subject: [PATCH 4/5] test: pin the sibling-prefix and leaving dangling-chain refusals in every package (#2506) Dropping the separator after the root broke no existing ui-sdk or ui-server test, and dropping the check on a followed link's target broke none anywhere. These cases fail on each mutation and pass on the copies the packages carried before the shared module. Refs #2506 Co-Authored-By: Claude Opus 5.5 --- packages/common/tests/safe-path.test.ts | 6 ++++++ packages/core/tests/containment-rows.test.ts | 6 ++++++ packages/ui-sdk/tests/bridge-tools.test.ts | 16 +++++++++++++++- packages/ui-server/tests/files-walker.test.ts | 13 ++++++++++++- 4 files changed, 39 insertions(+), 2 deletions(-) diff --git a/packages/common/tests/safe-path.test.ts b/packages/common/tests/safe-path.test.ts index 72f4d7f1c2..e6c897d33d 100644 --- a/packages/common/tests/safe-path.test.ts +++ b/packages/common/tests/safe-path.test.ts @@ -81,6 +81,9 @@ symlinkSync(outside, join(root, "bounce")); symlinkSync(join(root, "notes"), join(outside, "back")); symlinkSync("../../notes", join(root, ".brain/scratch/link")); symlinkSync(root, join(base, "root-link")); +// A dangling chain that leaves the root and comes back to a missing target inside. +symlinkSync(join(root, "notes/missing"), join(outside, "dangling-back")); +symlinkSync(join(outside, "dangling-back"), join(root, "dangling-bounce")); const FINAL_FOLLOW: ContainmentPolicy = { missingRoot: "refuse", danglingLinks: "follow", components: "final" }; const EVERY_REFUSE: ContainmentPolicy = { missingRoot: "lexical", danglingLinks: "refuse", components: "every" }; @@ -117,6 +120,9 @@ describe("resolveContained: one algorithm, sync and async", () => { ["dangling-in", "brain/notes/missing (as brain/dangling-in)", "refused dangling"], ["dangling-in/x", "brain/notes/missing/x (as brain/dangling-in/x)", "refused dangling"], ["dangling-out", "refused escape", "refused dangling"], + // Followed, the first hop already leaves the root: refused there, even + // though the chain ends inside. + ["dangling-bounce", "refused escape", "refused dangling"], // A dangling cycle: followed, it runs out of the link budget. ["cycle-a", "refused link-budget", "refused dangling"], ["cycle-a/x", "refused link-budget", "refused dangling"], diff --git a/packages/core/tests/containment-rows.test.ts b/packages/core/tests/containment-rows.test.ts index 0c56cd9600..df986182a6 100644 --- a/packages/core/tests/containment-rows.test.ts +++ b/packages/core/tests/containment-rows.test.ts @@ -37,6 +37,9 @@ symlinkSync(outside, join(root, "bounce")); symlinkSync(join(root, "notes"), join(outside, "back")); symlinkSync("../../notes", join(root, ".brain/scratch/link")); symlinkSync(root, join(base, "root-link")); +// A dangling chain that leaves the root and comes back to a missing target inside. +symlinkSync(join(root, "notes/missing"), join(outside, "dangling-back")); +symlinkSync(join(outside, "dangling-back"), join(root, "dangling-bounce")); /** The answer relative to the fixture base, or `refused`. */ const answer = (path: string | null) => (path === null ? "refused" : relative(base, path) || "."); @@ -74,6 +77,9 @@ describe("core safeResolve(root, rel): its resolver row", () => { ["dangling-in", "brain/notes/missing"], ["dangling-in/x", "brain/notes/missing/x"], ["dangling-out", "refused"], + // A dangling chain is refused as soon as it leaves the root, even when it + // ends inside. + ["dangling-bounce", "refused"], ["cycle-a", "refused"], ["cycle-a/x", "refused"], // Only the final path must be inside: out through one link and back diff --git a/packages/ui-sdk/tests/bridge-tools.test.ts b/packages/ui-sdk/tests/bridge-tools.test.ts index 18204e68bc..aa813d745b 100644 --- a/packages/ui-sdk/tests/bridge-tools.test.ts +++ b/packages/ui-sdk/tests/bridge-tools.test.ts @@ -1,7 +1,7 @@ import { describe, expect, test } from "bun:test"; import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync } from "fs"; import { tmpdir } from "os"; -import { isAbsolute, join } from "path"; +import { basename, isAbsolute, join } from "path"; import { BRIDGE_TOOL_POSTURE } from "../src/tool-contracts/bridge.js"; import { piMaskFilename } from "../src/server/bridge-tools/mask.js"; @@ -68,6 +68,20 @@ describe("resolveInRepo", () => { } }); + test("rejects a sibling directory that shares the root's name as a prefix", () => { + const root = mkdtempSync(join(tmpdir(), "bridge-path-root-")); + const sibling = `${root}-other`; + mkdirSync(sibling); + try { + symlinkSync(sibling, join(root, "sibling")); + expect(resolveInRepo(root, `../${basename(sibling)}/mask.png`)).toBeNull(); + expect(resolveInRepo(root, "sibling/mask.png")).toBeNull(); + } finally { + rmSync(root, { recursive: true, force: true }); + rmSync(sibling, { recursive: true, force: true }); + } + }); + test("rejects a symlink escape, including a missing tail below it", () => { const root = mkdtempSync(join(tmpdir(), "bridge-path-root-")); const outside = mkdtempSync(join(tmpdir(), "bridge-path-outside-")); diff --git a/packages/ui-server/tests/files-walker.test.ts b/packages/ui-server/tests/files-walker.test.ts index 6e2d15ed21..7a603ff693 100644 --- a/packages/ui-server/tests/files-walker.test.ts +++ b/packages/ui-server/tests/files-walker.test.ts @@ -1,6 +1,6 @@ import { describe, test, expect, beforeAll, afterAll, spyOn } from "bun:test"; import * as fsp from "node:fs/promises"; -import { mkdir, writeFile, symlink, rm } from "node:fs/promises"; +import { mkdir, writeFile, symlink, rm, realpath } from "node:fs/promises"; import { join, win32 } from "node:path"; import { tmpdir } from "node:os"; import { @@ -102,6 +102,17 @@ describe("safeResolve", () => { test("rejects symlink escape", async () => { await expect(safeResolve("escape-link", root)).rejects.toBeInstanceOf(PathEscapeError); }); + test("rejects a link into a sibling directory that shares the root's name as a prefix", async () => { + const sibling = `${await realpath(root)}-other`; + await mkdir(sibling, { recursive: true }); + try { + await symlink(sibling, join(root, "sibling-link")); + await expect(safeResolve("sibling-link/x.md", root)).rejects.toBeInstanceOf(PathEscapeError); + } finally { + await rm(join(root, "sibling-link"), { force: true }); + await rm(sibling, { recursive: true, force: true }); + } + }); test("accepts repo-relative path", async () => { await expect(safeResolve("notes/foo.md", root)).resolves.toBeTruthy(); }); From 3cfdb11187ea692f8e010e69ac7a32ef5bb03b11 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 3 Nov 2026 03:18:25 +0000 Subject: [PATCH 5/5] docs: move the files-walker test citations past the new sibling-prefix test (#2506) Refs #2506 Co-Authored-By: Claude Opus 5.5 --- docs/http-api-coverage.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/http-api-coverage.md b/docs/http-api-coverage.md index d2e39abf9e..f9e3c2012f 100644 --- a/docs/http-api-coverage.md +++ b/docs/http-api-coverage.md @@ -237,10 +237,10 @@ cover start refusal, mid-turn partial work, overlapping observations and leases. **F — Content and byte ranges.** -- `an uncompressed, all-ASCII PDF is served as binary, not as its source` ([source](../packages/ui-server/tests/files-walker.test.ts)), (`an uncompressed, all-ASCII PDF is served as binary, not as its source`, `packages/ui-server/tests/files-walker.test.ts:299-305`) -- `rejects file_too_large` ([source](../packages/ui-server/tests/files-walker.test.ts)), (`rejects file_too_large`, `packages/ui-server/tests/files-walker.test.ts:324-329`) +- `an uncompressed, all-ASCII PDF is served as binary, not as its source` ([source](../packages/ui-server/tests/files-walker.test.ts)), (`an uncompressed, all-ASCII PDF is served as binary, not as its source`, `packages/ui-server/tests/files-walker.test.ts:310-316`) +- `rejects file_too_large` ([source](../packages/ui-server/tests/files-walker.test.ts)), (`rejects file_too_large`, `packages/ui-server/tests/files-walker.test.ts:335-340`) - `rejects symlink escape` ([source](../packages/ui-server/tests/files-walker.test.ts)), (`rejects symlink escape`, `packages/ui-server/tests/files-walker.test.ts:102-104`) -- `a child of an existing file is not found without leaking its absolute path` ([source](../packages/ui-server/tests/files-walker.test.ts)), (`a child of an existing file is not found without leaking its absolute path`, `packages/ui-server/tests/files-walker.test.ts:335-348`) +- `a child of an existing file is not found without leaking its absolute path` ([source](../packages/ui-server/tests/files-walker.test.ts)), (`a child of an existing file is not found without leaking its absolute path`, `packages/ui-server/tests/files-walker.test.ts:346-359`) - `Safari's two-byte probe gets a 206 with its length, and the frame headers` ([source](../packages/ui-server/tests/files-raw-range.test.ts)), (`Safari's two-byte probe gets a 206 with its length, and the frame headers`, `packages/ui-server/tests/files-raw-range.test.ts:222-231`) - `a range that starts past the end is a 416 naming the size` ([source](../packages/ui-server/tests/files-raw-range.test.ts)), (`a range that starts past the end is a 416 naming the size`, `packages/ui-server/tests/files-raw-range.test.ts:87-92`) - `a HEAD request ignores Range, which applies to GET only` ([source](../packages/ui-server/tests/files-raw-range.test.ts)), (`a HEAD request ignores Range, which applies to GET only`, `packages/ui-server/tests/files-raw-range.test.ts:102-107`)