From c21d2125e08b864dd7d7f2b18f2dcfc10b2cd5e1 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 3 Nov 2026 11:06:04 +0000 Subject: [PATCH 1/3] CONTRACT: fix(core,ui-sdk,ui-server): give the strictest containment answer in every resolver row (#3422) Implements the maintainer ruling on #3422. - core `safeResolve`/`resolveWritable` (public, `@schlessera/brain/module`), the SDK's `resolveInRepo` and the server's file `safeResolve` now refuse an absolute request even inside the root, any `..` segment, `:` or `\` in a segment, dangling links and out-and-back links (`components: "every"`), and a root whose realpath fails. Breaking for core in the 0.45.0 minor; the integration-contract index and package API component record it, and the changeset carries migration notes. - Callers that re-checked an absolute path they already held now use the core-internal `safeResolveHeld` (module settings, module toggle) or pass a root-relative request (travel route import, diagram export). CLI path arguments are refused when absolute, as the containment guarantee states. - Deny-direction predicates use `isWithin(..., { trailingSeparator: "boundary" })`, so `/` holds every absolute path. A `/` transport bind, managed worktree generation, reference source view and local sync remote, and `/` host credential state, were accepted before; all are refused now. The hand-written `=== "/"` checks that the rule covers are gone. - Moved doc citations are updated. Co-Authored-By: Claude Opus 5.5 --- .changeset/strict-containment-answers.md | 25 +++++ api-report/core.txt | 2 +- docs/decisions/container-fresh-proc.md | 4 +- docs/decisions/governed-writable-workers.md | 22 ++--- docs/decisions/managed-worktrees.md | 4 +- docs/decisions/policy-write-boundary.md | 4 +- docs/decisions/worker-writable-areas.md | 10 +- docs/hosting/agent-workers.md | 2 +- docs/integration-contract.md | 18 ++++ docs/integration-contract/package-api.md | 20 ++++ docs/modules.md | 2 +- docs/plans/module-renderers.md | 2 +- docs/plans/storage-accounting.md | 2 +- packages/core/src/lib/module-settings.ts | 4 +- packages/core/src/lib/module-toggle.ts | 4 +- packages/core/src/lib/safe-path.ts | 57 +++++++++--- packages/core/tests/containment-rows.test.ts | 62 +++++++++---- packages/core/tests/eval-cli.test.ts | 4 +- packages/core/tests/safe-path.test.ts | 4 +- packages/module-diagrams/src/export-cli.ts | 2 +- packages/module-images/tests/scratch.test.ts | 6 +- packages/module-travel/src/route.ts | 9 +- .../server/bridge-tools/resolve-in-repo.ts | 14 +-- .../ui-sdk/src/server/worker-file-observer.ts | 3 +- packages/ui-sdk/src/server/worker-launcher.ts | 47 ++++++---- packages/ui-sdk/src/server/worker-rtk.ts | 5 +- .../ui-sdk/tests/containment-rows.test.ts | 91 +++++++++++++++---- packages/ui-sdk/tests/worker-launcher.test.ts | 4 +- packages/ui-server/src/brain/host-boundary.ts | 3 +- .../ui-server/src/brain/operational-state.ts | 7 +- packages/ui-server/src/brain/sync-mirror.ts | 3 +- packages/ui-server/src/files/walker.ts | 7 +- .../ui-server/tests/containment-rows.test.ts | 54 +++++++---- 33 files changed, 364 insertions(+), 143 deletions(-) create mode 100644 .changeset/strict-containment-answers.md diff --git a/.changeset/strict-containment-answers.md b/.changeset/strict-containment-answers.md new file mode 100644 index 0000000000..8b5906ebd4 --- /dev/null +++ b/.changeset/strict-containment-answers.md @@ -0,0 +1,25 @@ +--- +"@schlessera/brain": minor +"@schlessera/brain-ui-sdk": patch +"@schlessera/brain-ui-server": patch +"@schlessera/brain-module-diagrams": patch +"@schlessera/brain-module-travel": patch +--- + +**Breaking: `safeResolve` and `resolveWritable` from `@schlessera/brain/module` now give the strictest containment answer in every row (#3422).** They return `null` for: + +- an absolute path, even one inside the brain root; +- any `..` segment, even when the result stays inside; +- `:` or `\` in a segment; +- a dangling symlink, even one whose target is inside; +- a path that leaves the root through one symlink and comes back through another, since every existing component must now stay inside, not only the final path. + +A root whose realpath fails was already refused, and still is. The answer is still the canonical path. + +The CLI resolves its path arguments through the same helpers. A path given to `--out`, `--stamp`, `brain read`, `brain process`, `brain render`, `brain image` or `brain diagram export` is therefore refused when it is absolute, even inside the brain, as the integration contract's containment guarantee already says. Pass it relative to the brain root. + +Migration for module authors: pass paths relative to the brain root. To re-check an absolute path you already hold, such as an earlier answer from `safeResolve`, pass it relative to the root's realpath (`relative(safeResolve(root, ".")!, path)`). Normalise a link target before resolving it (`join(dirname(path), target)`) instead of sending its `..`. Do not rely on a dangling link to name a file you are about to create. + +The ui-sdk's `resolveInRepo` and the server's file `safeResolve` give the same answers. The SDK newly refuses `..`, `:` and `\`, dangling links and out-and-back links. The server newly refuses a missing brain root instead of falling back to the lexical path. + +The deny-direction containment checks now treat `/` as holding every absolute path. Before, a `/` source passed the worker launcher's refusal of "the brain or its ancestors" for a transport bind, a managed worktree generation and a reference source view, and the server's sync transport mounted a local remote of `/`. A host credential state directory of `/` was also accepted. All of these are now refused. diff --git a/api-report/core.txt b/api-report/core.txt index 65165c36d7..84fd01b53b 100644 --- a/api-report/core.txt +++ b/api-report/core.txt @@ -1578,7 +1578,7 @@ signatures (every public export and the types it is made of) resolveReranker (packages/core/src/lib/registry.ts) export function resolveReranker(config?: RerankerSettings): Reranker | undefined; resolveWritable (packages/core/src/lib/safe-path.ts) - export function resolveWritable(root: string, relOrAbs: string): string | null; + export function resolveWritable(root: string, relPath: string): string | null; restoreStorageAttachment (packages/core/src/lib/storage-attachments.ts) export function restoreStorageAttachment(root: string, path: string, expected: StorageAttachmentVersion, copy: (fd: number) => void, assertCurrent?: () => void): void; rewriteGeneratedRegion (packages/core/src/lib/generated-regions.ts) diff --git a/docs/decisions/container-fresh-proc.md b/docs/decisions/container-fresh-proc.md index dcc1664f36..0bf8b20da1 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:510-690`). +and a fresh procfs (`workerCommand`, `packages/ui-sdk/src/server/worker-launcher.ts:514-694`). 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:1636`). + (`FRESH_PROC_REFUSED`, `packages/ui-sdk/src/server/worker-launcher.ts:1645`). 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. diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index 00f6649886..f2eee7c4d4 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -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:421-428`). +relay (`providerRelayFor`, `packages/ui-server/src/brain/host-boundary.ts:422-429`). 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:681-691`). A relayed turn keeps no +`packages/ui-sdk/src/server/worker-launcher.ts:684-694`). 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:1137-1165`). +(`function* openPrivateTurnTempSteps`, `packages/ui-sdk/src/server/worker-launcher.ts:1146-1174`). 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, @@ -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:1911`): +(`export function restrictedReadPaths`, `packages/ui-sdk/src/server/worker-launcher.ts:1920`): - the Bun executable; - the backend entry's package, its `node_modules` chains and linked workspace @@ -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: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`). +`packages/ui-sdk/src/server/worker-launcher.ts:613-619`), +(`temporaryRuntimeMounts`, `packages/ui-sdk/src/server/worker-launcher.ts:640-679`) +and (`runtimeMaskOverlays`, `packages/ui-sdk/src/server/worker-launcher.ts:801-819`). 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 @@ -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:1100-1128`; +`packages/ui-sdk/src/server/worker-launcher.ts:1109-1137`; `function* openPrivateTurnTempSteps`, -`packages/ui-sdk/src/server/worker-launcher.ts:1137-1163`) before population and +`packages/ui-sdk/src/server/worker-launcher.ts:1146-1172`) before population and start-gate release (`function* launchAgentWorkerSteps`, -`packages/ui-sdk/src/server/worker-launcher.ts:1326-1414`). Group modes and a uid +`packages/ui-sdk/src/server/worker-launcher.ts:1335-1423`). 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:512-523`). + `packages/ui-server/src/brain/host-boundary.ts:513-524`). - 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/managed-worktrees.md b/docs/decisions/managed-worktrees.md index c1265b08e3..7dfc992e81 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:853-864`). +`// Managed worktrees (#2430): the whole access generation`, `packages/ui-sdk/src/server/worker-launcher.ts:862-873`). 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:865-876`). +(`// Shared reference source (#2432)`, `packages/ui-sdk/src/server/worker-launcher.ts:874-885`). 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 2ca54a82af..ecab0c2a94 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:1326-1581`): +`packages/ui-sdk/src/server/worker-launcher.ts:1335-1590`): 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:1100-1124`). bubblewrap's + `packages/ui-sdk/src/server/worker-launcher.ts:1109-1133`). 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 diff --git a/docs/decisions/worker-writable-areas.md b/docs/decisions/worker-writable-areas.md index 118fd68354..8301dd2660 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:902-943`). +(`export function prepareWorkerSandbox`, `packages/ui-sdk/src/server/worker-launcher.ts:911-952`). 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:824-854`). +describe (`function sandboxMounts`, `packages/ui-sdk/src/server/worker-launcher.ts:833-863`). 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:902-943`). Host-backed overlay +`packages/ui-sdk/src/server/worker-launcher.ts:911-952`). 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,14 +267,14 @@ 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 policy: ContainmentPolicy = isScratchPath(rel)`, `packages/ui-server/src/files/walker.ts:97-99`). +(`const policy: ContainmentPolicy = isScratchPath(rel)`, `packages/ui-server/src/files/walker.ts:96-98`). 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:116-152`). +(`export function readAnchoredSnapshot`, `packages/ui-server/src/files/walker.ts:115-151`). 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:517-547`), because a diff --git a/docs/hosting/agent-workers.md b/docs/hosting/agent-workers.md index 0c97221d98..311d49d482 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:553-568`). This does not select +`packages/ui-sdk/src/server/worker-launcher.ts:556-571`). 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 diff --git a/docs/integration-contract.md b/docs/integration-contract.md index f081007124..3a52347a19 100644 --- a/docs/integration-contract.md +++ b/docs/integration-contract.md @@ -20,6 +20,24 @@ same-commit update of the index or relevant authoritative component. How they ar The reasoning is in [decisions/contract-versioning.md](decisions/contract-versioning.md). +## Strictest path containment answers (breaking before 1.0, 0.45.0, #3422) + +`safeResolve` and `resolveWritable` from `@schlessera/brain/module` now return +`null` in these cases: + +- an absolute path, even inside the root; +- any `..` segment; +- `:` or `\` in a segment; +- a dangling symlink; +- a path any existing component of which leaves the root. + +The CLI's path arguments resolve through them, so an absolute `--out` or +document path is refused even inside the brain, as the containment guarantee +already states. The [maintainer ruling](https://github.com/schlessera/brain-kit/issues/3422#issuecomment-6599244174) +is recorded on the issue. See [the package API component](integration-contract/package-api.md#strictest-path-containment-answers-breaking-before-10-0450-3422). +This ships in the 0.45.0 minor with the `breaking` label and a changeset that +names the break. + ## Maintenance worker output allowance (additive, 0.45.0, #3357) A maintenance worker's launcher may declare its output stage's size and setting diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index 96c7ecbfaa..a9c33c6572 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -382,6 +382,26 @@ process context. First-party modules import this entry and never `@schlessera/brain/queries`. The `/internal` entry keeps the same names for the first-party packages that still import them. + +**Breaking before 1.0: strictest path containment answers (0.45.0, #3422).** +`safeResolve(root, rel)` and `resolveWritable(root, rel)` take a path relative +to the brain root. They return its canonical path, or `null` for any of these: + +- an absolute `rel`, even one inside the root; +- a `..` segment, even one whose result would stay inside; +- `:` or `\` in a segment, or a NUL; +- a dangling symlink, wherever it points; +- a path whose existing components do not all stay inside, such as one that + leaves through one link and comes back through another; +- a root whose realpath fails. + +Before 0.45.0, core accepted an absolute path inside the root and a `..` that +stayed inside. It also followed a dangling link to an inside target and checked +only the final path. A caller holding an absolute path passes it relative to +the root's realpath. The CLI's path arguments resolve through these helpers, so +the [containment guarantee](#guarantees-consumers-may-rely-on) now holds +literally for `--out` and document paths. + **Additive frozen configuration root (#2848).** `@schlessera/brain/module` exports `configurationRoot(root: string): string`. When `root` equals the trusted worker's `BRAIN_WORKER_DATA_ROOT` and `BRAIN_WORKER_CONFIG_ROOT` is diff --git a/docs/modules.md b/docs/modules.md index b18b3e0437..bc8eca1c43 100644 --- a/docs/modules.md +++ b/docs/modules.md @@ -600,7 +600,7 @@ first-party modules do not use it either. | Need | `@schlessera/brain/module` exports | | --- | --- | | Read configuration from a worker's frozen view | `configurationRoot(root)`; other roots pass through unchanged | -| Keep a path inside the brain | `safeResolve`, `resolveWritable` | +| Keep a path inside the brain | `safeResolve`, `resolveWritable`: a path relative to the root, never absolute and without `..`; dangling and out-and-back links are refused ([0.45.0](integration-contract/package-api.md#strictest-path-containment-answers-breaking-before-10-0450-3422)) | | Write a document atomically | `writeFileSafely` (`replace: false` refuses an existing name with `WriteRefusedError`, `code: "EEXIST"`) | | Intermediate files that are never canonical | `SCRATCH_DIR`, `scratchName`, `writeScratchFile`, `assertScratchWritable`, `isInScratch`, `isWriteRefusal`, `pruneScratch` | | Rewrite a generated region, keeping the rest of the file | `splitFrontmatterBlock`, `rewriteGeneratedRegion`, `inertGeneratedText` | diff --git a/docs/plans/module-renderers.md b/docs/plans/module-renderers.md index 6ed484352b..ce8f6ac204 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:303` classifies UTF-8 SVG as text. + `packages/ui-server/src/files/walker.ts:302` 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 89bfce463f..992758c929 100644 --- a/docs/plans/storage-accounting.md +++ b/docs/plans/storage-accounting.md @@ -69,7 +69,7 @@ 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:114-120`). + private locations (`statePaths`, `packages/ui-server/src/brain/operational-state.ts:113-119`). - 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`) diff --git a/packages/core/src/lib/module-settings.ts b/packages/core/src/lib/module-settings.ts index c8151e362c..d7b397d31e 100644 --- a/packages/core/src/lib/module-settings.ts +++ b/packages/core/src/lib/module-settings.ts @@ -7,7 +7,7 @@ import type { LoadedModule } from "./module-types.js"; import type { ModuleSettingsMigrationPlan } from "./module-settings-types.js"; import { isRecord, mergeModuleSettings, moduleSettingsPath, readModuleSettings } from "./module-settings-source.js"; import { equalSettings, rewriteSettingsJson } from "./module-settings-json.js"; -import { safeResolve, writeFileSafely } from "./safe-path.js"; +import { safeResolve, safeResolveHeld, writeFileSafely } from "./safe-path.js"; import { git, gitPath } from "./sync/git.js"; export class ModuleSettingsError extends Error { @@ -121,7 +121,7 @@ function commitChanges(brain: BrainContext, name: string, changes: Array<{ path: if (git(brain.root, ["rev-parse", "--verify", "HEAD"]).code) throw new ModuleSettingsError("Commit the initial brain before saving module settings", 422); const paths = actual.map((c) => relative(safeResolve(brain.root, ".")!, c.path)); for (const change of actual) { - if (safeResolve(brain.root, change.path) !== change.path || lstatSync(change.path, { throwIfNoEntry: false })?.isSymbolicLink()) throw new ModuleSettingsError("A settings target is unsafe; no changes made", 422); + if (safeResolveHeld(brain.root, change.path) !== change.path || lstatSync(change.path, { throwIfNoEntry: false })?.isSymbolicLink()) throw new ModuleSettingsError("A settings target is unsafe; no changes made", 422); const present = existsSync(change.path) ? readFileSync(change.path, "utf8") : null; if (present !== change.before) throw new ModuleSettingsError("Settings changed; review the saved values", 409); } diff --git a/packages/core/src/lib/module-toggle.ts b/packages/core/src/lib/module-toggle.ts index 104fc2198f..f4647292a8 100644 --- a/packages/core/src/lib/module-toggle.ts +++ b/packages/core/src/lib/module-toggle.ts @@ -6,7 +6,7 @@ import { planModuleFlag } from "./module-config-edit.js"; import { planModuleInstructions } from "./module-instructions.js"; import { discoverSkills } from "./skills/discover.js"; import { syncSkills } from "./skills/sync.js"; -import { safeResolve, writeFileSafely } from "./safe-path.js"; +import { safeResolveHeld, writeFileSafely } from "./safe-path.js"; import type { LoadedModule } from "./module-types.js"; import { readGeneratedRegion } from "./generated-regions.js"; @@ -25,7 +25,7 @@ export function toggleModule(cli: CliContext, name: string, enabled: boolean): { } const state = enabled ? "active" : "dormant"; const modules: LoadedModule[] = brain.modules.map((m) => m === mod ? { ...m, state } : m); - const path = safeResolve(brain.root, brain.configPath); + const path = safeResolveHeld(brain.root, brain.configPath); if (!path) throw new UsageError("Config resolves outside the brain root; no changes made"); const original = readFileSync(path, "utf8"); // All source, ownership, discovery and emitter checks precede every write. diff --git a/packages/core/src/lib/safe-path.ts b/packages/core/src/lib/safe-path.ts index 27e162362b..1e504e3c1d 100644 --- a/packages/core/src/lib/safe-path.ts +++ b/packages/core/src/lib/safe-path.ts @@ -2,27 +2,62 @@ import { randomBytes } from "crypto"; 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, join } from "path"; +import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "path"; -const CORE_CONTAINMENT: ContainmentPolicy = { missingRoot: "refuse", danglingLinks: "follow", components: "final" }; +const CORE_CONTAINMENT: ContainmentPolicy = { missingRoot: "refuse", danglingLinks: "refuse", components: "every" }; /** - * Resolve a relative path and verify it stays inside `root`, following + * Whether a request is refused before it is resolved: anything but a string, + * an absolute path, and a segment that is `..` or holds `:` or `\\` (#3422). + * A NUL is refused by the shared resolver. + */ +function refusedRequest(relPath: string): boolean { + if (typeof relPath !== "string") return true; + if (relPath.startsWith("/") || relPath.startsWith("\\")) return true; + return relPath.split("/").some((segment) => segment === ".." || segment.includes(":") || segment.includes("\\")); +} + +/** + * Resolve a repo-relative path and verify it stays inside `root`, following * symlinks (realpath) so a symlink inside the repo can't escape it. - * Returns the canonical absolute path, or null if the path escapes (or the - * root itself does not exist). + * Returns the canonical absolute path, or null if the path is refused, + * 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. + * #2506), with the strictest answer in every row since #3422: synchronous, + * `null` for every refusal; an absolute request is refused even inside the + * root, and so is any `..` segment, even one whose result would stay inside, + * and `:` or `\\` in a segment; a dangling link is refused wherever it points; + * and every existing component on the way must stay inside, not only the + * final path. A caller holding an absolute path passes it relative to the + * root (`relative(root, abs)`), which a path outside the root turns into a + * refused `..`. */ export function safeResolve(root: string, relPath: string): string | null { + if (refusedRequest(relPath)) return null; const contained = resolveContainedSync(root, relPath, CORE_CONTAINMENT); return contained.ok ? contained.canonical : null; } +/** + * Re-check a path the caller already holds as absolute: a canonical answer + * `safeResolve` gave earlier, or a file core located itself (the brain's + * config). It is `safeResolve` of the same path taken relative to the root's + * realpath, or to the root as given, whichever holds it lexically; a path + * under neither is refused. Not for requests: a request is relative, and + * `safeResolve` refuses an absolute one (#3422). + */ +export function safeResolveHeld(root: string, path: string): string | null { + if (typeof path !== "string" || !isAbsolute(path)) return null; + const canonicalRoot = safeResolve(root, "."); + if (!canonicalRoot) return null; + for (const base of [canonicalRoot, resolve(root)]) { + const rel = relative(base, path); + if (rel === "" || (!isAbsolute(rel) && rel.split(sep)[0] !== "..")) return safeResolve(root, rel || "."); + } + return null; +} + /** * Resolve a path the caller may read or write: inside the brain root only. * @@ -33,8 +68,8 @@ export function safeResolve(root: string, relPath: string): string | null { * what lands there, and gitignored and pruned, so it is never canonical. A * write into it goes through `ensureScratch`. */ -export function resolveWritable(root: string, relOrAbs: string): string | null { - return safeResolve(root, relOrAbs); +export function resolveWritable(root: string, relPath: string): string | null { + return safeResolve(root, relPath); } /** diff --git a/packages/core/tests/containment-rows.test.ts b/packages/core/tests/containment-rows.test.ts index df986182a6..ba99bf2c4e 100644 --- a/packages/core/tests/containment-rows.test.ts +++ b/packages/core/tests/containment-rows.test.ts @@ -1,11 +1,10 @@ /** * 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. + * synchronous and returns the canonical path or `null`. Since #3422 it gives + * the strictest answer in every row: it refuses an absolute request even + * inside the root, any `..` segment, `:` or `\\` in a segment, a dangling + * link wherever it points, a path that leaves through one link and comes back + * through another, and everything when the root's realpath fails. */ import { afterAll, describe, expect, test } from "bun:test"; import { mkdirSync, mkdtempSync, realpathSync, renameSync, rmSync, symlinkSync, writeFileSync } from "fs"; @@ -13,7 +12,7 @@ import { tmpdir } from "os"; import { join, relative } from "path"; import { SCRATCH_DIR } from "../src/lib/scratch"; -import { safeResolve } from "../src/lib/safe-path"; +import { safeResolve, safeResolveHeld } from "../src/lib/safe-path"; const base = realpathSync(mkdtempSync(join(tmpdir(), "brain-kit-containment-rows-"))); afterAll(() => rmSync(base, { recursive: true, force: true })); @@ -55,17 +54,21 @@ describe("core safeResolve(root, rel): its resolver row", () => { ["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"], + // `..` is refused even when the result stays inside (#3422). + ["notes/../notes/a.md", "refused"], + ["notes/sub/..", "refused"], ["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"], + // Absolute: refused even inside the root (#3422). + [join(root, "notes/a.md"), "refused"], + [root, "refused"], ["/etc/passwd", "refused"], - // Windows syntax is not checked. - ["a:b", "brain/a:b"], - ["a\\b", "brain/a\\b"], + // Windows syntax is refused in any segment (#3422). + ["a:b", "refused"], + ["notes/a:b.md", "refused"], + ["a\\b", "refused"], + ["\\notes", "refused"], ["a\0b", "refused"], // Links: canonical answers, escapes refused, including for a file that // does not exist yet under a symlinked parent. @@ -73,18 +76,19 @@ describe("core safeResolve(root, rel): its resolver row", () => { ["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"], + // A dangling link is refused wherever it points (#3422). + ["dangling-in", "refused"], + ["dangling-in/x", "refused"], ["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 - // through another is accepted. - ["bounce/back/a.md", "brain/notes/a.md"], + // Every component must stay inside, not only the final path: out through + // one link and back through another is refused (#3422). + ["bounce/back/a.md", "refused"], + ["bounce/back", "refused"], // Scratch is not special to the resolver. [".brain", "brain/.brain"], [".brain/scratch/s.txt", "brain/.brain/scratch/s.txt"], @@ -120,6 +124,24 @@ describe("core safeResolve(root, rel): its resolver row", () => { }); }); +describe("core safeResolveHeld(root, abs): re-checking a path the caller holds (#3422)", () => { + test("an absolute path under the root's realpath or the root as given gets safeResolve's answer", () => { + expect(answer(safeResolveHeld(root, join(root, "notes/a.md")))).toBe("brain/notes/a.md"); + expect(answer(safeResolveHeld(root, root))).toBe("brain"); + expect(answer(safeResolveHeld(join(base, "root-link"), join(base, "root-link/notes/a.md")))).toBe("brain/notes/a.md"); + expect(answer(safeResolveHeld(join(base, "root-link"), join(root, "notes/a.md")))).toBe("brain/notes/a.md"); + }); + + test("a relative path, a path outside the root and a path through a refused link are refused", () => { + expect(safeResolveHeld(root, "notes/a.md")).toBeNull(); + expect(safeResolveHeld(root, join(outside, "secret.md"))).toBeNull(); + expect(safeResolveHeld(root, `${root}-other/secret.md`)).toBeNull(); + expect(safeResolveHeld(root, join(root, "bounce/back/a.md"))).toBeNull(); + expect(safeResolveHeld(root, join(root, "dangling-in"))).toBeNull(); + expect(safeResolveHeld(join(base, "nope"), join(base, "nope/x"))).toBeNull(); + }); +}); + test("core's scratch area is .brain/scratch", () => { expect(SCRATCH_DIR).toBe(".brain/scratch"); }); diff --git a/packages/core/tests/eval-cli.test.ts b/packages/core/tests/eval-cli.test.ts index 6a8463ef89..e4e20a1483 100644 --- a/packages/core/tests/eval-cli.test.ts +++ b/packages/core/tests/eval-cli.test.ts @@ -109,7 +109,9 @@ describe("scores", () => { test("--out writes the same envelope that --json prints", async () => { const set = writeSet("out.jsonl", TOP1); const outPath = join(root, "evals", "runs", "latest.json"); - const { code, out } = await evalJson(["--set", set, "--out", outPath]); + // `--out` is repo-relative: an absolute path is refused, even inside the brain (#3422). + expect((await evalJson(["--set", set, "--out", outPath])).code).toBe(2); + const { code, out } = await evalJson(["--set", set, "--out", "evals/runs/latest.json"]); expect(code).toBe(0); expect(JSON.parse(readFileSync(outPath, "utf-8"))).toEqual(out); }); diff --git a/packages/core/tests/safe-path.test.ts b/packages/core/tests/safe-path.test.ts index ba31bb76cc..b8a436078d 100644 --- a/packages/core/tests/safe-path.test.ts +++ b/packages/core/tests/safe-path.test.ts @@ -94,10 +94,10 @@ describe("safeResolve — dangling and cyclic symlinks", () => { expect(safeResolve(root, "sneakydir/new.md")).toBeNull(); }); - test("accepts a dangling symlink whose target stays inside the root", () => { + test("refuses a dangling symlink even when its target stays inside the root (#3422)", () => { const root = makeRoot(); symlinkSync(join(root, "not-yet.md"), join(root, "link.md")); - expect(safeResolve(root, "link.md")).toBe(join(realpathSync(root), "not-yet.md")); + expect(safeResolve(root, "link.md")).toBeNull(); }); test("rejects a dangling symlink cycle instead of looping", () => { diff --git a/packages/module-diagrams/src/export-cli.ts b/packages/module-diagrams/src/export-cli.ts index 7d50a7cfbc..e80d599676 100644 --- a/packages/module-diagrams/src/export-cli.ts +++ b/packages/module-diagrams/src/export-cli.ts @@ -20,7 +20,7 @@ export async function readDiagramInput(root:string,input:string):Promise<{source try{for(;;){const item=await reader.read();if(item.done)break;size+=item.value.byteLength;if(size>1024*1024)throw Error("Diagram input exceeds the 1 MiB parse bound");chunks.push(item.value);}}finally{await reader.cancel();} return {source:new TextDecoder("utf-8",{fatal:true}).decode(Buffer.concat(chunks,size)),path:absolute?relative(root,absolute):"-",absolute}; } -function target(root:string,path:string):string {const parent=resolveWritable(root,dirname(path));if(!parent)throw Error("Output path must remain inside the brain");const result=join(parent,basename(path)),entry=lstatSync(result,{throwIfNoEntry:false});if(entry?.isSymbolicLink()||entry&&!entry.isFile())throw Error("Output must be an unlinked regular file name");if(!resolveWritable(root,result))throw Error("Output path must remain inside the brain");return result;} +function target(root:string,path:string):string {const parent=resolveWritable(root,dirname(path));if(!parent)throw Error("Output path must remain inside the brain");const result=join(parent,basename(path)),entry=lstatSync(result,{throwIfNoEntry:false});if(entry?.isSymbolicLink()||entry&&!entry.isFile())throw Error("Output must be an unlinked regular file name");if(resolveWritable(root,path)!==result)throw Error("Output path must remain inside the brain");return result;} function ownedTarget(root:string,path:string,id:string,document:string):boolean { const absolute=target(root,path);if(!existsSync(absolute))return false; const identity=derivedIdentity(readRegularText(absolute,8*1024*1024));if(!identity||identity.id!==id||identity.document!==document)throw Error(`Refusing to replace an unrelated SVG: ${path}`);return true; diff --git a/packages/module-images/tests/scratch.test.ts b/packages/module-images/tests/scratch.test.ts index db46d6eec4..7c8e9f1019 100644 --- a/packages/module-images/tests/scratch.test.ts +++ b/packages/module-images/tests/scratch.test.ts @@ -207,9 +207,11 @@ describe("brain image --scratch", () => { rmSync(outside, { recursive: true, force: true }); }); - test("an absolute --out inside the brain is reported repo-relative after generation, as in the dry run", async () => { + test("--out is repo-relative: an absolute path is refused even inside the brain (#3422), and the output is reported as given", async () => { stubProvider(); - expect(await run(["a lighthouse", "--draft", "--out", join(root, "assets", "draft.png")])).toBe(0); + expect(await run(["a lighthouse", "--draft", "--out", join(root, "assets", "draft.png")])).toBe(1); + out.length = 0; + expect(await run(["a lighthouse", "--draft", "--out", "assets/draft.png"])).toBe(0); const payload = JSON.parse(out.join("\n")) as { output: string; outputs: string[] }; expect(payload.output).toBe("assets/draft.png"); expect(payload.outputs).toEqual(["assets/draft.png"]); diff --git a/packages/module-travel/src/route.ts b/packages/module-travel/src/route.ts index c1b1b47cc6..51d9c6953c 100644 --- a/packages/module-travel/src/route.ts +++ b/packages/module-travel/src/route.ts @@ -125,10 +125,11 @@ export async function importRoute(root: string, source: string, to: string, star if (metrics.recorded_duration_s === null) warnings.push("Incomplete or non-monotonic timestamps: recorded duration remains unknown."); if (startM || endM) warnings.push("Trim boundaries interpolate position, elevation and timestamps along each edge."); for (let suffix = 1; suffix <= 10_000; suffix++) { - const candidate = join(directory, `${stem}${suffix === 1 ? "" : `-${suffix}`}.gpx`); - if (lstatSync(candidate, { throwIfNoEntry: false })) continue; - const output = safeResolve(root, candidate); - if (!output || safeResolve(root, directory) !== directory) throw new Error("Route output directory changed or escapes the brain root."); + const file = `${stem}${suffix === 1 ? "" : `-${suffix}`}.gpx`; + if (lstatSync(join(directory, file), { throwIfNoEntry: false })) continue; + // Requests stay root-relative: `safeResolve` refuses an absolute path (#3422). + const output = safeResolve(root, join(to, file)); + if (!output || safeResolve(root, to) !== directory) throw new Error("Route output directory changed or escapes the brain root."); try { writeFileSafely(output, gpx, { replace: false }); } catch (error) { if (error instanceof WriteRefusedError && error.message.startsWith("EEXIST:")) continue; throw error; } return { source_kind: kind, gpx: relative(canonicalRoot, output).replaceAll("\\", "/"), ...metrics, trim: { start_m: startM, end_m: endM }, warnings, 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 7b2da28def..c4fa4e11cf 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,18 +1,20 @@ 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" }; +const SDK_CONTAINMENT: ContainmentPolicy = { missingRoot: "refuse", danglingLinks: "refuse", components: "every" }; /** * Resolve a repo-relative path without allowing a symlink to escape the repo. * * 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. + * #2506), with the strictest answer in every row since #3422, as core's + * `safeResolve` gives: an absolute request is refused even inside the root, + * and so is any `..` segment, `:` or `\\` in a segment, a dangling link + * wherever it points, and a path any existing component of which leaves the + * root. Synchronous, `null` for every refusal, the canonical path on success. */ export function resolveInRepo(root: string, relPath: string): string | null { - if (isAbsolute(relPath)) return null; + if (typeof relPath !== "string" || relPath.startsWith("/") || relPath.startsWith("\\")) return null; + if (relPath.split("/").some((segment) => segment === ".." || segment.includes(":") || segment.includes("\\"))) return null; const contained = resolveContainedSync(root, relPath, SDK_CONTAINMENT); return contained.ok ? contained.canonical : null; } diff --git a/packages/ui-sdk/src/server/worker-file-observer.ts b/packages/ui-sdk/src/server/worker-file-observer.ts index f2f3575fb4..2ec30798a8 100644 --- a/packages/ui-sdk/src/server/worker-file-observer.ts +++ b/packages/ui-sdk/src/server/worker-file-observer.ts @@ -27,7 +27,8 @@ export function createWorkerFileObserver(options: { const suffix = relative(source.worker, path); const canonical = resolve(options.brain, source.rel, suffix); // A null mask is a view of no bytes, not a host read of its secret source. - if (/^\.env(?:\.|$)/.test(relative(options.brain, canonical).split("/")[0] ?? "") || options.maskPaths?.some(mask => within(canonical, mask))) return { key, version: EMPTY }; + // Deny direction (#3422): a mask at `/` would cover every path. + if (/^\.env(?:\.|$)/.test(relative(options.brain, canonical).split("/")[0] ?? "") || options.maskPaths?.some(mask => isWithin(mask, canonical, { trailingSeparator: "boundary" }))) return { key, version: EMPTY }; const fds: number[] = []; try { let fd = openSync(source.host, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW); fds.push(fd); diff --git a/packages/ui-sdk/src/server/worker-launcher.ts b/packages/ui-sdk/src/server/worker-launcher.ts index 6f1a5e77a7..279cfc9888 100644 --- a/packages/ui-sdk/src/server/worker-launcher.ts +++ b/packages/ui-sdk/src/server/worker-launcher.ts @@ -256,8 +256,8 @@ function restrictedMounts(envelope: RestrictedEnvelope, brain: string): string[] const path = realpathSync(requested); // The read envelope is explicit. The host root, a home or a whole system // tree would make it the old read-only host view under another name. - if (path === "/" || path === "/tmp" || path === "/home" || path === "/etc" || path === "/run" || path === "/var" || path === "/proc" - || brain === path || brain.startsWith(`${path}/`)) { + if (path === "/tmp" || path === "/home" || path === "/etc" || path === "/run" || path === "/var" || path === "/proc" + || holds(path, brain)) { throw new WorkerHostError(`restricted read path ${path} is broader than an explicit envelope`); } if (seen.has(path)) continue; @@ -274,7 +274,7 @@ function restrictedMounts(envelope: RestrictedEnvelope, brain: string): string[] && (directory.mode & 0o7777) === (separateIdentity ? 0o750 : 0o700) && (socket.mode & 0o7777) === (separateIdentity ? 0o660 : 0o600) && (!separateIdentity || directory.gid === process.getgid?.() && socket.gid === process.getgid?.()) - && !within(brain, inference) && !within(inference, brain); + && !holds(brain, inference) && !holds(inference, brain); } catch { /* Missing, aliased or unreadable IPC is never launch authority. */ } if (!valid) throw new WorkerHostError("the inference relay requires its private directory and server-owned socket"); argv.push("--ro-bind", inference, WORKER_INFERENCE_DIR); @@ -295,7 +295,7 @@ function transportMounts(envelope: NonNullable, brain for (let index = 0; index < argv.length; index++) { if (argv[index] !== "--bind" && argv[index] !== "--ro-bind") continue; const source = realpathSync(argv[index + 1]!); - if (within(source, brain) || within(brain, source)) throw new WorkerHostError("a transport mount must not expose the brain or its ancestors"); + if (holds(source, brain) || holds(brain, source)) throw new WorkerHostError("a transport mount must not expose the brain or its ancestors"); index += 2; } argv.push("--dir", MAINTENANCE_HOME, @@ -372,7 +372,7 @@ function serverSocketDirectory(requested: string, socket: string, brain: string) && (directoryInfo.mode & 0o7777) === (separateIdentity ? 0o750 : 0o700) && (socketInfo.mode & 0o7777) === (separateIdentity ? 0o660 : 0o600) && (!separateIdentity || directoryInfo.gid === serverGid && socketInfo.gid === serverGid) - && !within(brain, directory) && !within(directory, brain)) return directory; + && !holds(brain, directory) && !holds(directory, brain)) return directory; } catch { /* Missing, aliased or unreadable IPC is never launch authority. */ } throw new WorkerHostError("the provider relay requires its private server-owned directory and socket"); } @@ -405,9 +405,9 @@ function maintenanceMounts(envelope: MaintenanceEnvelope, brain: string, egressM if (info.uid !== serverUid) throw new WorkerHostError("a private mask ancestor is not server-owned"); covered = parent; } - if (covered !== path && (within(covered, brain) || within(brain, covered) || envelope.readPaths.some(requested => { + if (covered !== path && (holds(covered, brain) || holds(brain, covered) || envelope.readPaths.some(requested => { const runtime = realpathSync(requested); - return within(covered, runtime) || within(runtime, covered); + return holds(covered, runtime) || holds(runtime, covered); }))) throw new WorkerHostError("a private mask ancestor overlaps the brain or required runtime"); return covered; }; @@ -417,7 +417,9 @@ function maintenanceMounts(envelope: MaintenanceEnvelope, brain: string, egressM try { path = realpathSync(requested); } catch { continue; } const info = statSync(path); if (!info.isDirectory() && !info.isFile()) continue; - if (path === "/" || within(brain, path)) { + // Masking `/` is refused for itself, not as a holder of the brain: a mask + // over another ancestor of the brain is allowed, as the brain is bound back. + if (path === "/" || holds(brain, path)) { throw new WorkerHostError(`a maintenance worker cannot mask ${path}: it is the brain, inside it or the root`); } // Host /tmp is already absent behind the worker's private tmpfs. A @@ -466,7 +468,9 @@ function maintenanceMounts(envelope: MaintenanceEnvelope, brain: string, egressM if (envelope.home) { if (!envelope.credentials) throw new WorkerHostError("only a credentialed maintenance worker sees the server's home"); const home = realpathSync(envelope.home.path); - if (home === "/" || within(brain, home)) throw new WorkerHostError("the server's home must be a directory outside the brain"); + // `/` is refused for itself: a home that holds the brain is ordinary, but + // one at `/` would bind the whole host back over the masks. + if (home === "/" || holds(brain, home)) throw new WorkerHostError("the server's home must be a directory outside the brain"); if (envelope.home.overlay) throw new WorkerHostError("maintenance HOME overlays are not bounded; use read-only HOME and bounded XDG directories"); argv.push("--ro-bind", home, home); // A mask inside the home (the UI database's directory below it) is laid @@ -478,13 +482,13 @@ function maintenanceMounts(envelope: MaintenanceEnvelope, brain: string, egressM if (!envelope.credentials || envelope.maskEnvFiles) argv.push(...maintenanceEnvMasks(brain, brain)); for (const requested of envelope.writeFiles ?? []) { const real = realpathSync(requested); - if (!lstatSync(real).isFile() || within(brain, real)) throw new WorkerHostError("a maintenance worker's writable file must be a regular file outside the brain"); + if (!lstatSync(real).isFile() || holds(brain, real)) throw new WorkerHostError("a maintenance worker's writable file must be a regular file outside the brain"); argv.push("--bind", real, real); } for (const requested of envelope.writeDirectories ?? []) { const info = lstatSync(requested); const real = realpathSync(requested); - if (!info.isDirectory() || info.isSymbolicLink() || real === "/" || within(brain, real) || within(real, brain)) { + if (!info.isDirectory() || info.isSymbolicLink() || holds(brain, real) || holds(real, brain)) { throw new WorkerHostError("a maintenance worker's writable storage must be an unlinked directory outside the brain"); } argv.push("--bind", real, real); @@ -519,8 +523,7 @@ export function workerCommand(input: WorkerLaunch): string[] { } const brain = realpathSync(input.brainPath); const scratch = input.scratchPath ? realpathSync(normalize(input.scratchPath)) : WORKER_SCRATCH; - if (!isAbsolute(scratch) || scratch === brain || scratch.startsWith(`${brain}/`) - || brain.startsWith(`${scratch}/`) || scratch === "/" || brain === "/" || brain === "/tmp") { + if (!isAbsolute(scratch) || holds(brain, scratch) || holds(scratch, brain) || brain === "/tmp") { throw new WorkerHostError("scratch must be a separate location outside the authoritative brain and its ancestors"); } if (input.turnTempBytes !== undefined) { @@ -562,7 +565,7 @@ export function workerCommand(input: WorkerLaunch): string[] { && (directoryInfo.mode & 0o7777) === (separateIdentity ? 0o750 : 0o700) && (socketInfo.mode & 0o7777) === (separateIdentity ? 0o660 : 0o600) && (!separateIdentity || directoryInfo.gid === serverGid && socketInfo.gid === serverGid) - && !within(brain, directory) && !within(directory, brain); + && !holds(brain, directory) && !holds(directory, brain); } catch { /* Missing, aliased or unreadable IPC is never launch authority. */ } if (!valid) throw new WorkerHostError("egress transport requires its private server-owned proxy directory and socket"); egressMounts = ["--ro-bind", directory, WORKER_EGRESS_DIR]; @@ -601,7 +604,7 @@ export function workerCommand(input: WorkerLaunch): string[] { const reservedRuntimePaths = ["/proc", "/dev", scratch, WORKER_STATE, ...(emptyHome ? [WORKER_EMPTY_HOME] : []), WORKER_AREA_ROOT, WORKER_DATA_ROOT, WORKER_WORKTREE_ROOT, WORKER_REFERENCE_ROOT, WORKER_XDG_HOME, WORKER_INFERENCE_DIR, WORKER_EGRESS_DIR, WORKER_PROVIDER_RELAY_DIR, MAINTENANCE_HOME, ...Object.values(MAINTENANCE_XDG_DIRS), "/tmp/brain-maintenance-output", ...(maintenance?.output ? [maintenance.output.target] : []), ...(transport ? [transport.mirror, ...(transport.writePaths ?? [])] : [])]; - const runtimeEntries = input.command.filter((path, index) => isAbsolute(path) && existsSync(path) && (index === 0 || !reservedRuntimePaths.some(reserved => within(reserved, runtimeCanonicalName(path)) || within(runtimeCanonicalName(path), reserved)))); + const runtimeEntries = input.command.filter((path, index) => isAbsolute(path) && existsSync(path) && (index === 0 || !reservedRuntimePaths.some(reserved => holds(reserved, runtimeCanonicalName(path)) || holds(runtimeCanonicalName(path), reserved)))); const runtimePaths = input.restricted?.readPaths ?? transport?.readPaths ?? maintenance?.readPaths ?? input.sandbox?.readPaths ?? [...restrictedReadPaths(runtimeEntries), ...runtimeEntries]; // Validate names before stat/mount planning too: a missing executable under @@ -727,6 +730,12 @@ export function workerCommand(input: WorkerLaunch): string[] { /** Whether `path` is `dir` or lies below it. */ export const within = (dir: string, path: string) => isWithin(dir, path); +/** + * {@link within} in the deny direction (#3422): a `dir` of `/` holds every + * absolute path, so a refusal of "the brain or its ancestors" refuses `/` + * without a check of its own. + */ +export const holds = (dir: string, path: string) => isWithin(dir, path, { trailingSeparator: "boundary" }); /** Resolve aliases even when the final installed entry is not present yet. */ function runtimeCanonicalName(requested: string): string { @@ -745,7 +754,7 @@ function runtimeCanonicalName(requested: string): string { function validateRuntimePlacement(requested: string, reserved: readonly string[]): void { if (!isAbsolute(requested)) throw new WorkerHostError("owned runtime paths must be absolute"); for (const path of new Set([normalize(requested), runtimeCanonicalName(requested)])) { - const conflict = reserved.find(privatePath => within(path, privatePath) || within(privatePath, path)); + const conflict = reserved.find(privatePath => holds(path, privatePath) || holds(privatePath, path)); if (conflict) throw new WorkerHostError(`owned runtime path ${requested} (${path}) collides with reserved private worker path ${conflict}; install the runtime in a separate noncolliding directory`); } } @@ -838,7 +847,7 @@ function sandboxMounts(input: WorkerLaunch, brain: string, scratch: string, stat const path = mount.path; const info = lstatSync(path, { throwIfNoEntry: false }); if (path !== join(brain, rel) || !info?.isDirectory() || realpathSync(path) !== path - || within(path, scratch) || within(scratch, path) || (state !== undefined && (within(path, state) || within(state, path)))) { + || holds(path, scratch) || holds(scratch, path) || (state !== undefined && (holds(path, state) || holds(state, path)))) { throw new WorkerHostError(`the writable ${name} area must be a real directory at its own path inside the brain`); } out.binds.push("--bind", input.areaOutput ? join(input.areaOutput.source, rel) : path, @@ -858,7 +867,7 @@ function sandboxMounts(input: WorkerLaunch, brain: string, scratch: string, stat if (sandbox.restricted || input.restricted || input.maintenance || input.transport || workerProfile(sandbox) === "restricted") throw new WorkerHostError("only an interactive governed or strict worker binds a managed worktree generation"); if (!isAbsolute(source) || !info?.isDirectory() || realpathSync(source) !== normalize(source) || info.uid !== 0 || (info.mode & 0o7777) !== 0o755 - || within(brain, source) || within(source, brain)) + || holds(brain, source) || holds(source, brain)) throw new WorkerHostError("a managed worktree generation must be its pool's root-owned directory outside the brain"); out.binds.push("--bind", source, WORKER_WORKTREE_ROOT); } @@ -871,7 +880,7 @@ function sandboxMounts(input: WorkerLaunch, brain: string, scratch: string, stat if (sandbox.restricted || input.restricted || input.maintenance || input.transport || workerProfile(sandbox) === "restricted") throw new WorkerHostError("only an interactive governed or strict worker binds a reference source view"); if (!isAbsolute(source) || !info?.isDirectory() || realpathSync(source) !== normalize(source) || info.uid !== 0 || (info.mode & 0o7777) !== 0o755 - || within(brain, source) || within(source, brain)) + || holds(brain, source) || holds(source, brain)) throw new WorkerHostError("a reference source view must be its pool's root-owned directory outside the brain"); out.binds.push("--ro-bind", source, `${WORKER_REFERENCE_ROOT}/${domain}`); } diff --git a/packages/ui-sdk/src/server/worker-rtk.ts b/packages/ui-sdk/src/server/worker-rtk.ts index 4daf8220b8..2f84acb3a7 100644 --- a/packages/ui-sdk/src/server/worker-rtk.ts +++ b/packages/ui-sdk/src/server/worker-rtk.ts @@ -19,7 +19,8 @@ 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 isWithin(root, path); } +/** Whether `path` is `root` or below it; a `root` of `/` holds every absolute path (#3422), as a mount at `/` holds every binary. */ +export function within(root: string, path: string): boolean { return isWithin(root, path, { trailingSeparator: "boundary" }); } /** ELF64 native static executables, including dependency-free static PIE. */ export function isStaticNativeElf(path: string): boolean { const bytes = readFileSync(path); @@ -101,7 +102,7 @@ export async function rewriteWorkerRtk(worker: LaunchedWorker | undefined, comma const fields = line.split(" "); const path = fields[4]!.replace(/\\([0-7]{3})/g, (_match, octal: string) => String.fromCharCode(parseInt(octal, 8))); return { path, options: fields[5]!.split(",") }; - }).filter(mount => mount.path === "/" || within(mount.path, binary)).sort((a,b) => b.path.length - a.path.length); + }).filter(mount => within(mount.path, binary)).sort((a,b) => b.path.length - a.path.length); if (!mounts[0]?.options.includes("ro") || mounts[0]?.options.includes("noexec")) return command; const host = statSync(binary); if (host.dev !== info.dev || host.ino !== info.ino || ![0, process.geteuid!()].includes(host.uid) || host.nlink !== 1 || (host.mode & 0o6022) || host.size > 32 * 1024 * 1024 || !isStaticNativeElf(binary)) return command; diff --git a/packages/ui-sdk/tests/containment-rows.test.ts b/packages/ui-sdk/tests/containment-rows.test.ts index c847b959e0..34b975a46f 100644 --- a/packages/ui-sdk/tests/containment-rows.test.ts +++ b/packages/ui-sdk/tests/containment-rows.test.ts @@ -1,10 +1,11 @@ /** * 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. + * rel)` gives the strictest answer in every row since #3422, as core's + * `safeResolve` does: it refuses an absolute request, any `..` segment, `:` or + * `\\` in a segment, a dangling link and a path that leaves through one link + * and comes back through another. The predicates each keep their own argument + * order, equality and trailing-separator answers; a deny-direction predicate + * takes a root `/` as holding every absolute path (#3422). */ import { afterAll, describe, expect, test } from "bun:test"; import { mkdirSync, mkdtempSync, realpathSync, renameSync, rmSync, symlinkSync, writeFileSync } from "fs"; @@ -16,7 +17,7 @@ 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 { holds as launcherHolds, prepareWorkerSandbox, within as launcherWithin, workerCommand, type WorkerLaunch } from "../src/server/worker-launcher"; import { within as rtkWithin } from "../src/server/worker-rtk"; import { within as turnTempWithin } from "../src/server/worker-turn-temp"; @@ -57,28 +58,35 @@ describe("ui-sdk resolveInRepo(root, rel): its resolver row", () => { ["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"], + // `..` is refused even when the result stays inside (#3422). + ["notes/../notes/a.md", "refused"], + ["notes/sub/..", "refused"], ["notes/../../x", "refused"], // Sibling prefix: `brain-other` starts with `brain`. ["../brain-other/secret.md", "refused"], - // Absolute: refused even inside the root (core accepts it). + // Absolute: refused even inside the root. [join(root, "notes/a.md"), "refused"], + [root, "refused"], ["/etc/passwd", "refused"], - // Windows syntax is not checked. - ["a:b", "brain/a:b"], - ["a\\b", "brain/a\\b"], + // Windows syntax is refused in any segment (#3422). + ["a:b", "refused"], + ["notes/a:b.md", "refused"], + ["a\\b", "refused"], + ["\\notes", "refused"], ["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"], + // A dangling link is refused wherever it points (#3422). + ["dangling-in", "refused"], + ["dangling-in/x", "refused"], ["dangling-out", "refused"], ["cycle-a", "refused"], ["cycle-a/x", "refused"], - ["bounce/back/a.md", "brain/notes/a.md"], + // Every existing component must stay inside: out and back is refused (#3422). + ["bounce/back/a.md", "refused"], + ["bounce/back", "refused"], [".brain", "brain/.brain"], [".brain/scratch/s.txt", "brain/.brain/scratch/s.txt"], [".brain/scratch/link", "brain/notes"], @@ -139,7 +147,9 @@ 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], + // Deny direction (#3422): root `/` holds every absolute path. + ["worker-launcher holds(dir, path)", launcherHolds, TRAILING_TOLERATED], + ["worker-rtk within(root, path)", rtkWithin, TRAILING_TOLERATED], ["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], @@ -163,3 +173,52 @@ describe("ui-sdk containment predicates: their matrix rows", () => { expect(poolInside("/a", "/a/b")).toBe(false); }); }); + +/** + * Each deny site that refuses "the brain or its ancestors" refuses a `/` + * source (#3422). `/` is root-owned and 0755 on a Linux host, so it passes + * the ownership and mode checks before each containment refusal; under the + * old literal rule `/` held nothing below it and every one of these was + * accepted, binding the whole host, brain included, into the worker. + */ +describe("worker-launcher deny sites refuse a `/` source (#3422)", () => { + const linux = process.platform === "linux" && Boolean(Bun.which("bwrap")); + const brain = realpathSync(root); + const launch = (extra: Partial) => () => workerCommand({ brainPath: brain, command: [process.execPath], env: {}, ...extra }); + + // A `/` read path is refused first by the runtime placement check, the + // deny site that keeps runtime paths off the reserved private mounts: `/` + // holds `/proc`. That check shadows the transport bind check + // (`transportMounts`) and the restricted envelope's own list for `/`. + const placement = "owned runtime path / (/) collides with reserved private worker path /proc"; + test.skipIf(!linux)("a transport read path of `/` (worker-launcher validateRuntimePlacement)", () => { + const mirror = join(base, "transport-mirror"); + mkdirSync(mirror, { recursive: true }); + expect(launch({ transport: { mirror, readPaths: ["/"] } })).toThrow(placement); + }); + + test.skipIf(!linux)("a restricted read path of `/` (worker-launcher validateRuntimePlacement)", () => { + expect(launch({ restricted: { readPaths: ["/"], inferenceDir: base } })).toThrow(placement); + }); + + test.skipIf(!linux)("a managed worktree generation at `/` (worker-launcher sandboxMounts)", () => { + const sandbox = prepareWorkerSandbox(brain, { profile: "governed", areas: [] }); + expect(launch({ sandbox: { ...sandbox, worktrees: { source: "/" } } })) + .toThrow("a managed worktree generation must be its pool's root-owned directory outside the brain"); + }); + + test.skipIf(!linux)("a reference source view at `/` (worker-launcher sandboxMounts)", () => { + const sandbox = prepareWorkerSandbox(brain, { profile: "governed", areas: [] }); + expect(launch({ sandbox: { ...sandbox, references: { public: "/" } } })) + .toThrow("a reference source view must be its pool's root-owned directory outside the brain"); + }); + + test.skipIf(!linux)("a maintenance worker's writable directory at `/` (worker-launcher maintenanceMounts)", () => { + expect(launch({ maintenance: { network: false, credentials: false, readPaths: [process.execPath], writeDirectories: ["/"] } })) + .toThrow("a maintenance worker's writable storage must be an unlinked directory outside the brain"); + }); + + test.skipIf(!linux)("a scratch path of `/` (worker-launcher workerCommand)", () => { + expect(launch({ scratchPath: "/" })).toThrow("scratch must be a separate location outside the authoritative brain and its ancestors"); + }); +}); diff --git a/packages/ui-sdk/tests/worker-launcher.test.ts b/packages/ui-sdk/tests/worker-launcher.test.ts index eef38cef17..fcd2719afa 100644 --- a/packages/ui-sdk/tests/worker-launcher.test.ts +++ b/packages/ui-sdk/tests/worker-launcher.test.ts @@ -356,7 +356,9 @@ os.execve(${JSON.stringify(boot.command[0])}, ${JSON.stringify(boot.command)}, $ try { const relay = f.relay(); expect(() => workerCommand({ brainPath: f.brain, command: [process.execPath], env: {}, - restricted: { readPaths: [path === "ancestor" ? f.root : path], inferenceDir: relay } })).toThrow("broader than an explicit envelope"); + restricted: { readPaths: [path === "ancestor" ? f.root : path], inferenceDir: relay } })) + // `/` holds the reserved private mounts (#3422), so the runtime placement check refuses it first. + .toThrow(path === "/" ? "collides with reserved private worker path" : "broader than an explicit envelope"); } finally { f.cleanup(); } }); diff --git a/packages/ui-server/src/brain/host-boundary.ts b/packages/ui-server/src/brain/host-boundary.ts index 7163beafa4..b8ea1c1693 100644 --- a/packages/ui-server/src/brain/host-boundary.ts +++ b/packages/ui-server/src/brain/host-boundary.ts @@ -173,7 +173,8 @@ 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) => isWithin(dir, path); +/** Deny direction (#3422): whether `path` is `dir` or below it; a `dir` of `/` holds every absolute path. */ +export const within = (dir: string, path: string) => isWithin(dir, path, { trailingSeparator: "boundary" }); 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 6ca73fc2a8..78dcb46ccc 100644 --- a/packages/ui-server/src/brain/operational-state.ts +++ b/packages/ui-server/src/brain/operational-state.ts @@ -31,11 +31,10 @@ function canonical(path: string, links = 0): string { return current; } /** - * 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. + * A deny check, under the deny-direction rule (#3422): a brain at `/` holds + * every absolute path, so all state counts as inside it. */ -export const within = (root: string, path: string) => root === "/" || isWithin(root, path); +export const within = (root: string, path: string) => isWithin(root, path, { trailingSeparator: "boundary" }); /** 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 9cdab8545c..77a0932045 100644 --- a/packages/ui-server/src/brain/sync-mirror.ts +++ b/packages/ui-server/src/brain/sync-mirror.ts @@ -27,7 +27,8 @@ 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) => isWithin(root, path); +/** Deny direction (#3422): whether `path` is `root` or below it; a `root` of `/` holds every absolute path. */ +export const within = (root: string, path: string) => isWithin(root, path, { trailingSeparator: "boundary" }); const mirrorLocks = createKeyedLock(); /** One host-private mirror per brain/database; standalone clients get private temporary state. */ diff --git a/packages/ui-server/src/files/walker.ts b/packages/ui-server/src/files/walker.ts index 3363b7252c..b9f5db630d 100644 --- a/packages/ui-server/src/files/walker.ts +++ b/packages/ui-server/src/files/walker.ts @@ -64,11 +64,10 @@ export function isScratchPath(rel: string): boolean { /** * 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). + * a dangling link is refused wherever it points; and a root whose realpath + * fails refuses everything (#3422), as core and the SDK do. */ -const SERVER_CONTAINMENT = { missingRoot: "lexical", danglingLinks: "refuse", components: "every" } as const satisfies ContainmentPolicy; +const SERVER_CONTAINMENT = { missingRoot: "refuse", danglingLinks: "refuse", components: "every" } as const satisfies ContainmentPolicy; /** * Resolve a repo-relative path to an absolute path, rejecting any escape diff --git a/packages/ui-server/tests/containment-rows.test.ts b/packages/ui-server/tests/containment-rows.test.ts index 6381f63cf5..83a1a574c9 100644 --- a/packages/ui-server/tests/containment-rows.test.ts +++ b/packages/ui-server/tests/containment-rows.test.ts @@ -2,12 +2,12 @@ * 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`. + * existing component must stay inside, not only the final path; a root whose + * realpath fails refuses everything (#3422); 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 and + * normalisation answers; a deny-direction predicate takes a root `/` as + * holding every absolute path (#3422). */ import { afterAll, describe, expect, test } from "bun:test"; import { mkdirSync, mkdtempSync, realpathSync, renameSync, rmSync, symlinkSync, writeFileSync } from "fs"; @@ -15,9 +15,9 @@ 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 { createHostBoundary, 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 { syncTransportCommand, within as syncMirrorWithin } from "../src/brain/sync-mirror"; import { isScratchPath, safeResolve } from "../src/files/walker"; import { inside as processInside } from "../src/storage/process"; @@ -109,10 +109,11 @@ describe("ui-server safeResolve(rel, root): its resolver row", () => { 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"); + test("a root whose realpath fails refuses everything (#3422)", async () => { + expect(await answer("notes/a.md", join(base, "nope"))).toBe("refused"); + expect(await answer("", join(base, "nope"))).toBe("refused"); expect(await answer("x", join(root, "dangling-in"))).toBe("refused"); - expect(await answer("x", join(root, "file.md/x"))).toBe("error ENOTDIR"); + expect(await answer("x", join(root, "file.md/x"))).toBe("refused"); }); test("each call reads the filesystem again: a directory swapped for an escaping link is refused", async () => { @@ -147,7 +148,9 @@ const PREDICATE_CASES: [string, string][] = [ ["/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"; +// Deny direction (#3422): root `/` holds every absolute path, as does a root +// written with its trailing separator. +const DENY_BOUNDARY = "T T - - 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. A @@ -156,10 +159,9 @@ const rows: [string, (root: string, path: string) => boolean, string][] = [ ["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. - ["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], + ["operational-state within(root, path)", operationalStateWithin, DENY_BOUNDARY], + ["sync-mirror within(root, path)", syncMirrorWithin, DENY_BOUNDARY], + ["host-boundary within(dir, path)", hostBoundaryWithin, DENY_BOUNDARY], ]; describe("ui-server containment predicates: their matrix rows", () => { @@ -169,3 +171,23 @@ describe("ui-server containment predicates: their matrix rows", () => { }); } }); + +/** + * Each deny site that refuses "the brain or its ancestors" refuses `/` + * (#3422). Under the old literal rule `/` held nothing below it, so a local + * sync remote of `/` was mounted writable and host credential state at `/` + * was accepted beside the brain. + */ +describe("ui-server deny sites refuse `/` (#3422)", () => { + test.skipIf(!Bun.which("git", { PATH: "/usr/bin:/bin" }))("a local sync remote at `/` (sync-mirror syncTransportCommand)", () => { + for (const remote of ["/", "file:///"]) { + expect(() => syncTransportCommand({ brain: root, mirror: join(base, "mirror"), remote, env: {}, args: [] })) + .toThrow("the sync transport must not mount the brain or its ancestors"); + } + }); + + test("host credential state at `/` (host-boundary createHostBoundary)", () => { + expect(() => createHostBoundary({ brainPath: root, credentialDomain: { directory: "/" } })) + .toThrow("Host credential state must be separate from repository input."); + }); +}); From 14fa07f65872cad4ad73acd8e3ef9383c032294e Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 3 Nov 2026 11:43:28 +0000 Subject: [PATCH 2/3] CONTRACT: fix(cli): convert absolute CLI path arguments inside the brain to brain-relative (#3422) Maintainer ruling of 2026-11-03 on #3465: safeResolve stays strict, and the CLI turns an absolute path argument inside the brain into a brain-relative one before calling it. brainRelativeArgument (core lib, exported from @schlessera/brain/module) does that once for every CLI path argument: read, import --stamp, archive, process, render (input, --out), eval --out, geo (track, --compare, --along, map --out), okf export --out, image (--out, --ref, --mask), diagram export/build (input, --out), travel photo --to and travel route (source, --to). An absolute path outside the brain, or one with a .. segment, stays absolute and is refused; one through a symlink that leaves the brain is refused by safeResolve. Restores the eval and image tests that accept an absolute --out inside the brain. Co-Authored-By: Claude Opus 5.5 --- api-report/core.txt | 3 + packages/core/src/cli/commands/archive.ts | 3 +- packages/core/src/cli/commands/eval.ts | 4 +- packages/core/src/cli/commands/geo.ts | 6 +- packages/core/src/cli/commands/import.ts | 4 +- packages/core/src/cli/commands/okf.ts | 3 +- packages/core/src/cli/commands/process.ts | 4 +- packages/core/src/cli/commands/read.ts | 4 +- packages/core/src/cli/commands/render.ts | 8 +- packages/core/src/lib/safe-path.ts | 31 +++++++ packages/core/src/module.ts | 2 +- .../core/tests/cli-path-arguments.test.ts | 87 +++++++++++++++++++ packages/core/tests/containment-rows.test.ts | 44 +++++++++- packages/core/tests/eval-cli.test.ts | 12 ++- packages/module-diagrams/src/export-cli.ts | 6 +- packages/module-images/src/cli.ts | 5 +- packages/module-images/tests/scratch.test.ts | 20 ++++- packages/module-travel/src/cli.ts | 4 +- packages/module-travel/src/route.ts | 4 +- 19 files changed, 219 insertions(+), 35 deletions(-) create mode 100644 packages/core/tests/cli-path-arguments.test.ts diff --git a/api-report/core.txt b/api-report/core.txt index 84fd01b53b..e6c3bd4605 100644 --- a/api-report/core.txt +++ b/api-report/core.txt @@ -159,6 +159,7 @@ export "./module" (./src/module.ts) type WriteFileSafelyOptions WriteRefusedError assertScratchWritable + brainRelativeArgument buildTaxonomy configurationRoot geminiCompletions @@ -1425,6 +1426,8 @@ signatures (every public export and the types it is made of) }, z.core.$strict>>>; }, z.core.$strict>>; }, z.core.$strict>; + brainRelativeArgument (packages/core/src/lib/safe-path.ts) + export function brainRelativeArgument(root: string, arg: string): string; buildPathMatcher (packages/core/src/lib/reranker.ts) export function buildPathMatcher(patterns: readonly string[] | undefined): ((path: string) => boolean) | undefined; buildTaxonomy (packages/core/src/lib/taxonomy.ts) diff --git a/packages/core/src/cli/commands/archive.ts b/packages/core/src/cli/commands/archive.ts index 2bfd1ac418..30c8eb8ad2 100644 --- a/packages/core/src/cli/commands/archive.ts +++ b/packages/core/src/cli/commands/archive.ts @@ -1,6 +1,7 @@ import type { Database } from "bun:sqlite"; import { archiveDocument } from "../../lib/archiver.js"; +import { brainRelativeArgument } from "../../lib/safe-path.js"; import { indexAll } from "../../lib/indexer.js"; import type { CoreCommand } from "../types.js"; import { emit, embeddingDims, parseArgs, UsageError } from "../io.js"; @@ -14,7 +15,7 @@ export const archiveCommand: CoreCommand = { helpBlock: HELP, async run(args, cli) { const { args: pos, flags } = parseArgs(args); - const relPath = pos[0]; + const relPath = pos[0] && brainRelativeArgument(cli.brain.root, pos[0]); if (!relPath) { throw new UsageError("Usage: brain archive [--dry-run]"); } diff --git a/packages/core/src/cli/commands/eval.ts b/packages/core/src/cli/commands/eval.ts index b5b1b674fc..6daf1104f7 100644 --- a/packages/core/src/cli/commands/eval.ts +++ b/packages/core/src/cli/commands/eval.ts @@ -36,7 +36,7 @@ import type { ScoreRow, SetHeader, } from "../../lib/retrieval-eval.js"; -import { resolveWritable, safeResolve, writeFileSafely } from "../../lib/safe-path.js"; +import { brainRelativeArgument, resolveWritable, safeResolve, writeFileSafely } from "../../lib/safe-path.js"; import { isInScratch, isWriteRefusal, writeScratchFile } from "../../lib/scratch.js"; import { hybridSearch, type SearchDeps } from "../../lib/search-engine.js"; import type { EmbeddingProvider } from "../../lib/seams.js"; @@ -631,7 +631,7 @@ async function runEval(args: string[], cli: CliContext): Promise { if (flags.lint === true) return lintSet(cli.json, root, setPath, redact); // Everything the CLI writes stays inside the brain (integration contract, // "Containment"): checked before any search runs, and again at the write. - const outRel = typeof flags.out === "string" ? flags.out : undefined; + const outRel = typeof flags.out === "string" ? brainRelativeArgument(root, flags.out) : undefined; if (outRel !== undefined && !resolveWritable(root, outRel)) { throw new UsageError(`Output path is not inside the brain: ${outRel}`); } diff --git a/packages/core/src/cli/commands/geo.ts b/packages/core/src/cli/commands/geo.ts index 1eabc3f064..fcbfe9b815 100644 --- a/packages/core/src/cli/commands/geo.ts +++ b/packages/core/src/cli/commands/geo.ts @@ -6,7 +6,7 @@ import { nearestTrackPoint, parseTrackGpx, routePoint, summarizeTrack, trackCove import { GeoClient, type GeoResult, type GeocodeCandidate, type PoiResult, type RoutingResult, type StaticMapInput, type StaticMapPin, type StaticMapResult } from "@schlessera/brain-geo/server"; import { resolveGeoConfig } from "../../lib/geo-config.js"; -import { safeResolve, resolveWritable, writeFileSafely } from "../../lib/safe-path.js"; +import { brainRelativeArgument, safeResolve, resolveWritable, writeFileSafely } from "../../lib/safe-path.js"; import { assertScratchWritable, isInScratch, isWriteRefusal, pruneScratch, writeScratchFile } from "../../lib/scratch.js"; import { parseArgs, UsageError, type Flags } from "../io.js"; import type { CliContext, CoreCommand } from "../types.js"; @@ -97,7 +97,7 @@ function usage(fn: () => T): T { try { return fn(); } catch (error) { throw new UsageError((error as Error).message); } } async function readTrack(root: string, path: string): Promise<{ track: ParsedTrack; summary: TrackSummary }> { - const absolute = safeResolve(root, path); + const absolute = safeResolve(root, brainRelativeArgument(root, path)); if (!absolute) throw new UsageError(`Track path must remain inside the brain: ${path}`); const file = Bun.file(absolute); if (!await file.exists()) throw new UsageError(`Track file does not exist: ${path}`); @@ -207,7 +207,7 @@ export const geoCommand: CoreCommand = { async function runMap(args: string[], argv: string[], flags: Flags, cli: CliContext, geo: GeoClient): Promise { if (cli.brain.configPath === null) throw new UsageError("Map refuses to write in an uninitialized directory; run brain init first."); - const root = realpathSync(cli.brain.root), out = option(flags, "out", true)!; + const root = realpathSync(cli.brain.root), out = brainRelativeArgument(cli.brain.root, option(flags, "out", true)!); if (extname(out).toLowerCase() !== ".png") throw new UsageError("Map --out must name a PNG file."); const absolute = resolveWritable(root, out); if (!absolute) throw new UsageError("Map output must remain inside the brain."); diff --git a/packages/core/src/cli/commands/import.ts b/packages/core/src/cli/commands/import.ts index 4c88a47772..e9bb42e3c9 100644 --- a/packages/core/src/cli/commands/import.ts +++ b/packages/core/src/cli/commands/import.ts @@ -3,7 +3,7 @@ import { resolve } from "path"; import { Glob } from "bun"; import { stringifyDocument } from "../../lib/frontmatter.js"; -import { safeResolve, writeFileSafely } from "../../lib/safe-path.js"; +import { brainRelativeArgument, safeResolve, writeFileSafely } from "../../lib/safe-path.js"; import type { CoreCommand } from "../types.js"; import { emit, parseArgs, UsageError } from "../io.js"; @@ -33,7 +33,7 @@ export const importCommand: CoreCommand = { throw new UsageError("Usage: brain import --stamp "); } - const base = safeResolve(cli.brain.root, dir); + const base = safeResolve(cli.brain.root, brainRelativeArgument(cli.brain.root, dir)); if (base === null) { throw new UsageError(`--stamp directory escapes the brain root: ${dir}`); } diff --git a/packages/core/src/cli/commands/okf.ts b/packages/core/src/cli/commands/okf.ts index bd211ab44a..716bbcccd5 100644 --- a/packages/core/src/cli/commands/okf.ts +++ b/packages/core/src/cli/commands/okf.ts @@ -8,6 +8,7 @@ import { type OkfExportReport, } from "../../lib/okf-exporter.js"; import type { CoreCommand } from "../types.js"; +import { brainRelativeArgument } from "../../lib/safe-path.js"; import { emit, parseArgs, UsageError } from "../io.js"; const HELP = `brain okf — export and validate Open Knowledge Format v0.1 bundles @@ -81,7 +82,7 @@ export const okfCommand: CoreCommand = { const report = await exportOkfBundle({ root: cli.brain.root, taxonomy: cli.brain.taxonomy, - outDir: typeof flags.out === "string" ? flags.out : undefined, + outDir: typeof flags.out === "string" ? brainRelativeArgument(cli.brain.root, flags.out) : undefined, include: repeatedValues(argv, "include"), exclude: repeatedValues(argv, "exclude"), copyAssets: flags["no-assets"] !== true, diff --git a/packages/core/src/cli/commands/process.ts b/packages/core/src/cli/commands/process.ts index d0e8e36a8c..9c0686d7ce 100644 --- a/packages/core/src/cli/commands/process.ts +++ b/packages/core/src/cli/commands/process.ts @@ -7,7 +7,7 @@ import { parseFrontmatter } from "@schlessera/brain-common/internal/frontmatter" import type { CompletionProvider } from "../../lib/seams.js"; import { hybridSearch, type SearchDeps } from "../../lib/search-engine.js"; -import { safeResolve } from "../../lib/safe-path.js"; +import { brainRelativeArgument, safeResolve } from "../../lib/safe-path.js"; import { openDatabase } from "../../lib/db.js"; import type { CliContext, CoreCommand } from "../types.js"; import type { SearchOptions } from "../../lib/types.js"; @@ -188,7 +188,7 @@ export const processCommand: CoreCommand = { return; } - const notePath = pos[0]; + const notePath = pos[0] && brainRelativeArgument(cli.brain.root, pos[0]); if (!notePath) { throw new UsageError("Usage: brain process [--keep-note] [--all]"); } diff --git a/packages/core/src/cli/commands/read.ts b/packages/core/src/cli/commands/read.ts index d5a2d6aadc..5d310f97ec 100644 --- a/packages/core/src/cli/commands/read.ts +++ b/packages/core/src/cli/commands/read.ts @@ -1,7 +1,7 @@ import { existsSync, readFileSync } from "fs"; import { readDocumentPart, SectionNotFoundError } from "../../lib/document-parts.js"; -import { safeResolve } from "../../lib/safe-path.js"; +import { brainRelativeArgument, safeResolve } from "../../lib/safe-path.js"; import type { CoreCommand } from "../types.js"; import { parseArgs, UsageError } from "../io.js"; @@ -23,7 +23,7 @@ export const readCommand: CoreCommand = { helpBlock: HELP, async run(args, cli) { const { args: pos, flags } = parseArgs(args); - const relPath = pos[0]; + const relPath = pos[0] && brainRelativeArgument(cli.brain.root, pos[0]); if (!relPath) { throw new UsageError("Usage: brain read "); } diff --git a/packages/core/src/cli/commands/render.ts b/packages/core/src/cli/commands/render.ts index d27b5d1fdc..c0864e2454 100644 --- a/packages/core/src/cli/commands/render.ts +++ b/packages/core/src/cli/commands/render.ts @@ -11,7 +11,7 @@ import { documentTitle, isFullDocument, prepareStaticDocument } from "@schlesser import { DOCUMENT_KINDS, readSkeleton, resolveKind } from "@schlessera/brain-render-template/kinds"; import { collectModuleRenderers } from "../../lib/module-renderers.js"; -import { resolveWritable, writeFileSafely } from "../../lib/safe-path.js"; +import { brainRelativeArgument, resolveWritable, writeFileSafely } from "../../lib/safe-path.js"; import { assertScratchWritable, isInScratch, @@ -195,7 +195,7 @@ function runReference(pos: string[], flags: Record, js export function validateRenderInput(args: string[], root: string): void { const { args: pos, flags } = parseArgs(args); if (flags.kind !== undefined || flags.blocks === true) return; - const input = pos[0]; + const input = pos[0] && brainRelativeArgument(root, pos[0]); if (!input) throw new UsageError("Usage: brain render [--format pdf|png|html] [--out ]"); if (input === "-") return; const abs = resolveWritable(root, input); @@ -213,7 +213,7 @@ export const renderCommand: CoreCommand = { return; } if (flags.scaffold === true) throw new UsageError("--scaffold needs --kind "); - const input = pos[0]; + const input = pos[0] && brainRelativeArgument(cli.brain.root, pos[0]); if (!input) { throw new UsageError("Usage: brain render [--format pdf|png|html] [--out ]"); } @@ -257,7 +257,7 @@ export const renderCommand: CoreCommand = { (fromStdin ? undefined : sourceLabel); // --- resolve the output path - const outFlag = typeof flags.out === "string" ? flags.out : undefined; + const outFlag = typeof flags.out === "string" ? brainRelativeArgument(root, flags.out) : undefined; if (outFlag && flags.scratch === true) { throw new UsageError("--out and --scratch are exclusive"); } diff --git a/packages/core/src/lib/safe-path.ts b/packages/core/src/lib/safe-path.ts index 1e504e3c1d..d316febefe 100644 --- a/packages/core/src/lib/safe-path.ts +++ b/packages/core/src/lib/safe-path.ts @@ -58,6 +58,37 @@ export function safeResolveHeld(root: string, path: string): string | null { return null; } +/** + * A CLI path argument as the request `safeResolve` takes (#3422). An absolute + * argument lexically inside the brain (under the root as given or under its + * realpath) becomes brain-relative, `.` for the root itself. Anything else is + * returned unchanged, so the resolver gives its own answer: a relative + * argument is resolved as before, and an absolute one outside the brain, or + * one with a `..` segment, stays absolute and is refused. Only the spelling + * changes here: the relative result still goes through `safeResolve`, so a + * symlink on the way that leaves the brain is refused there. + * + * Every CLI argument that names a brain path goes through this before it + * reaches `safeResolve` or `resolveWritable`. Requests from anywhere else (MCP + * tools, settings, files) do not: they are repo-relative by contract. + */ +export function brainRelativeArgument(root: string, arg: string): string { + if (typeof arg !== "string" || !isAbsolute(arg)) return arg; + if (arg.split(/[\\/]/).includes("..")) return arg; + const bases = [resolve(root)]; + try { + bases.push(realpathSync(root)); + } catch { + // A root that does not resolve is refused by the resolver anyway. + } + for (const base of bases) { + const rel = relative(base, arg); + if (rel === "") return "."; + if (!isAbsolute(rel) && rel.split(sep)[0] !== "..") return rel.split(sep).join("/"); + } + return arg; +} + /** * Resolve a path the caller may read or write: inside the brain root only. * diff --git a/packages/core/src/module.ts b/packages/core/src/module.ts index 211d8a8d05..4fd703778f 100644 --- a/packages/core/src/module.ts +++ b/packages/core/src/module.ts @@ -17,7 +17,7 @@ export { configurationRoot } from "./lib/config.js"; // Path containment and atomic writes -export { safeResolve, resolveWritable, writeFileSafely, WriteRefusedError } from "./lib/safe-path.js"; +export { safeResolve, resolveWritable, brainRelativeArgument, writeFileSafely, WriteRefusedError } from "./lib/safe-path.js"; export type { WriteFileSafelyOptions } from "./lib/safe-path.js"; // The scratch area (.brain/scratch) diff --git a/packages/core/tests/cli-path-arguments.test.ts b/packages/core/tests/cli-path-arguments.test.ts new file mode 100644 index 0000000000..684dd74be4 --- /dev/null +++ b/packages/core/tests/cli-path-arguments.test.ts @@ -0,0 +1,87 @@ +/** + * CLI path arguments (#3422, maintainer ruling of 2026-11-03): an absolute + * argument inside the brain is converted to a brain-relative path before it + * reaches `safeResolve`, which itself stays strict. An absolute argument + * outside the brain is still refused, and so is one that only reaches the + * outside through a symlink inside the brain. `brain eval --out` and + * `brain image --out` carry the same rows in their own suites. + */ + +import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import { existsSync, mkdtempSync, symlinkSync, writeFileSync } from "fs"; +import { tmpdir } from "os"; +import { join } from "path"; + +import { cleanup, makeTempBrain, runCli } from "./cli-harness"; + +let root: string; +let outside: string; + +beforeAll(() => { + root = makeTempBrain(); + outside = mkdtempSync(join(tmpdir(), "brain-cli-path-outside-")); + writeFileSync(join(outside, "secret.md"), "---\ntitle: Secret\ntype: note\n---\n\nOutside the brain.\n"); + symlinkSync(outside, join(root, "notes", "link-out")); +}); + +afterAll(() => { + cleanup(root); + cleanup(outside); +}); + +describe("brain read ", () => { + test("an absolute path inside the brain is read", async () => { + const { code, stdout } = await runCli(root, ["read", join(root, "health", "knee-injury.md")]); + expect(code).toBe(0); + expect(stdout).toContain("Left Knee"); + }); + + test("an absolute path outside the brain is refused", async () => { + const { code, stdout, stderr } = await runCli(root, ["read", join(outside, "secret.md")]); + expect(code).not.toBe(0); + expect(stdout).not.toContain("Outside the brain"); + expect(stderr).toContain("File not found"); + }); + + test("an absolute path through a symlink that leaves the brain is refused", async () => { + const { code, stdout, stderr } = await runCli(root, ["read", join(root, "notes", "link-out", "secret.md")]); + expect(code).not.toBe(0); + expect(stdout).not.toContain("Outside the brain"); + expect(stderr).toContain("File not found"); + }); +}); + +describe("brain archive ", () => { + test("an absolute path inside the brain is archived, reported brain-relative", async () => { + const { code, stdout } = await runCli(root, ["archive", join(root, "notes", "loose-idea.md"), "--dry-run", "--json"]); + expect(code).toBe(0); + expect(JSON.parse(stdout).path).toBe("notes/loose-idea.md"); + }); + + test("an absolute path outside the brain, or through a link out of it, is refused", async () => { + for (const path of [join(outside, "secret.md"), join(root, "notes", "link-out", "secret.md")]) { + const { code, stderr } = await runCli(root, ["archive", path, "--dry-run", "--json"]); + expect(code).not.toBe(0); + expect(stderr).toContain("escapes the brain root"); + } + }); +}); + +describe("brain okf export --out ", () => { + test("an absolute directory inside the brain passes containment and is named brain-relative", async () => { + const { stderr } = await runCli(root, ["okf", "export", "--out", join(root, "okf-abs"), "--json"]); + // The fixture does not exclude this directory from indexing, so the export + // stops at that later check, which names the converted relative path. + expect(stderr).not.toContain("escapes the brain root"); + expect(stderr).toContain("okf-abs."); + }); + + test("an absolute directory outside the brain, or through a link out of it, is refused", async () => { + for (const out of [join(outside, "okf"), join(root, "notes", "link-out", "okf")]) { + const { code, stderr } = await runCli(root, ["okf", "export", "--out", out, "--json"]); + expect(code).not.toBe(0); + expect(stderr).toContain("escapes the brain root"); + expect(existsSync(join(outside, "okf"))).toBe(false); + } + }); +}); diff --git a/packages/core/tests/containment-rows.test.ts b/packages/core/tests/containment-rows.test.ts index ba99bf2c4e..c36ffd9054 100644 --- a/packages/core/tests/containment-rows.test.ts +++ b/packages/core/tests/containment-rows.test.ts @@ -12,7 +12,7 @@ import { tmpdir } from "os"; import { join, relative } from "path"; import { SCRATCH_DIR } from "../src/lib/scratch"; -import { safeResolve, safeResolveHeld } from "../src/lib/safe-path"; +import { brainRelativeArgument, safeResolve, safeResolveHeld } from "../src/lib/safe-path"; const base = realpathSync(mkdtempSync(join(tmpdir(), "brain-kit-containment-rows-"))); afterAll(() => rmSync(base, { recursive: true, force: true })); @@ -142,6 +142,48 @@ describe("core safeResolveHeld(root, abs): re-checking a path the caller holds ( }); }); +describe("core brainRelativeArgument(root, arg): CLI path arguments (#3422 ruling of 2026-11-03)", () => { + /** The argument after conversion, then `safeResolve`'s answer to it. */ + const cli = (r: string, arg: string) => answer(safeResolve(r, brainRelativeArgument(r, arg))); + + test("an absolute argument inside the brain becomes brain-relative and is accepted", () => { + expect(brainRelativeArgument(root, join(root, "notes/a.md"))).toBe("notes/a.md"); + expect(brainRelativeArgument(root, root)).toBe("."); + expect(brainRelativeArgument(root, `${root}/`)).toBe("."); + expect(cli(root, join(root, "notes/a.md"))).toBe("brain/notes/a.md"); + expect(cli(root, join(root, "notes/new.md"))).toBe("brain/notes/new.md"); + // The root as given or its realpath: either spelling is inside the brain. + expect(cli(join(base, "root-link"), join(base, "root-link/notes/a.md"))).toBe("brain/notes/a.md"); + expect(cli(join(base, "root-link"), join(root, "notes/a.md"))).toBe("brain/notes/a.md"); + }); + + test("a relative argument is passed through unchanged", () => { + expect(brainRelativeArgument(root, "notes/a.md")).toBe("notes/a.md"); + expect(brainRelativeArgument(root, "notes/../x")).toBe("notes/../x"); + }); + + test("an absolute argument outside the brain stays absolute and is refused", () => { + for (const arg of [join(outside, "secret.md"), `${root}-other/secret.md`, "/", join(root, "notes/../../brain-other/secret.md")]) { + expect(brainRelativeArgument(root, arg)).toBe(arg); + expect(cli(root, arg)).toBe("refused"); + } + }); + + test("a `..` segment keeps the argument absolute, even when its result would stay inside", () => { + const arg = join(root, "notes") + "/../file.md"; + expect(brainRelativeArgument(root, arg)).toBe(arg); + expect(cli(root, arg)).toBe("refused"); + }); + + test("an absolute argument through a link that leaves the brain is refused", () => { + expect(brainRelativeArgument(root, join(root, "link-out/secret.md"))).toBe("link-out/secret.md"); + expect(cli(root, join(root, "link-out/secret.md"))).toBe("refused"); + expect(cli(root, join(root, "link-out/new.md"))).toBe("refused"); + expect(cli(root, join(root, "bounce/back/a.md"))).toBe("refused"); + expect(cli(root, join(root, "dangling-in"))).toBe("refused"); + }); +}); + test("core's scratch area is .brain/scratch", () => { expect(SCRATCH_DIR).toBe(".brain/scratch"); }); diff --git a/packages/core/tests/eval-cli.test.ts b/packages/core/tests/eval-cli.test.ts index e4e20a1483..de66f85069 100644 --- a/packages/core/tests/eval-cli.test.ts +++ b/packages/core/tests/eval-cli.test.ts @@ -109,9 +109,7 @@ describe("scores", () => { test("--out writes the same envelope that --json prints", async () => { const set = writeSet("out.jsonl", TOP1); const outPath = join(root, "evals", "runs", "latest.json"); - // `--out` is repo-relative: an absolute path is refused, even inside the brain (#3422). - expect((await evalJson(["--set", set, "--out", outPath])).code).toBe(2); - const { code, out } = await evalJson(["--set", set, "--out", "evals/runs/latest.json"]); + const { code, out } = await evalJson(["--set", set, "--out", outPath]); expect(code).toBe(0); expect(JSON.parse(readFileSync(outPath, "utf-8"))).toEqual(out); }); @@ -280,6 +278,14 @@ describe("--out stays inside the brain", () => { expect(existsSync(join(outside, "through-dir.json"))).toBe(false); }); + test("an absolute path through a symlinked directory that leaves the brain is refused (#3422)", async () => { + symlinkSync(outside, join(root, "evals", "abs-linked-dir")); + const { code, stderr } = await refusedOut(join(root, "evals", "abs-linked-dir", "through-abs.json")); + expect(code).toBe(2); + expect(stderr).toContain("Output path is not inside the brain"); + expect(existsSync(join(outside, "through-abs.json"))).toBe(false); + }); + test("a symlinked file inside the brain does not redirect the write", async () => { const target = join(outside, "through-file.json"); writeFileSync(target, "untouched"); diff --git a/packages/module-diagrams/src/export-cli.ts b/packages/module-diagrams/src/export-cli.ts index e80d599676..1861b13ae0 100644 --- a/packages/module-diagrams/src/export-cli.ts +++ b/packages/module-diagrams/src/export-cli.ts @@ -1,6 +1,6 @@ import { existsSync,lstatSync } from "node:fs"; import { basename,dirname,extname,join,relative } from "node:path"; -import { markdownFences,resolveWritable,writeFileSafely,renderHtmlArtifact,SCRATCH_DIR,scratchName,assertScratchWritable,writeScratchFile,isInScratch } from "@schlessera/brain/module"; +import { brainRelativeArgument,markdownFences,resolveWritable,writeFileSafely,renderHtmlArtifact,SCRATCH_DIR,scratchName,assertScratchWritable,writeScratchFile,isInScratch } from "@schlessera/brain/module"; import {readRegularText} from "./regular-text.js"; import { parseDiagram } from "./svg-model.js"; import { embedDiagramFonts } from "./fonts.js"; @@ -15,7 +15,7 @@ const themes=new Set(["light","dark","print"]),formats=new Set(["svg","png","pdf const finding=(code:string,path:string,error:unknown):ArtifactFinding=>({code,path,message:error instanceof Error?error.message:String(error)}); /** Bounded UTF-8 input, before a complete allocation, for files and stdin. */ export async function readDiagramInput(root:string,input:string):Promise<{source:string;path:string;absolute:string|null}>{ - const absolute=input==="-"?null:resolveWritable(root,input);if(input!=="-"&&!absolute)throw Error("Input path must remain inside the brain");if(absolute&&!lstatSync(absolute).isFile())throw Error("Input must be a regular file"); + const absolute=input==="-"?null:resolveWritable(root,brainRelativeArgument(root,input));if(input!=="-"&&!absolute)throw Error("Input path must remain inside the brain");if(absolute&&!lstatSync(absolute).isFile())throw Error("Input must be a regular file"); const file=absolute?Bun.file(absolute):Bun.stdin,reader=file.stream().getReader(),chunks:Uint8Array[]=[];let size=0; try{for(;;){const item=await reader.read();if(item.done)break;size+=item.value.byteLength;if(size>1024*1024)throw Error("Diagram input exceeds the 1 MiB parse bound");chunks.push(item.value);}}finally{await reader.cancel();} return {source:new TextDecoder("utf-8",{fatal:true}).decode(Buffer.concat(chunks,size)),path:absolute?relative(root,absolute):"-",absolute}; @@ -31,7 +31,7 @@ export async function exportDiagram(argv:string[],root:string):Promise --theme light|dark|print --format svg|png|pdf [--out path]");const theme=parsed.flags["--theme"]??"print",format=parsed.flags["--format"]??"svg";if(!themes.has(theme)||!formats.has(format))throw Error("Unknown diagram theme or artifact format");result.theme=theme as DiagramTheme;result.format=format as DiagramExportResult["format"]; const input=await readDiagramInput(root,parsed.position[0]!);result.input=input.path;const checked=checkDiagram(input.source);result.warnings=checked.warnings.map(w=>finding(w.code,w.path,w.message));if(!checked.valid){result.errors=checked.errors.map(e=>finding(e.code,e.path,e.message));return result;} - const svg=embedDiagramFonts(toFlatSvg(input.source,result.theme)),defaultName=input.path==="-"?join(SCRATCH_DIR,scratchName(`diagram-${theme}`,format)):input.path.replace(/(?:\.diagram\.ya?ml|\.[^./\\]+)$/i,"")+`.${theme}.${format}`,output=parsed.flags["--out"]??defaultName; + const svg=embedDiagramFonts(toFlatSvg(input.source,result.theme)),defaultName=input.path==="-"?join(SCRATCH_DIR,scratchName(`diagram-${theme}`,format)):input.path.replace(/(?:\.diagram\.ya?ml|\.[^./\\]+)$/i,"")+`.${theme}.${format}`,output=parsed.flags["--out"]===undefined?defaultName:brainRelativeArgument(root,parsed.flags["--out"]); if(extname(output).toLowerCase()!==`.${format}`)throw Error("Output extension must match the artifact format");const destination=target(root,output);if(destination===input.absolute)throw Error("The source cannot be replaced by its derived artifact");if(isInScratch(root,output))assertScratchWritable(root,destination); let data:string|Uint8Array=svg;if(format!=="svg"){const box=/viewBox="[-0-9.]+ [-0-9.]+ ([0-9.]+) ([0-9.]+)"/.exec(svg)!;const width=Number(box[1]),height=Number(box[2]);data=await renderHtmlArtifact({html:`${svg}`,format:format as "png"|"pdf",width:Math.max(320,width)});} result.output=write(root,output,data,input.path!=="-"||!!parsed.flags["--out"]);result.bytes=typeof data==="string"?Buffer.byteLength(data):data.byteLength;result.ok=true; diff --git a/packages/module-images/src/cli.ts b/packages/module-images/src/cli.ts index 0bdd93ca7c..4717452c5a 100644 --- a/packages/module-images/src/cli.ts +++ b/packages/module-images/src/cli.ts @@ -8,6 +8,7 @@ import { isInScratch, isWriteRefusal, pruneScratch, + brainRelativeArgument, resolveWritable, safeResolve, scratchName, @@ -130,7 +131,7 @@ function slugify(prompt: string): string { } function loadImage(root: string, rel: string): ImageInput { - const abs = safeResolve(root, rel); + const abs = safeResolve(root, brainRelativeArgument(root, rel)); if (!abs) throw new Error(`Path escapes the brain root: ${rel}`); if (!existsSync(abs)) throw new Error(`No such file: ${rel}`); const ext = extname(abs).toLowerCase(); @@ -282,7 +283,7 @@ export const imageCommand: CommandModule = { // earlier draft must keep showing that draft. const toScratch = parsed.flags.scratch === true; const outRel = - (parsed.flags.out as string | undefined) ?? + (parsed.flags.out === undefined ? undefined : brainRelativeArgument(ctx.root, parsed.flags.out as string)) ?? (toScratch ? `${SCRATCH_DIR}/${scratchName(slugify(prompt), ext)}` : `${cfg.imagesDir}/${slugify(prompt)}-${new Date().toISOString().slice(0, 10)}.${ext}`); diff --git a/packages/module-images/tests/scratch.test.ts b/packages/module-images/tests/scratch.test.ts index 7c8e9f1019..a0415247bd 100644 --- a/packages/module-images/tests/scratch.test.ts +++ b/packages/module-images/tests/scratch.test.ts @@ -207,17 +207,29 @@ describe("brain image --scratch", () => { rmSync(outside, { recursive: true, force: true }); }); - test("--out is repo-relative: an absolute path is refused even inside the brain (#3422), and the output is reported as given", async () => { + test("an absolute --out inside the brain is reported repo-relative after generation, as in the dry run", async () => { stubProvider(); - expect(await run(["a lighthouse", "--draft", "--out", join(root, "assets", "draft.png")])).toBe(1); - out.length = 0; - expect(await run(["a lighthouse", "--draft", "--out", "assets/draft.png"])).toBe(0); + expect(await run(["a lighthouse", "--draft", "--out", join(root, "assets", "draft.png")])).toBe(0); const payload = JSON.parse(out.join("\n")) as { output: string; outputs: string[] }; expect(payload.output).toBe("assets/draft.png"); expect(payload.outputs).toEqual(["assets/draft.png"]); expect(readFileSync(join(root, "assets", "draft.png"), "utf8")).toBe(PNG_BYTES); }); + test("an absolute --out outside the brain, or through a link out of it, is refused and nothing lands outside (#3422)", async () => { + const outside = mkdtempSync(join(tmpdir(), "brain-outside-")); + mkdirSync(join(root, "assets"), { recursive: true }); + symlinkSync(outside, join(root, "assets", "link-out")); + stubProvider(); + for (const target of [join(outside, "draft.png"), join(root, "assets", "link-out", "draft.png")]) { + out.length = 0; + expect(await run(["a lighthouse", "--draft", "--out", target])).toBe(1); + expect(out.join("\n")).toContain("Output path is not inside the brain"); + } + expect(readdirSync(outside)).toEqual([]); + rmSync(outside, { recursive: true, force: true }); + }); + test("the ignore rule is checked again after the provider call, so a rule lost in flight refuses the write", async () => { ignoreScratch(root); // The rule disappears while the request is out: the pre-flight check diff --git a/packages/module-travel/src/cli.ts b/packages/module-travel/src/cli.ts index 59efdec92c..d92af04896 100644 --- a/packages/module-travel/src/cli.ts +++ b/packages/module-travel/src/cli.ts @@ -1,6 +1,6 @@ import { existsSync, lstatSync, readFileSync } from "fs"; import { join } from "path"; -import { safeResolve, writeFileSafely } from "@schlessera/brain/module"; +import { brainRelativeArgument, safeResolve, writeFileSafely } from "@schlessera/brain/module"; import type { CommandContext, CommandModule } from "@schlessera/brain"; import { readTravelCorpus } from "./content.js"; import type { TravelConfig } from "./module.js"; @@ -97,7 +97,7 @@ const command: CommandModule = { } if (!files.length || to === undefined) throw new Error("Usage: brain travel photo --to [--name ] [--date YYYY-MM-DD] [--force-date] [--json]"); const { preparePhotos } = await import("./photo.js"); - const photo = await preparePhotos(ctx.root, files, to, { name, date, forceDate }); + const photo = await preparePhotos(ctx.root, files, brainRelativeArgument(ctx.root, to), { name, date, forceDate }); if (ctx.json) console.log(JSON.stringify({ photo }, null, 2)); else { for (const file of photo.files) console.log(file.source + " → " + file.output + " (" + file.width + "×" + file.height + ")"); diff --git a/packages/module-travel/src/route.ts b/packages/module-travel/src/route.ts index 51d9c6953c..cbba76035b 100644 --- a/packages/module-travel/src/route.ts +++ b/packages/module-travel/src/route.ts @@ -1,6 +1,6 @@ import { readFileSync, lstatSync } from "node:fs"; import { basename, extname, join, relative } from "node:path"; -import { safeResolve, writeFileSafely, WriteRefusedError } from "@schlessera/brain/module"; +import { brainRelativeArgument, safeResolve, writeFileSafely, WriteRefusedError } from "@schlessera/brain/module"; import { parseHtml, ScrapeClient } from "@schlessera/brain-scrape"; import { MAX_ROUTE_BYTES, parseGpx, quantizeRoute, routeMetrics, routePoint, trimRoute, writeGpx } from "./route-gpx.js"; import type { RouteGeometry, RouteMetrics } from "./route-gpx.js"; @@ -160,7 +160,7 @@ export async function runRoute(args: string[], root: string, json: boolean): Pro else source = arg; } if (!source || !to) throw new Error("Usage: brain travel route --to [--name