From e40cd412304ecb52d9eae91ab7043fbfbfb3678e Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 3 Nov 2026 10:40:46 +0100 Subject: [PATCH 1/4] refactor(common): hold symlink-safe path containment once (#2506) (#3424) * test: characterize every containment resolver and predicate before sharing them (#2506) Each package gets a table-driven test of its current rows of the resolver and containment-predicate matrices, against a fixture tree with escapes via .., a sibling prefix, symlinked parents of new files, dangling links, a symlink cycle, an out-and-back link pair, scratch links, a symlinked root, a missing root and a directory swapped for an escaping link between calls. The module-private predicates are exported so the tests can reach them. Refs #2506 Co-Authored-By: Claude Opus 5.5 * refactor(common): hold symlink-safe path containment once (#2506) core, the ui-sdk and ui-server each carried their own symlink-safe resolver and their own containment predicates, and the copies already disagreed. The new @schlessera/brain-common/internal/safe-path entry holds: - isWithin(root, path, rule), the containment primitive. Its answers for equality, the separator, a root that already ends in a separator, and normalisation are explicit parameters. - one canonicalisation algorithm, written as a generator of filesystem queries so the sync and async variants run the same steps. It resolves under the root's realpath and canonicalises the nearest existing ancestor. The caller's policy sets how a missing root, a dangling link and the per-component check are handled, and whether a link is refused at a given component. core's safeResolve, the SDK's resolveInRepo and ui-server's safeResolve are now thin wrappers. Each keeps its own request refusals, error type and policy. The twelve named predicates are calls to isWithin with their row's parameters. The scratch-directory copies read BRAIN_SCRATCH_DIR, and isScratchPath still covers .brain itself. Two answers change, and each has a named test: - ui-server's safeResolve refuses a path through a symlink cycle. Its copy accepted it, while core and the SDK already refused it. - core-queries' inside() no longer refuses a child whose name starts with "..". It is inside the package. Doc citations into the files whose lines moved are updated. Refs #2506 Co-Authored-By: Claude Opus 5.5 * refactor(ui-server): read the scratch and workspaces names from worker-areas (#2506) Two more literal copies of the scratch directory name, in the scratch ignore query and the storage roots, now read BRAIN_SCRATCH_DIR, and the storage roots read BRAIN_WORKSPACES_DIR. Refs #2506 Co-Authored-By: Claude Opus 5.5 * test: pin the sibling-prefix and leaving dangling-chain refusals in every package (#2506) Dropping the separator after the root broke no existing ui-sdk or ui-server test, and dropping the check on a followed link's target broke none anywhere. These cases fail on each mutation and pass on the copies the packages carried before the shared module. Refs #2506 Co-Authored-By: Claude Opus 5.5 * docs: move the files-walker test citations past the new sibling-prefix test (#2506) Refs #2506 Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- .changeset/safe-path-once.md | 8 + api-report/common.txt | 9 + docs/decisions/container-fresh-proc.md | 6 +- docs/decisions/design-kit/links.md | 2 +- docs/decisions/governed-writable-workers.md | 42 +-- docs/decisions/index-query-api.md | 2 +- docs/decisions/managed-worktrees.md | 4 +- docs/decisions/policy-write-boundary.md | 6 +- docs/decisions/public-export-boundary.md | 8 +- docs/decisions/reference-pool-accounting.md | 4 +- docs/decisions/worker-writable-areas.md | 12 +- docs/hosting/agent-workers.md | 4 +- docs/http-api-coverage.md | 6 +- docs/plans/module-renderers.md | 2 +- docs/plans/storage-accounting.md | 4 +- docs/plans/storage-lifecycle.md | 6 +- packages/common/README.md | 1 + packages/common/package.json | 5 + packages/common/src/safe-path.ts | 255 ++++++++++++++++++ packages/common/tests/safe-path.test.ts | 176 ++++++++++++ packages/core/src/lib/safe-path.ts | 82 +----- packages/core/src/lib/scratch.ts | 8 +- packages/core/tests/containment-rows.test.ts | 125 +++++++++ .../ui-sdk/src/server/bridge-tools/mask.ts | 14 +- .../server/bridge-tools/resolve-in-repo.ts | 68 +---- .../src/server/maintenance-env-masks.ts | 3 +- .../src/server/native-reference-pool.ts | 4 +- .../ui-sdk/src/server/worker-file-observer.ts | 4 +- packages/ui-sdk/src/server/worker-launcher.ts | 3 +- packages/ui-sdk/src/server/worker-rtk.ts | 3 +- .../ui-sdk/src/server/worker-turn-temp.ts | 3 +- packages/ui-sdk/tests/bridge-tools.test.ts | 16 +- .../ui-sdk/tests/containment-rows.test.ts | 165 ++++++++++++ packages/ui-server/src/brain/host-boundary.ts | 3 +- .../ui-server/src/brain/operational-state.ts | 8 +- .../ui-server/src/brain/scratch-mask-query.ts | 3 +- packages/ui-server/src/brain/sync-mirror.ts | 3 +- packages/ui-server/src/core-queries.ts | 9 +- packages/ui-server/src/files/walker.ts | 116 +++----- packages/ui-server/src/storage/collect.ts | 3 +- packages/ui-server/src/storage/process.ts | 6 +- .../ui-server/tests/containment-rows.test.ts | 171 ++++++++++++ packages/ui-server/tests/files-walker.test.ts | 13 +- tests/allowed-edges.ts | 5 +- 44 files changed, 1113 insertions(+), 287 deletions(-) create mode 100644 .changeset/safe-path-once.md create mode 100644 packages/common/src/safe-path.ts create mode 100644 packages/common/tests/safe-path.test.ts create mode 100644 packages/core/tests/containment-rows.test.ts create mode 100644 packages/ui-sdk/tests/containment-rows.test.ts create mode 100644 packages/ui-server/tests/containment-rows.test.ts diff --git a/.changeset/safe-path-once.md b/.changeset/safe-path-once.md new file mode 100644 index 0000000000..b7ed39f57a --- /dev/null +++ b/.changeset/safe-path-once.md @@ -0,0 +1,8 @@ +--- +"@schlessera/brain-common": patch +"@schlessera/brain": patch +"@schlessera/brain-ui-sdk": patch +"@schlessera/brain-ui-server": patch +--- + +Symlink-safe path containment now has one implementation, in the new internal entry `@schlessera/brain-common/internal/safe-path` (#2506). It holds `isWithin`, the containment primitive whose equality, separator, trailing-separator and normalisation answers are explicit parameters, and one canonicalisation algorithm with a synchronous and an asynchronous variant. core's `safeResolve`, the SDK's `resolveInRepo` and the server's `safeResolve` are thin wrappers over it, and the scratch-directory copies read the shared `BRAIN_SCRATCH_DIR`. Each caller keeps its own answers, with two exceptions: the server's `safeResolve` now refuses a path through a symlink cycle, as core and the SDK already did, instead of answering a path that resolves nowhere; and the server's check that core's query entry lies inside its package no longer refuses a directory whose name starts with `..`. `safeResolve` and `SCRATCH_DIR` stay exported from `@schlessera/brain/module` with their signatures and answers unchanged. The new entry is internal and carries no compatibility promise. diff --git a/api-report/common.txt b/api-report/common.txt index 4668773343..155e0b5d5a 100644 --- a/api-report/common.txt +++ b/api-report/common.txt @@ -86,6 +86,15 @@ export "./internal/provider-unavailable" (./src/provider-unavailable.ts) providerUnavailableNotice withheldKeys +export "./internal/safe-path" (./src/safe-path.ts) + type ContainedPath + type ContainmentPolicy + type ContainmentRefusal + type WithinRule + isWithin + resolveContained + resolveContainedSync + export "./internal/worker-areas" (./src/worker-areas.ts) BRAIN_SCRATCH_DIR BRAIN_WORKSPACES_DIR diff --git a/docs/decisions/container-fresh-proc.md b/docs/decisions/container-fresh-proc.md index c890dde85a..dcc1664f36 100644 --- a/docs/decisions/container-fresh-proc.md +++ b/docs/decisions/container-fresh-proc.md @@ -1,7 +1,7 @@ # A fresh /proc for agent workers in a container The agent worker launcher gives every worker its own user and PID namespaces -and a fresh procfs (`workerCommand`, `packages/ui-sdk/src/server/worker-launcher.ts:509-689`). +and a fresh procfs (`workerCommand`, `packages/ui-sdk/src/server/worker-launcher.ts:510-690`). Under Docker's default masked `/proc` paths the kernel refuses that procfs mount, so every turn on such a host refuses with `bwrap: Can't mount proc on /newroot/proc: Operation not permitted` (#1622, @@ -22,7 +22,7 @@ does not change. /proc because the parent /proc has masked or covered paths; in Docker, run the container with --security-opt systempaths=unconfined", followed by bubblewrap's own line. Every other launch failure keeps the generic list - (`FRESH_PROC_REFUSED`, `packages/ui-sdk/src/server/worker-launcher.ts:1635`). + (`FRESH_PROC_REFUSED`, `packages/ui-sdk/src/server/worker-launcher.ts:1636`). The match is on bubblewrap's literal message, not a guess from the environment: a host that refuses for another reason is not told to change Docker options. @@ -145,7 +145,7 @@ most host-global `/proc` files check only the file mode, not a capability. **Ruling on #1629 (2026-10-11): a root-run server's worker gets its whole `/proc` read-only. Root servers still qualify.** `workerCommand` adds `--remount-ro /proc` after `--proc /proc` when the server's uid or effective -uid is 0 (`rootProcCover`, `packages/ui-sdk/src/server/worker-launcher.ts:334-336`). +uid is 0 (`rootProcCover`, `packages/ui-sdk/src/server/worker-launcher.ts:335-337`). Measured as container root with `systempaths=unconfined` and the seccomp profile above, with bubblewrap `0.9.0` from the image and the host's `0.12.0`, each in the ordinary and the restricted mode: diff --git a/docs/decisions/design-kit/links.md b/docs/decisions/design-kit/links.md index 0bb6ba1d07..910cb6a57d 100644 --- a/docs/decisions/design-kit/links.md +++ b/docs/decisions/design-kit/links.md @@ -108,7 +108,7 @@ found, and what the ruling did not say: (`LINK_BLOCK_SCHEMA`, `packages/ui-sdk/src/tool-contracts/blocks.ts:429-449`) mirrors the props. `classifyLink` (`classifyLink`, `packages/render-template/src/links.ts:252-311`) is pure. The edge table records the new dependency - (`"@schlessera/brain-ui-sdk"`, `tests/allowed-edges.ts:75`), and ui-kit now + (`"@schlessera/brain-ui-sdk"`, `tests/allowed-edges.ts:76`), and ui-kit now builds and publishes ahead of ui-sdk. At that point the kit's own row was unchanged. #558 later moved the pure classifier to the template's `./links` leaf and added the kit-to-template edge; D13's purity gate still holds. diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index a0f3ead01a..00f6649886 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -505,11 +505,11 @@ before application-lock admission, acquires its own complete native checkpoint asynchronously and runs a credential-free, read-only Git query. It releases that input after the worker drains, without creating or publishing a writable stage (`createScratchIgnoreQuery`, -`packages/ui-server/src/brain/scratch-mask-query.ts:7-43`). Exit 1 means the +`packages/ui-server/src/brain/scratch-mask-query.ts:8-44`). Exit 1 means the directory is not ignored. Launch failure, another exit or timeout means the rule could not be verified; the mask remains refused without forwarding worker stderr or claiming that the ignore file needs repair (`assertScratchMaskAsync`, -`packages/ui-sdk/src/server/bridge-tools/mask.ts:224-235`). +`packages/ui-sdk/src/server/bridge-tools/mask.ts:228-239`). **Credentials never reach a process that evaluates repository inputs.** A read-only host does not stop sandboxed code from stealing a credential it was @@ -543,7 +543,7 @@ maintenance worker no longer receives the keys the provider relay carries (`GEMINI_API_KEY`, `ANTHROPIC_API_KEY`, `OPENAI_API_KEY` and keys the operator lists for it), and the brain's `.env*` files are masked as they are for a credential-free worker. Its `brain` CLI reaches those providers through its own -relay (`providerRelayFor`, `packages/ui-server/src/brain/host-boundary.ts:420-427`). +relay (`providerRelayFor`, `packages/ui-server/src/brain/host-boundary.ts:421-428`). What remains is narrower and stated in the status: keys the relay does not carry (the `jev` reranker's, a `brain sync` agent runner's login) and every key on a host without managed native storage, where there is no relay. @@ -596,7 +596,7 @@ lists the keys each first-party command reads. The launcher withholds every provider credential in the subprocess descriptor from a governed or strict turn worker, except what its backend declares for its own inference and what an operator admits (`const turnProfile`, -`packages/ui-sdk/src/server/worker-launcher.ts:680-690`). A relayed turn keeps no +`packages/ui-sdk/src/server/worker-launcher.ts:681-691`). A relayed turn keeps no key. An unrelayed one keeps only its runtime's own inference credential, under the 2026-10-22 ruling that hosts without managed native storage keep today's inference credentials; pi resolves its own credentials there, so it keeps all @@ -1027,7 +1027,7 @@ worker's command starts, the server opens that tmpfs from outside through the sandbox's `/proc//root`. It waits until the path is a tmpfs of exactly the allowance on another device than the server's own `/tmp`, and keeps the descriptor -(`function* openPrivateTurnTempSteps`, `packages/ui-sdk/src/server/worker-launcher.ts:1136-1164`). +(`function* openPrivateTurnTempSteps`, `packages/ui-sdk/src/server/worker-launcher.ts:1137-1165`). Every later read goes through that descriptor, after the worker's namespace is gone as well, and never enters another mount, so runtime state below `/tmp` is never read as turn temp. The allowance (256 MiB by default, @@ -1035,14 +1035,14 @@ is gone as well, and never enters another mount, so runtime state below against its own budget, and a turn that cannot reserve it is refused as `worker_state_busy` (docs/hosting/agent-workers.md). The `turn_temp` tool reports usage and purges paths through the same descriptor -(`export function purgeTurnTemp`, `packages/ui-sdk/src/server/worker-turn-temp.ts:450-458`). +(`export function purgeTurnTemp`, `packages/ui-sdk/src/server/worker-turn-temp.ts:451-459`). The restricted envelope gets the same sized `/tmp` and promotes nothing. After the worker exits, the backend rewrites the answer text the turn appended to its saved transcript, and only that text. It looks at Markdown link and image destinations and reference definitions outside code. A file is promoted once per turn however often it is linked, up to 128 MiB per file, 256 MiB and 64 files per turn -(`export function createTurnTempPromoter`, `packages/ui-sdk/src/server/worker-turn-temp.ts:124-135`). +(`export function createTurnTempPromoter`, `packages/ui-sdk/src/server/worker-turn-temp.ts:125-136`). The copy goes to `.brain/scratch/turns//` under a name the reader's file links accept, so the rewritten link is brain-relative and is pinned like any other scratch link. Each result reaches the server as a `promotion` or @@ -1065,10 +1065,10 @@ Live blocks still use streamed-text offsets; the client and server share the span rebasing function and discard ambiguous overlaps as plain Markdown. **Pinning.** A link into `.brain/scratch/` pins the target. Prune skips pinned -files (`export function pruneScratch`, `packages/core/src/lib/scratch.ts:641`). +files (`export function pruneScratch`, `packages/core/src/lib/scratch.ts:645`). A pin is released when every conversation that links the file is deleted or falls out of retention. If the scratch area still exceeds its size limit -(`SCRATCH_MAX_BYTES`, `scratch.ts:58`) after unpinned files are pruned, the +(`SCRATCH_MAX_BYTES`, `scratch.ts:62`) after unpinned files are pruned, the overage is reported. Pinned files are never deleted. A writer that prunes after writing into scratch also passes the paths it just produced, protected for that one call (`pinnedPaths`), so retained pins over the cap cannot make it @@ -1352,7 +1352,7 @@ external editor throughout a native tool's execution. The parent observes the worker's resolved mount sources, including strict startup copies and writable area aliases; it does not substitute newer canonical bytes for a frozen view (`createWorkerFileObserver`, -`packages/ui-sdk/src/server/worker-file-observer.ts:13`). A failed or changing +`packages/ui-sdk/src/server/worker-file-observer.ts:15`). A failed or changing read cannot establish a new version. Claude's native `file_unchanged` response also preserves the previous observation: it supplied no new bytes (`const finishNativeFile`, @@ -2186,7 +2186,7 @@ a filesystem socket that is visible through the read-only host root: a Docker socket, a session bus, an SSH agent or a host proxy. Each of those is an unrecorded way out, and some reach privileged host effects. The launcher already masks `.git` in restricted workers for exactly this reason -(`function maskedGit`, `packages/ui-sdk/src/server/worker-launcher.ts:226`). +(`function maskedGit`, `packages/ui-sdk/src/server/worker-launcher.ts:227`). `governed` and `strict` workers therefore mask the host's runtime and state directories with empty read-only tmpfs mounts. Maintenance workers share the @@ -2204,7 +2204,7 @@ The worker's private `/tmp` and the other host masks remain in place. After the masks, the launcher re-binds only the explicit runtime inputs the worker needs, read-only, with the same resolution the restricted envelope uses -(`export function restrictedReadPaths`, `packages/ui-sdk/src/server/worker-launcher.ts:1910`): +(`export function restrictedReadPaths`, `packages/ui-sdk/src/server/worker-launcher.ts:1911`): - the Bun executable; - the backend entry's package, its `node_modules` chains and linked workspace @@ -2228,7 +2228,7 @@ such ancestor with empty tmpfs instead; it never binds that ancestor's real contents. Search permission uses the helper's primary shared group class when that group owns the directory, including when only the other class has execute permission. Existing canonical aliases and nested masks fold into that cover -(`maintenanceMounts`, `packages/ui-sdk/src/server/worker-launcher.ts:385-444`). +(`maintenanceMounts`, `packages/ui-sdk/src/server/worker-launcher.ts:386-445`). This supports disjoint private-state layouts, including a nested operational database below a server-owned `0700` parent. New ancestor coverage that would @@ -2304,9 +2304,9 @@ and subdirectories through retained aliases. It does not restore unrelated host-temp siblings or make runtime bytes writable. The concrete checks and mounts are in (`validateRuntimePlacement`, -`packages/ui-sdk/src/server/worker-launcher.ts:609-615`), -(`temporaryRuntimeMounts`, `packages/ui-sdk/src/server/worker-launcher.ts:636-675`) -and (`runtimeMaskOverlays`, `packages/ui-sdk/src/server/worker-launcher.ts:791-809`). +`packages/ui-sdk/src/server/worker-launcher.ts:610-616`), +(`temporaryRuntimeMounts`, `packages/ui-sdk/src/server/worker-launcher.ts:637-676`) +and (`runtimeMaskOverlays`, `packages/ui-sdk/src/server/worker-launcher.ts:792-810`). Alias restoration recognizes names already supplied by a read-only bind or an explicit system-view symlink. It does not mount a canonical executable over an existing alias such as `/bin/sh`; missing owned temporary paths still receive @@ -3337,7 +3337,7 @@ before mounting them: both belong to the server, helper mode uses its primary GID and exact `0750`/`0660` modes, and no-helper mode retains exact `0700`/`0600`. Missing endpoints, aliases, non-sockets, foreign ownership and wider modes refuse before payload execution -(`function restrictedMounts`, `packages/ui-sdk/src/server/worker-launcher.ts:250-284`). +(`function restrictedMounts`, `packages/ui-sdk/src/server/worker-launcher.ts:251-285`). This compatibility check does not change default autonomous admission or add another route. @@ -3475,11 +3475,11 @@ An ordinary group-shared directory was accessible, but the worker's private mount and namespace links through `/proc/` were denied. Changing the private directory to `0770` did not remove that process-access barrier. The current launcher opens mounts directly (`function openPrivateState`, -`packages/ui-sdk/src/server/worker-launcher.ts:1099-1127`; +`packages/ui-sdk/src/server/worker-launcher.ts:1100-1128`; `function* openPrivateTurnTempSteps`, -`packages/ui-sdk/src/server/worker-launcher.ts:1136-1162`) before population and +`packages/ui-sdk/src/server/worker-launcher.ts:1137-1163`) before population and start-gate release (`function* launchAgentWorkerSteps`, -`packages/ui-sdk/src/server/worker-launcher.ts:1325-1413`). Group modes and a uid +`packages/ui-sdk/src/server/worker-launcher.ts:1326-1414`). Group modes and a uid switch alone therefore cannot implement the selected cross-uid lifecycle. **Authority and launch.** One trusted external supervisor owns each worker @@ -3914,7 +3914,7 @@ files, `.claude/`, `.agents/`, `.pi/`, `.mcp.json`, and - The core CLI loads `brain.config.ts` or `brain.config.json` at the canonical brain cwd (`loadUserConfig`, `packages/core/src/lib/config.ts:594-628`). Host commands bind that cwd to the selected brain (`function hostSpawn`, - `packages/ui-server/src/brain/host-boundary.ts:511-522`). + `packages/ui-server/src/brain/host-boundary.ts:512-523`). - Bun startup uses root `bunfig.toml` and `package.json`; retained literal preload/module inputs can identify a nested module's nearest package scope. The inventory walks parent directories only within the originating journal diff --git a/docs/decisions/index-query-api.md b/docs/decisions/index-query-api.md index 74886b6add..56f558816e 100644 --- a/docs/decisions/index-query-api.md +++ b/docs/decisions/index-query-api.md @@ -118,7 +118,7 @@ neither justified a service or configurable query-provider seam. > **2026-10-05 — Implementation context (#697).** UI-server now declares the > optional peer and resolves the entry lazily, once per app -> (`createCoreQueryAccess`, `packages/ui-server/src/core-queries.ts:192-227`). The +> (`createCoreQueryAccess`, `packages/ui-server/src/core-queries.ts:193-228`). The > source-backed range is `>=0.40.0 <1.0.0`: the published 0.40.0 manifest is the > first to export `./queries`, its declarations name all nine operations and its > query source matches the source the server was migrated against; 0.39.0 has no diff --git a/docs/decisions/managed-worktrees.md b/docs/decisions/managed-worktrees.md index 3194de6862..c1265b08e3 100644 --- a/docs/decisions/managed-worktrees.md +++ b/docs/decisions/managed-worktrees.md @@ -98,7 +98,7 @@ Each governed or strict turn whose journal is recording opens one worker generation, and every worker of that turn binds the generation's root-owned directory whole at `/tmp/brain-worktrees`, inside the turn's own `/tmp` (`// Managed worktrees (#2430): a journaled turn's workers bind one empty generation.`, `packages/ui-server/src/ws/run-session.ts:570-582`; -`// Managed worktrees (#2430): the whole access generation`, `packages/ui-sdk/src/server/worker-launcher.ts:852-863`). +`// Managed worktrees (#2430): the whole access generation`, `packages/ui-sdk/src/server/worker-launcher.ts:853-864`). A granted worktree appears there as `/tmp/brain-worktrees//` on the worker's next path lookup; the worker cannot create entries beside it, and a restricted worker never binds a generation. Nothing returns a host path to the @@ -212,7 +212,7 @@ nothing. **Shared source is read through views.** Each such turn's workers bind the public view and their principal's private view whole and read-only at `/tmp/brain-reference/public` and `/tmp/brain-reference/private` -(`// Shared reference source (#2432)`, `packages/ui-sdk/src/server/worker-launcher.ts:864-875`). +(`// Shared reference source (#2432)`, `packages/ui-sdk/src/server/worker-launcher.ts:865-876`). A view the domain has not published to yet is opened empty first, so the turn sees its own first acquisition (`async bindable(principalId: string`, `packages/ui-server/src/brain/reference-source.ts:741-753`). diff --git a/docs/decisions/policy-write-boundary.md b/docs/decisions/policy-write-boundary.md index 3fe86900e3..2ca54a82af 100644 --- a/docs/decisions/policy-write-boundary.md +++ b/docs/decisions/policy-write-boundary.md @@ -497,13 +497,13 @@ sessions. before the runtime starts and read it after the worker is gone, while the tmpfs is reachable only inside the worker. The launcher does both from the host (`function* launchAgentWorkerSteps`, -`packages/ui-sdk/src/server/worker-launcher.ts:1325-1580`): +`packages/ui-sdk/src/server/worker-launcher.ts:1326-1581`): 1. It finds the sandbox's first process from the kernel's record of bubblewrap's only child, then opens the tmpfs root through `/proc//root` and keeps that directory descriptor (`function openPrivateState`, - `packages/ui-sdk/src/server/worker-launcher.ts:1099-1123`). bubblewrap's + `packages/ui-sdk/src/server/worker-launcher.ts:1100-1124`). bubblewrap's process exists before its mounts do, so the open is accepted only once the path is its own mount (a device other than its parent's), a tmpfs of exactly the allowance, and empty; until then it would name the host's @@ -513,7 +513,7 @@ host (`function* launchAgentWorkerSteps`, code: the absolute `/bin/sh` reads one line from the worker's stdin with its `read` builtin, which only the server writes, and then becomes the command; closed stdin or any other line ends the worker unstarted - (`const STATE_GATE`, `packages/ui-sdk/src/server/worker-launcher.ts:56`). + (`const STATE_GATE`, `packages/ui-sdk/src/server/worker-launcher.ts:57`). The gate runs no `PATH` lookup, so nothing in the worker's environment or the brain can stand in for it, and the shell reads a pipe a byte at a time, so the runtime's own input is untouched. The server copies the snapshot in diff --git a/docs/decisions/public-export-boundary.md b/docs/decisions/public-export-boundary.md index 09a16600ad..2f9f8d42d7 100644 --- a/docs/decisions/public-export-boundary.md +++ b/docs/decisions/public-export-boundary.md @@ -290,15 +290,17 @@ its watch implementation and CLI remain implementation details. An internal-only package (#1396): `@schlessera/brain-common` has no root entry. Its entries, `./internal/env`, `./internal/frontmatter` and `./internal/worker-areas`, `./internal/protected-paths`, -`./internal/governance-policy` and `./internal/claude-subscription`, follow -the internal-entry rule above. +`./internal/governance-policy`, `./internal/claude-subscription` and +`./internal/safe-path`, follow the internal-entry rule above. The policy helper (#1744) serves both core and the server without requiring the server’s optional core peer; it adds no supported extension interface. The first two replace byte-identical copies of `env-core.ts` and `frontmatter-parse.ts` that the packages carried; the third (#1693) holds the worker write-area rules that the ui-sdk's sandbox note and core's CLI refusal both state. The subscription billing guard (#2493) replaces the copies core's CLI runner and -the chat backend carried. A name a +the chat backend carried. Symlink-safe containment (#2506) replaces the +resolvers core, the ui-sdk and ui-server carried and their hand-written +containment predicates. A name a public entry re-exports from it, such as core's `DynamicEnvReadSpec` and `readEnvVar`, stays part of that package's supported surface and is recorded in that package's report. diff --git a/docs/decisions/reference-pool-accounting.md b/docs/decisions/reference-pool-accounting.md index 76858e1b86..25b09c9aed 100644 --- a/docs/decisions/reference-pool-accounting.md +++ b/docs/decisions/reference-pool-accounting.md @@ -8,7 +8,7 @@ actual allocated disk. That decision left the mechanism to implementation. This record names the mechanism, the primary sources it relies on and the native observations that qualified it. The pool is managed by the existing host-only native manager -(`createNativeReferencePool`, `packages/ui-sdk/src/server/native-reference-pool.ts:270-962`). +(`createNativeReferencePool`, `packages/ui-sdk/src/server/native-reference-pool.ts:272-964`). No consumer uses it yet. ## A separate volume, not another subvolume of the brain store @@ -224,7 +224,7 @@ directory its intent records. Sealing also makes the root's top directory `roots/` and `views/` join the mandatory worker masks. A worker sees reference source only through a view bound for it, and other domains' views stay invisible. `poolView` (#2432) opens a view's directory before its first -publication (`function viewOpen`, `packages/ui-sdk/src/server/native-reference-pool.ts:938-941`), +publication (`function viewOpen`, `packages/ui-sdk/src/server/native-reference-pool.ts:940-943`), so a worker that binds it at its start sees the domain's first publication on a later lookup ([agent tools](managed-worktrees.md#agent-tools)). diff --git a/docs/decisions/worker-writable-areas.md b/docs/decisions/worker-writable-areas.md index 773ca521ef..118fd68354 100644 --- a/docs/decisions/worker-writable-areas.md +++ b/docs/decisions/worker-writable-areas.md @@ -81,7 +81,7 @@ on the transcript persist path and is not part of this record. **One resolution, two consumers.** `prepareWorkerSandbox` resolves the areas and per-turn XDG layout once per worker -(`export function prepareWorkerSandbox`, `packages/ui-sdk/src/server/worker-launcher.ts:901-942`). +(`export function prepareWorkerSandbox`, `packages/ui-sdk/src/server/worker-launcher.ts:902-943`). The backend passes the result both to the launcher, which turns it into bubblewrap arguments, and to `workerSandboxNote`, which renders the agent's note (`export function workerSandboxNote`, `packages/ui-sdk/src/server/worker-sandbox.ts:592-657`). @@ -89,7 +89,7 @@ The launcher re-checks the resolved layout against the actual launch: the same brain and envelope, each writable area still a real directory at its own path in the brain. The backend selects runtime HOME separately. A mismatch refuses the launch instead of binding something the note does not -describe (`function sandboxMounts`, `packages/ui-sdk/src/server/worker-launcher.ts:823-853`). +describe (`function sandboxMounts`, `packages/ui-sdk/src/server/worker-launcher.ts:824-854`). A launch without a resolved layout keeps the 0.41 view: only the per-turn scratch is writable. @@ -153,7 +153,7 @@ through the roadblock path. This is a worker write boundary, not an immutable view: host-side changes to that directory remain visible. A backend may select a different runtime HOME as described below; it does not make the host home writable. `prepareWorkerSandbox` resolves this same XDG mode on every eligible host (`export function prepareWorkerSandbox`, -`packages/ui-sdk/src/server/worker-launcher.ts:901-942`). Host-backed overlay +`packages/ui-sdk/src/server/worker-launcher.ts:902-943`). Host-backed overlay uppers cannot live on the worker's private tmpfs; keeping them would leave an unbounded write area. Tools reading XDG config see the per-turn directory, while direct reads of real HOME retain the read-only host view. @@ -267,17 +267,17 @@ The `read_only_brain` code and its **Serving.** The file routes refuse any symlink at or below `.brain` for a scratch path, and a scratch listing omits links -(`const scratchRequest`, `packages/ui-server/src/files/walker.ts:115`). +(`const policy: ContainmentPolicy = isScratchPath(rel)`, `packages/ui-server/src/files/walker.ts:97-99`). Elsewhere in the brain an in-brain link resolves as before. Those checks run before the open, so a file whose requested or resolved path lies in `.brain/scratch/` or `workspaces/` is then read once, from its resolved path, through descriptors that never follow a link (each directory from the brain root opened with `O_NOFOLLOW | O_DIRECTORY` through the previous one, the file with `O_NOFOLLOW`), and the route serves that snapshot; the size cap bounds it -(`export function readAnchoredSnapshot`, `packages/ui-server/src/files/walker.ts:157-193`). +(`export function readAnchoredSnapshot`, `packages/ui-server/src/files/walker.ts:116-152`). Core's prune reads every entry with `lstat`, and on Linux removes each file and emptied directory through its parent's descriptor in the same way -(`function anchored`, `packages/core/src/lib/scratch.ts:513-543`), because a +(`function anchored`, `packages/core/src/lib/scratch.ts:517-547`), because a hosted agent can swap a scratch directory for a link while the host prunes. ## Measurements diff --git a/docs/hosting/agent-workers.md b/docs/hosting/agent-workers.md index f69970cf33..0c97221d98 100644 --- a/docs/hosting/agent-workers.md +++ b/docs/hosting/agent-workers.md @@ -91,7 +91,7 @@ owner-only `0700`/`0600` modes. Before mounting the proxy, the launcher checks canonical paths, server ownership, the expected helper group, exact modes and socket type. Missing entries, symlinks and widened permissions refuse before the payload starts (`if (input.egress)`, -`packages/ui-sdk/src/server/worker-launcher.ts:552-567`). This does not select +`packages/ui-sdk/src/server/worker-launcher.ts:553-568`). This does not select the ordinary inference route or enable the proxy by default. Native output stages use the existing manager's active stage identity. The @@ -1273,7 +1273,7 @@ its working directory. No first-party code reads `.env` any other way. The launcher binds `/dev/null` over every present `.env*` name at the brain root, and over the file an `.env*` link leads to, after every other mount, so no later bind can restore it (`maintenanceEnvMasks`, -`packages/ui-sdk/src/server/maintenance-env-masks.ts:66-70`). The worker cannot +`packages/ui-sdk/src/server/maintenance-env-masks.ts:67-71`). The worker cannot open them: a read fails with `EACCES`, so Bun loads nothing and `cat .env` prints nothing. A new `.env*` name is a protected tier A path, so a turn cannot create one in the brain either. diff --git a/docs/http-api-coverage.md b/docs/http-api-coverage.md index d2e39abf9e..f9e3c2012f 100644 --- a/docs/http-api-coverage.md +++ b/docs/http-api-coverage.md @@ -237,10 +237,10 @@ cover start refusal, mid-turn partial work, overlapping observations and leases. **F — Content and byte ranges.** -- `an uncompressed, all-ASCII PDF is served as binary, not as its source` ([source](../packages/ui-server/tests/files-walker.test.ts)), (`an uncompressed, all-ASCII PDF is served as binary, not as its source`, `packages/ui-server/tests/files-walker.test.ts:299-305`) -- `rejects file_too_large` ([source](../packages/ui-server/tests/files-walker.test.ts)), (`rejects file_too_large`, `packages/ui-server/tests/files-walker.test.ts:324-329`) +- `an uncompressed, all-ASCII PDF is served as binary, not as its source` ([source](../packages/ui-server/tests/files-walker.test.ts)), (`an uncompressed, all-ASCII PDF is served as binary, not as its source`, `packages/ui-server/tests/files-walker.test.ts:310-316`) +- `rejects file_too_large` ([source](../packages/ui-server/tests/files-walker.test.ts)), (`rejects file_too_large`, `packages/ui-server/tests/files-walker.test.ts:335-340`) - `rejects symlink escape` ([source](../packages/ui-server/tests/files-walker.test.ts)), (`rejects symlink escape`, `packages/ui-server/tests/files-walker.test.ts:102-104`) -- `a child of an existing file is not found without leaking its absolute path` ([source](../packages/ui-server/tests/files-walker.test.ts)), (`a child of an existing file is not found without leaking its absolute path`, `packages/ui-server/tests/files-walker.test.ts:335-348`) +- `a child of an existing file is not found without leaking its absolute path` ([source](../packages/ui-server/tests/files-walker.test.ts)), (`a child of an existing file is not found without leaking its absolute path`, `packages/ui-server/tests/files-walker.test.ts:346-359`) - `Safari's two-byte probe gets a 206 with its length, and the frame headers` ([source](../packages/ui-server/tests/files-raw-range.test.ts)), (`Safari's two-byte probe gets a 206 with its length, and the frame headers`, `packages/ui-server/tests/files-raw-range.test.ts:222-231`) - `a range that starts past the end is a 416 naming the size` ([source](../packages/ui-server/tests/files-raw-range.test.ts)), (`a range that starts past the end is a 416 naming the size`, `packages/ui-server/tests/files-raw-range.test.ts:87-92`) - `a HEAD request ignores Range, which applies to GET only` ([source](../packages/ui-server/tests/files-raw-range.test.ts)), (`a HEAD request ignores Range, which applies to GET only`, `packages/ui-server/tests/files-raw-range.test.ts:102-107`) diff --git a/docs/plans/module-renderers.md b/docs/plans/module-renderers.md index 2fbb6dab9a..6ed484352b 100644 --- a/docs/plans/module-renderers.md +++ b/docs/plans/module-renderers.md @@ -181,7 +181,7 @@ reach the app through `![](x.svg)`: - **An `.svg` file must open as an image.** Today it opens as source, because the byte sniff in `export function classifyKind`, - `packages/ui-server/src/files/walker.ts:347` classifies UTF-8 SVG as text. + `packages/ui-server/src/files/walker.ts:303` classifies UTF-8 SVG as text. - **SVG images must print light.** Measured: a host `@media print { :root { color-scheme: light } }` makes an `` SVG take its light palette. diff --git a/docs/plans/storage-accounting.md b/docs/plans/storage-accounting.md index f90b09c73c..89bfce463f 100644 --- a/docs/plans/storage-accounting.md +++ b/docs/plans/storage-accounting.md @@ -69,14 +69,14 @@ Source anchors, checked against the reviewed commit: thinning (`thin`, `packages/core/src/lib/stats-history.ts:232-244`). - D: effective path/journal resolution (`createApp`, `packages/ui-server/src/app.ts:301-337`), WAL store (`createUiDb`, `packages/ui-server/src/db/client.ts:27-44`), and - private locations (`statePaths`, `packages/ui-server/src/brain/operational-state.ts:108-114`). + private locations (`statePaths`, `packages/ui-server/src/brain/operational-state.ts:114-120`). - E: live/archive paths (`transcriptPaths`, `packages/ui-backend-claude/src/transcript-archive.ts:30-39`). - F: session location (`piSessionDirectory`, `packages/ui-backend-pi/src/session-storage.ts:8-28`). - G: staging location (`shareStagingRoot`, `packages/ui-server/src/share/staging.ts:143-145`) and settlement-aware cleanup (`function claim`, `packages/ui-server/src/inbox/lifecycle-writes.ts:42-61`). [#807](https://github.com/schlessera/brain-kit/issues/807) supplies live-work and settlement protection for staging cleanup. -- H: scratch defaults (`SCRATCH_DIR`, `packages/core/src/lib/scratch.ts:52-61`), +- H: scratch defaults (`SCRATCH_DIR`, `packages/core/src/lib/scratch.ts:56-65`), scheduled prune (`startScratchPrune`, `packages/ui-server/src/cron/scratch-prune.ts:41-49`), and the [writable-area decision](../decisions/worker-writable-areas.md). [#1656](https://github.com/schlessera/brain-kit/issues/1656) supplies retained diff --git a/docs/plans/storage-lifecycle.md b/docs/plans/storage-lifecycle.md index b0295ec76e..2aa8b12251 100644 --- a/docs/plans/storage-lifecycle.md +++ b/docs/plans/storage-lifecycle.md @@ -76,9 +76,9 @@ Source foundations for the matrix: - Staging eligibility, removal and acknowledgment are separate (`export function createInboxCleanup`, `packages/ui-server/src/inbox/cleanup.ts:18-82`). - Scratch pin loading and per-entry revalidation sit inside pruning - (`export function pruneScratch`, `packages/core/src/lib/scratch.ts:641-722`); + (`export function pruneScratch`, `packages/core/src/lib/scratch.ts:645-726`); explicit clean is different - (`export function cleanScratch`, `packages/core/src/lib/scratch.ts:725-743`). + (`export function cleanScratch`, `packages/core/src/lib/scratch.ts:729-747`). Server refresh refuses incomplete enumeration and confirms missing histories before releasing links (`function openScratchPins`, `packages/ui-server/src/cron/scratch-pins.ts:72-195`). - Claude publishes and verifies cold copies before deleting the live source @@ -90,7 +90,7 @@ Source foundations for the matrix: Object copies reserve temporary bytes before writing (`async putFileAsync`, `packages/ui-server/src/brain/journal-objects.ts:95-150`). - Turn-temp purge has its own scope and measured result - (`export function purgeTurnTemp`, `packages/ui-sdk/src/server/worker-turn-temp.ts:450-533`), + (`export function purgeTurnTemp`, `packages/ui-sdk/src/server/worker-turn-temp.ts:451-534`), and tool validation/recording (`export function handleTurnTemp`, `packages/ui-sdk/src/server/bridge-tools/turn-temp.ts:19-41`). [Operational recovery](../inbox-recovery.md) specifies backup consistency and diff --git a/packages/common/README.md b/packages/common/README.md index 0bbc577d31..c004c6cba3 100644 --- a/packages/common/README.md +++ b/packages/common/README.md @@ -16,6 +16,7 @@ one; it arrives as their dependency. | `@schlessera/brain-common/internal/governance-policy` | Data-only policy schema, defaults, parsing and anchored reads shared by the core CLI and hosted server (#1744). The server can read policy without installing its optional core peer. | | `@schlessera/brain-common/internal/index-location` | Where the disposable search index lives: the `.brain-index/` directory holding `brain.db` and its SQLite sidecars, and the legacy root-level names a brain migrates away from by rebuilding (#1668). | | `@schlessera/brain-common/internal/claude-subscription` | The subscription billing guard both Claude runners apply: the cleared credential variables, the neutralised flag settings, the settings refusal and the account verdict. core's CLI runner and the chat backend import it, so a newly found credential or routing variable is added once (#2493). | +| `@schlessera/brain-common/internal/safe-path` | Symlink-safe path containment: `isWithin`, the containment primitive whose equality, separator, trailing-separator and normalisation answers are explicit parameters, and `resolveContained`/`resolveContainedSync`, one canonicalisation algorithm that resolves a request under the root's realpath through its nearest existing ancestor. core's `safeResolve`, the SDK's `resolveInRepo` and the server's `safeResolve` are thin wrappers that each keep their own request refusals and policy, so a hardening fix lands once (#2506). | Nothing else belongs here. A further helper needs its own issue and a reason it cannot live in the package that uses it. diff --git a/packages/common/package.json b/packages/common/package.json index 006737a9a6..314678be3e 100644 --- a/packages/common/package.json +++ b/packages/common/package.json @@ -75,6 +75,11 @@ "bun": "./src/claude-subscription.ts", "types": "./dist/claude-subscription.d.ts", "default": "./dist/claude-subscription.js" + }, + "./internal/safe-path": { + "bun": "./src/safe-path.ts", + "types": "./dist/safe-path.d.ts", + "default": "./dist/safe-path.js" } }, "files": [ diff --git a/packages/common/src/safe-path.ts b/packages/common/src/safe-path.ts new file mode 100644 index 0000000000..f9b3fba908 --- /dev/null +++ b/packages/common/src/safe-path.ts @@ -0,0 +1,255 @@ +/** + * Symlink-safe path containment, held once for core, the ui-sdk and ui-server + * (#2506). Two parts: + * + * - {@link isWithin}, the string question "is this path the root or below + * it?". The callers' answers differ on equality, the separator, a root + * ending in a separator and normalisation, so those are parameters + * ({@link WithinRule}) rather than hidden choices. + * - {@link resolveContained} and {@link resolveContainedSync}, one + * canonicalisation algorithm: resolve the request under the root's + * realpath, canonicalise its nearest existing ancestor, and check the + * canonical result against the root. A dangling link is either followed + * to its target, which must stay inside, or refused. The algorithm is a + * generator of filesystem queries, so the synchronous and asynchronous + * variants run the same steps. + * + * What a caller accepts as a request (absolute paths, `..`, Windows syntax) + * and how it reports a refusal stay in that caller: they are its policy, and + * the resolver rows of #2506 differ on them. Everything after the request is + * accepted is decided here. + */ +import { lstatSync, readlinkSync, realpathSync } from "node:fs"; +import { lstat, readlink, realpath } from "node:fs/promises"; +import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path"; + +/** How {@link isWithin} answers the cases its callers disagree on. */ +export interface WithinRule { + /** Whether the root itself counts as within. Default `true`. */ + readonly includeRoot?: boolean; + /** The separator that must follow the root. Default `/`. */ + readonly separator?: string; + /** + * A root already ending in the separator: `"append"` (default) appends + * another, so `/` and `/a/` hold nothing below them; `"boundary"` takes the + * root's own separator as the boundary, so `/` holds every absolute path. + */ + readonly trailingSeparator?: "append" | "boundary"; + /** + * Resolve both paths against the working directory first, as + * `path.relative` does, so `/a/b/../c` is not within `/a/b`. Default + * `false`: the comparison is on the strings as given. + */ + readonly resolvePaths?: boolean; +} + +/** Whether `path` is `root` or below it, under `rule`. The argument order is fixed: root first. */ +export function isWithin(root: string, path: string, rule: WithinRule = {}): boolean { + if (rule.resolvePaths) { + root = resolve(root); + path = resolve(path); + } + if (path === root) return rule.includeRoot ?? true; + const separator = rule.separator ?? "/"; + const prefix = rule.trailingSeparator === "boundary" && root.endsWith(separator) ? root : root + separator; + return path.startsWith(prefix); +} + +/** The platform-separator rule the resolvers check canonical paths with. */ +const CANONICAL: WithinRule = { separator: sep }; + +/** What a caller decides about the filesystem it resolves through. */ +export interface ContainmentPolicy { + /** + * A root whose realpath fails. `"refuse"`: nothing resolves. `"lexical"`: + * a root that does not exist yet contains the lexical path; a dangling + * link in its place is refused and any other failure is an error. + */ + readonly missingRoot: "refuse" | "lexical"; + /** + * A symlink whose target cannot be resolved. `"follow"`: re-check its + * target, which must stay inside, so a write through it lands inside. + * `"refuse"`: refuse it, wherever it points. + */ + readonly danglingLinks: "follow" | "refuse"; + /** + * `"final"`: only the canonical path must stay inside, so a request may + * leave through one link and come back through another. `"every"`: each + * existing component on the way must stay inside too. + */ + readonly components: "final" | "every"; + /** + * Refuse a symlink at this lexical component without following it; `root` + * is the root's realpath. Only consulted with `components: "every"`, + * which visits each component. + */ + readonly refuseLinkAt?: (path: string, root: string) => boolean; +} + +/** Why a request was refused. */ +export type ContainmentRefusal = "nul" | "missing-root" | "escape" | "dangling" | "link-budget" | "refused-link"; + +export type ContainedPath = + | { + readonly ok: true; + /** The root's realpath (its lexical path when a missing root is allowed). */ + readonly root: string; + /** The request resolved under {@link root}, links as written. */ + readonly lexical: string; + /** The request with every existing link followed; the missing tail as written. */ + readonly canonical: string; + } + | { readonly ok: false; readonly reason: ContainmentRefusal } + /** A filesystem failure that is neither absence nor a refusal (EIO, ...). */ + | { readonly ok: false; readonly reason: "error"; readonly error: NodeJS.ErrnoException }; + +/** + * Codes that mean "this component cannot be resolved": the lookup stops + * there and what follows is treated as not existing yet. Any other code is + * an error, never an acceptance. + */ +const UNRESOLVABLE = new Set(["ENOENT", "ENOTDIR", "ENAMETOOLONG", "ELOOP", "EACCES", "EPERM"]); + +/** The kernel's symlink budget for one lookup. */ +const MAX_LINK_HOPS = 40; + +type FsQuery = + | { readonly op: "realpath" | "readlink"; readonly path: string } + | { readonly op: "lstat"; readonly path: string }; +type FsReply = + | { readonly ok: true; readonly value: string; readonly link: boolean } + | { readonly ok: false; readonly error: NodeJS.ErrnoException }; +type Steps = Generator; + +const failed = (error: unknown): FsReply => ({ ok: false, error: error as NodeJS.ErrnoException }); +const unresolvable = (reply: FsReply) => !reply.ok && UNRESOLVABLE.has(reply.error.code ?? ""); + +function querySync(query: FsQuery): FsReply { + try { + if (query.op === "lstat") return { ok: true, value: query.path, link: lstatSync(query.path).isSymbolicLink() }; + return { ok: true, value: query.op === "realpath" ? realpathSync(query.path) : readlinkSync(query.path), link: false }; + } catch (error) { + return failed(error); + } +} + +async function queryAsync(query: FsQuery): Promise { + try { + if (query.op === "lstat") return { ok: true, value: query.path, link: (await lstat(query.path)).isSymbolicLink() }; + return { ok: true, value: query.op === "realpath" ? await realpath(query.path) : await readlink(query.path), link: false }; + } catch (error) { + return failed(error); + } +} + +/** + * Canonicalise `path` (lexically inside `root`, a realpath): realpath its + * nearest existing ancestor and re-append the missing tail. A purely lexical + * fallback would let a symlinked parent smuggle a not-yet-created file + * outside the root. A dangling link is not "missing": a write through it is + * created at its target, so it is followed and re-checked, or refused. + */ +function* canonicalise(root: string, path: string, policy: ContainmentPolicy): Steps { + let existing = path; + let tail: string[] = []; + let hops = 0; + for (;;) { + const real = yield { op: "realpath", path: existing }; + if (real.ok) { + const candidate = tail.length > 0 ? join(real.value, ...tail) : real.value; + if (!isWithin(root, candidate, CANONICAL)) return { ok: false, reason: "escape" }; + return { ok: true, root, lexical: path, canonical: candidate }; + } + if (!unresolvable(real)) return { ok: false, reason: "error", error: real.error }; + const entry = yield { op: "lstat", path: existing }; + if (entry.ok && entry.link) { + // A link whose realpath fails: dangling, a cycle, or unreadable. + if (policy.danglingLinks === "refuse") return { ok: false, reason: "dangling" }; + if (++hops > MAX_LINK_HOPS) return { ok: false, reason: "link-budget" }; + const target = yield { op: "readlink", path: existing }; + if (!target.ok) return { ok: false, reason: "error", error: target.error }; + const resolved = isAbsolute(target.value) ? resolve(target.value) : resolve(dirname(existing), target.value); + const rejoined = tail.length > 0 ? join(resolved, ...tail) : resolved; + if (!isWithin(root, rejoined, CANONICAL)) return { ok: false, reason: "escape" }; + existing = rejoined; + tail = []; + continue; + } + if (!entry.ok && !unresolvable(entry)) return { ok: false, reason: "error", error: entry.error }; + // Not there (yet), or there but not resolvable as a whole: canonicalise + // what is above it. The walk ends at the root, which resolved. + tail.unshift(basename(existing)); + const parent = dirname(existing); + if (parent === existing) return { ok: false, reason: "escape" }; + existing = parent; + } +} + +function* containedSteps(root: string, rel: string, policy: ContainmentPolicy): Steps { + // A NUL would make the later fs call throw: a containment failure, not a + // deferred TypeError. + if (rel.includes("\0")) return { ok: false, reason: "nul" }; + const lexicalRoot = resolve(root); + const rootReal = yield { op: "realpath", path: lexicalRoot }; + if (!rootReal.ok) { + if (policy.missingRoot === "refuse") return { ok: false, reason: "missing-root" }; + if (rootReal.error.code !== "ENOENT") return { ok: false, reason: "error", error: rootReal.error }; + // Present but unresolvable means a dangling link stands in its place. + const entry = yield { op: "lstat", path: lexicalRoot }; + if (entry.ok) return { ok: false, reason: "dangling" }; + if (!unresolvable(entry)) return { ok: false, reason: "error", error: entry.error }; + const lexical = resolve(lexicalRoot, rel); + if (!isWithin(lexicalRoot, lexical, CANONICAL)) return { ok: false, reason: "escape" }; + // Nothing below a missing root exists to be followed. + return { ok: true, root: lexicalRoot, lexical, canonical: lexical }; + } + const absRoot = rootReal.value; + const lexical = resolve(absRoot, rel); + if (!isWithin(absRoot, lexical, CANONICAL)) return { ok: false, reason: "escape" }; + if (policy.components === "final") { + const contained = yield* canonicalise(absRoot, lexical, policy); + return contained.ok ? { ...contained, lexical } : contained; + } + // Each component in order, from the root down: a link refused here is + // refused before it is followed, and every existing prefix must canonicalise + // inside, not only the whole path. + let prefix = absRoot; + const prefixes = [absRoot]; + for (const segment of relative(absRoot, lexical).split(sep)) { + if (!segment) continue; + prefix = join(prefix, segment); + prefixes.push(prefix); + } + let canonical = absRoot; + for (const path of prefixes) { + if (policy.refuseLinkAt?.(path, absRoot)) { + const entry = yield { op: "lstat", path }; + if (entry.ok && entry.link) return { ok: false, reason: "refused-link" }; + } + const contained = yield* canonicalise(absRoot, path, policy); + if (!contained.ok) return contained; + canonical = contained.canonical; + } + return { ok: true, root: absRoot, lexical, canonical }; +} + +/** {@link resolveContained}, synchronously. */ +export function resolveContainedSync(root: string, rel: string, policy: ContainmentPolicy): ContainedPath { + const steps = containedSteps(root, rel, policy); + let step = steps.next(); + while (!step.done) step = steps.next(querySync(step.value)); + return step.value; +} + +/** + * Resolve `rel` under `root` and check that it stays inside, following + * symlinks, under the caller's {@link ContainmentPolicy}. Each call reads the + * filesystem again: the answer describes the moment of the call, so a + * caller that opens the path later still owns the race between the two. + */ +export async function resolveContained(root: string, rel: string, policy: ContainmentPolicy): Promise { + const steps = containedSteps(root, rel, policy); + let step = steps.next(); + while (!step.done) step = steps.next(await queryAsync(step.value)); + return step.value; +} diff --git a/packages/common/tests/safe-path.test.ts b/packages/common/tests/safe-path.test.ts new file mode 100644 index 0000000000..e6c897d33d --- /dev/null +++ b/packages/common/tests/safe-path.test.ts @@ -0,0 +1,176 @@ +import { afterAll, describe, expect, test } from "bun:test"; +import { mkdirSync, mkdtempSync, realpathSync, renameSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, relative, sep } from "node:path"; + +import { + isWithin, + resolveContained, + resolveContainedSync, + type ContainedPath, + type ContainmentPolicy, + type WithinRule, +} from "../src/safe-path"; + +describe("isWithin(root, path, rule)", () => { + // Columns: equality, child, sibling prefix, parent, root `/` (absolute, + // itself, relative), trailing separator on the root, unnormalised paths. + const CASES: [string, string][] = [ + ["/a/b", "/a/b"], ["/a/b", "/a/b/c"], ["/a/b", "/a/bc"], ["/a/b", "/a"], + ["/", "/x"], ["/", "/"], ["/", "x"], + ["/a/b/", "/a/b/c"], ["/a/b/", "/a/b"], + ["/a/b", "/a/b/"], ["/a/b", "/a/b/../c"], ["/a/b", "/a/b/..c"], ["/a/b", "/a/b//c"], + ]; + const row = (rule?: WithinRule) => CASES.map(([root, path]) => (isWithin(root, path, rule) ? "T" : "-")).join(" "); + + // Every combination a caller uses (#2506), each written out. + test("the default: root included, `/` appended to any root, strings as given", () => { + expect(row()).toBe("T T - - - T - - - T T T T"); + expect(row({ includeRoot: true, separator: "/", trailingSeparator: "append", resolvePaths: false })).toBe(row()); + }); + + test("a trailing separator on the root is its boundary, so `/` holds every absolute path", () => { + expect(row({ trailingSeparator: "boundary" })).toBe("T T - - T T - T - T T T T"); + }); + + test("resolved first, root included (relative()-based callers)", () => { + expect(row({ resolvePaths: true, separator: sep, trailingSeparator: "boundary" })).toBe("T T - - T T T T T T - T T"); + }); + + test("resolved first, root excluded", () => { + expect(row({ includeRoot: false, resolvePaths: true, separator: sep, trailingSeparator: "boundary" })) + .toBe("- T - - T - T T - - - T T"); + }); + + test("the separator is a parameter", () => { + expect(isWithin("C:\\a", "C:\\a\\b", { separator: "\\" })).toBe(true); + expect(isWithin("C:\\a", "C:\\ab", { separator: "\\" })).toBe(false); + expect(isWithin("C:\\a", "C:\\a/b", { separator: "\\" })).toBe(false); + expect(isWithin("/a", "/a\\b", { separator: "\\" })).toBe(true); + }); + + test("the sibling prefix is never within, under any rule", () => { + for (const rule of [{}, { trailingSeparator: "boundary" }, { resolvePaths: true }, { includeRoot: false }] as WithinRule[]) { + expect(isWithin("/srv/brain", "/srv/brain-other/x", rule)).toBe(false); + expect(isWithin("/srv/brain", "/srv/brainx", rule)).toBe(false); + } + }); + + test("the argument order is root first", () => { + expect(isWithin("/a", "/a/b")).toBe(true); + expect(isWithin("/a/b", "/a")).toBe(false); + }); +}); + +const base = realpathSync(mkdtempSync(join(tmpdir(), "brain-common-safe-path-"))); +afterAll(() => rmSync(base, { recursive: true, force: true })); +const root = join(base, "brain"); +const outside = join(base, "brain-other"); +mkdirSync(join(root, "notes"), { recursive: true }); +mkdirSync(join(root, ".brain/scratch"), { recursive: true }); +mkdirSync(outside); +writeFileSync(join(root, "notes/a.md"), "a"); +writeFileSync(join(outside, "secret.md"), "s"); +symlinkSync("notes", join(root, "link-in")); +symlinkSync(outside, join(root, "link-out")); +symlinkSync("notes/missing", join(root, "dangling-in")); +symlinkSync(join(outside, "missing"), join(root, "dangling-out")); +symlinkSync("cycle-b", join(root, "cycle-a")); +symlinkSync("cycle-a", join(root, "cycle-b")); +symlinkSync(outside, join(root, "bounce")); +symlinkSync(join(root, "notes"), join(outside, "back")); +symlinkSync("../../notes", join(root, ".brain/scratch/link")); +symlinkSync(root, join(base, "root-link")); +// A dangling chain that leaves the root and comes back to a missing target inside. +symlinkSync(join(root, "notes/missing"), join(outside, "dangling-back")); +symlinkSync(join(outside, "dangling-back"), join(root, "dangling-bounce")); + +const FINAL_FOLLOW: ContainmentPolicy = { missingRoot: "refuse", danglingLinks: "follow", components: "final" }; +const EVERY_REFUSE: ContainmentPolicy = { missingRoot: "lexical", danglingLinks: "refuse", components: "every" }; + +/** `canonical` (and `lexical` when it differs) relative to the fixture base, or the refusal. */ +function show(result: ContainedPath): string { + if (!result.ok) return result.reason === "error" ? `error ${result.error.code}` : `refused ${result.reason}`; + const canonical = relative(base, result.canonical); + const lexical = relative(base, result.lexical); + return canonical === lexical ? canonical : `${canonical} (as ${lexical})`; +} + +/** Both variants, which must agree. */ +async function both(at: string, rel: string, policy: ContainmentPolicy): Promise { + const sync = show(resolveContainedSync(at, rel, policy)); + expect(show(await resolveContained(at, rel, policy))).toBe(sync); + return sync; +} + +describe("resolveContained: one algorithm, sync and async", () => { + const rows: [string, string, string][] = [ + // rel, final + follow, every + refuse + ["notes/a.md", "brain/notes/a.md", "brain/notes/a.md"], + ["notes/new.md", "brain/notes/new.md", "brain/notes/new.md"], + ["a/b/c.md", "brain/a/b/c.md", "brain/a/b/c.md"], + ["", "brain", "brain"], + ["../brain-other/secret.md", "refused escape", "refused escape"], + ["notes/../../brain-other", "refused escape", "refused escape"], + ["a\0b", "refused nul", "refused nul"], + ["link-in/a.md", "brain/notes/a.md (as brain/link-in/a.md)", "brain/notes/a.md (as brain/link-in/a.md)"], + // A symlinked parent of a file that does not exist yet. + ["link-out/new.md", "refused escape", "refused escape"], + ["link-in/new.md", "brain/notes/new.md (as brain/link-in/new.md)", "brain/notes/new.md (as brain/link-in/new.md)"], + ["dangling-in", "brain/notes/missing (as brain/dangling-in)", "refused dangling"], + ["dangling-in/x", "brain/notes/missing/x (as brain/dangling-in/x)", "refused dangling"], + ["dangling-out", "refused escape", "refused dangling"], + // Followed, the first hop already leaves the root: refused there, even + // though the chain ends inside. + ["dangling-bounce", "refused escape", "refused dangling"], + // A dangling cycle: followed, it runs out of the link budget. + ["cycle-a", "refused link-budget", "refused dangling"], + ["cycle-a/x", "refused link-budget", "refused dangling"], + // Out through one link and back through another. + ["bounce/back/a.md", "brain/notes/a.md (as brain/bounce/back/a.md)", "refused escape"], + ]; + for (const [rel, finalFollow, everyRefuse] of rows) { + test(JSON.stringify(rel), async () => { + expect(await both(root, rel, FINAL_FOLLOW)).toBe(finalFollow); + expect(await both(root, rel, EVERY_REFUSE)).toBe(everyRefuse); + }); + } + + test("an absolute request is resolved like any other: inside is accepted", async () => { + expect(await both(root, join(root, "notes/a.md"), FINAL_FOLLOW)).toBe("brain/notes/a.md"); + expect(await both(root, "/etc/passwd", FINAL_FOLLOW)).toBe("refused escape"); + }); + + test("a root that is itself a symlink resolves against its target", async () => { + expect(await both(join(base, "root-link"), "notes/a.md", FINAL_FOLLOW)).toBe("brain/notes/a.md"); + expect(await both(join(base, "root-link"), "link-out/x", EVERY_REFUSE)).toBe("refused escape"); + }); + + test("a missing root: refused, or the lexical path; never through a dangling link or a file", async () => { + expect(await both(join(base, "nope"), "notes/a.md", FINAL_FOLLOW)).toBe("refused missing-root"); + expect(await both(join(base, "nope"), "notes/a.md", EVERY_REFUSE)).toBe("nope/notes/a.md"); + expect(await both(join(base, "nope"), "../brain/notes", EVERY_REFUSE)).toBe("refused escape"); + expect(await both(join(root, "dangling-in"), "x", EVERY_REFUSE)).toBe("refused dangling"); + writeFileSync(join(base, "file"), ""); + expect(await both(join(base, "file/x"), "y", EVERY_REFUSE)).toBe("error ENOTDIR"); + }); + + test("refuseLinkAt refuses a link at a chosen component before following it", async () => { + const policy: ContainmentPolicy = { ...EVERY_REFUSE, refuseLinkAt: (path, absRoot) => isWithin(join(absRoot, ".brain"), path) }; + expect(await both(root, ".brain/scratch/link/a.md", policy)).toBe("refused refused-link"); + expect(await both(root, ".brain/scratch/link/a.md", EVERY_REFUSE)).toBe("brain/notes/a.md (as brain/.brain/scratch/link/a.md)"); + expect(await both(root, "link-in/a.md", policy)).toBe("brain/notes/a.md (as brain/link-in/a.md)"); + // Only the component walk consults it. + expect(await both(root, ".brain/scratch/link/a.md", { ...FINAL_FOLLOW, refuseLinkAt: () => true })).toBe("brain/notes/a.md (as brain/.brain/scratch/link/a.md)"); + }); + + test("each call reads the filesystem again: a directory swapped for an escaping link is refused", async () => { + const swap = join(root, "swap"); + mkdirSync(swap); + expect(await both(root, "swap/new.md", FINAL_FOLLOW)).toBe("brain/swap/new.md"); + renameSync(swap, join(base, "swapped-away")); + symlinkSync(outside, swap); + expect(await both(root, "swap/new.md", FINAL_FOLLOW)).toBe("refused escape"); + expect(await both(root, "swap/new.md", EVERY_REFUSE)).toBe("refused escape"); + }); +}); diff --git a/packages/core/src/lib/safe-path.ts b/packages/core/src/lib/safe-path.ts index 4dd66513dd..27e162362b 100644 --- a/packages/core/src/lib/safe-path.ts +++ b/packages/core/src/lib/safe-path.ts @@ -1,82 +1,26 @@ import { randomBytes } from "crypto"; -import { closeSync, fchmodSync, linkSync, lstatSync, mkdirSync, openSync, realpathSync, readlinkSync, renameSync, rmSync, writeSync } from "fs"; +import { resolveContainedSync, type ContainmentPolicy } from "@schlessera/brain-common/internal/safe-path"; +import { closeSync, fchmodSync, linkSync, lstatSync, mkdirSync, openSync, realpathSync, renameSync, rmSync, writeSync } from "fs"; import type { Stats } from "fs"; -import { basename, dirname, isAbsolute, join, resolve, sep } from "path"; +import { basename, dirname, join } from "path"; + +const CORE_CONTAINMENT: ContainmentPolicy = { missingRoot: "refuse", danglingLinks: "follow", components: "final" }; /** * Resolve a relative path and verify it stays inside `root`, following * symlinks (realpath) so a symlink inside the repo can't escape it. - * The trailing-slash comparison rejects sibling-prefix paths like - * `../brain-other/x.md` that a bare startsWith(root) would accept. * Returns the canonical absolute path, or null if the path escapes (or the * root itself does not exist). + * + * core's row of the shared resolver (`@schlessera/brain-common/internal/safe-path`, + * #2506): synchronous, `null` for every refusal, an absolute path accepted + * when it lies inside the root, `..` accepted while the result stays inside, + * a dangling link followed to a target that must stay inside, and only the + * final path checked, not each component on the way. */ export function safeResolve(root: string, relPath: string): string | null { - // A NUL byte would make the later fs call throw ERR_INVALID_ARG_VALUE — - // reject it as a containment failure, not a deferred TypeError. - if (relPath.includes("\0")) return null; - - let rootReal: string; - try { - rootReal = realpathSync(resolve(root)); - } catch { - return null; - } - // Separator-aware containment check (backslash paths on Windows). - const contains = (p: string) => p === rootReal || p.startsWith(rootReal + sep); - const fullPath = resolve(rootReal, relPath); - if (!contains(fullPath)) return null; - // Canonicalize through symlinks. When the target (or a stretch of its - // parents) doesn't exist yet, canonicalize the nearest EXISTING ancestor and - // re-append the missing tail — a purely lexical fallback would let a - // symlinked parent directory smuggle a to-be-created file outside the root. - let existing = fullPath; - const tail: string[] = []; - // Symlink-hop budget: a dangling-link CYCLE (a→b, b→a) throws in realpath - // but resolves link-by-link here — bound it like the kernel does. - let hops = 0; - for (;;) { - let real: string; - try { - real = realpathSync(existing); - } catch { - // realpath failed: either the entry is genuinely absent, or it is a - // DANGLING symlink (exists, target missing). The two are different - // security cases — a write through a dangling link is created AT THE - // LINK TARGET, so it must be resolved and re-checked, never treated as - // "doesn't exist yet". - let linkTarget: string | null = null; - try { - if (lstatSync(existing).isSymbolicLink()) { - linkTarget = readlinkSync(existing); - } - } catch { - // lstat failed too → the entry really doesn't exist. - } - if (linkTarget !== null) { - if (++hops > 40) return null; - const resolvedTarget = isAbsolute(linkTarget) - ? resolve(linkTarget) - : resolve(dirname(existing), linkTarget); - // Re-enter containment checking with the link's target substituted in. - const rejoined = tail.length > 0 ? join(resolvedTarget, ...tail) : resolvedTarget; - if (!contains(rejoined)) return null; - existing = rejoined; - tail.length = 0; - continue; - } - tail.unshift(basename(existing)); - const parent = dirname(existing); - // The loop always terminates at rootReal (it exists), but guard the - // filesystem root anyway. - if (parent === existing) return null; - existing = parent; - continue; - } - const candidate = tail.length > 0 ? join(real, ...tail) : real; - if (!contains(candidate)) return null; - return candidate; - } + const contained = resolveContainedSync(root, relPath, CORE_CONTAINMENT); + return contained.ok ? contained.canonical : null; } /** diff --git a/packages/core/src/lib/scratch.ts b/packages/core/src/lib/scratch.ts index 3fff9f8cfc..02cd405c1b 100644 --- a/packages/core/src/lib/scratch.ts +++ b/packages/core/src/lib/scratch.ts @@ -46,10 +46,14 @@ import { import type { Stats } from "fs"; import { tmpdir } from "os"; import { basename, dirname, join, relative, resolve, sep } from "path"; +import { BRAIN_SCRATCH_DIR } from "@schlessera/brain-common/internal/worker-areas"; import { modeOf, WriteRefusedError, writeExclusive, writeFileSafely } from "./safe-path.js"; -/** Repo-relative scratch directory. Every mechanism that needs it reads this. */ -export const SCRATCH_DIR = ".brain/scratch"; +/** + * Repo-relative scratch directory. Every mechanism that needs it reads this; + * the value is the one the SDK and server share (`BRAIN_SCRATCH_DIR`, #2506). + */ +export const SCRATCH_DIR = BRAIN_SCRATCH_DIR; /** Files older than this are pruned. */ export const SCRATCH_TTL_MS = 7 * 24 * 60 * 60 * 1000; diff --git a/packages/core/tests/containment-rows.test.ts b/packages/core/tests/containment-rows.test.ts new file mode 100644 index 0000000000..df986182a6 --- /dev/null +++ b/packages/core/tests/containment-rows.test.ts @@ -0,0 +1,125 @@ +/** + * core's row of the resolver matrix (#2506): `safeResolve(root, rel)` is + * synchronous, returns the canonical path or `null`, accepts an absolute path + * that lies inside the root, accepts `..` while the result stays inside, + * follows a dangling link whose target stays inside, and refuses everything + * when the root's realpath fails. Written against the copy core carried + * before the shared `@schlessera/brain-common/internal/safe-path`, and kept + * unchanged across the move. + */ +import { afterAll, describe, expect, test } from "bun:test"; +import { mkdirSync, mkdtempSync, realpathSync, renameSync, rmSync, symlinkSync, writeFileSync } from "fs"; +import { tmpdir } from "os"; +import { join, relative } from "path"; + +import { SCRATCH_DIR } from "../src/lib/scratch"; +import { safeResolve } from "../src/lib/safe-path"; + +const base = realpathSync(mkdtempSync(join(tmpdir(), "brain-kit-containment-rows-"))); +afterAll(() => rmSync(base, { recursive: true, force: true })); +const root = join(base, "brain"); +const outside = join(base, "brain-other"); + +mkdirSync(join(root, "notes/sub"), { recursive: true }); +mkdirSync(outside); +mkdirSync(join(root, ".brain/scratch"), { recursive: true }); +writeFileSync(join(root, "notes/a.md"), "a"); +writeFileSync(join(root, "file.md"), "f"); +writeFileSync(join(outside, "secret.md"), "s"); +writeFileSync(join(root, ".brain/scratch/s.txt"), "s"); +symlinkSync("notes", join(root, "link-in")); +symlinkSync(outside, join(root, "link-out")); +symlinkSync("notes/missing", join(root, "dangling-in")); +symlinkSync(join(outside, "missing"), join(root, "dangling-out")); +symlinkSync("cycle-b", join(root, "cycle-a")); +symlinkSync("cycle-a", join(root, "cycle-b")); +symlinkSync(outside, join(root, "bounce")); +symlinkSync(join(root, "notes"), join(outside, "back")); +symlinkSync("../../notes", join(root, ".brain/scratch/link")); +symlinkSync(root, join(base, "root-link")); +// A dangling chain that leaves the root and comes back to a missing target inside. +symlinkSync(join(root, "notes/missing"), join(outside, "dangling-back")); +symlinkSync(join(outside, "dangling-back"), join(root, "dangling-bounce")); + +/** The answer relative to the fixture base, or `refused`. */ +const answer = (path: string | null) => (path === null ? "refused" : relative(base, path) || "."); + +describe("core safeResolve(root, rel): its resolver row", () => { + const rows: [string, string][] = [ + ["notes/a.md", "brain/notes/a.md"], + ["notes/new.md", "brain/notes/new.md"], + ["a/b/c.md", "brain/a/b/c.md"], + ["", "brain"], + [".", "brain"], + ["./notes/a.md", "brain/notes/a.md"], + ["notes//a.md", "brain/notes/a.md"], + ["notes/a.md/", "brain/notes/a.md"], + ["file.md/x", "brain/file.md/x"], + // `..` is accepted while the result stays inside. + ["notes/../notes/a.md", "brain/notes/a.md"], + ["notes/../../x", "refused"], + // Sibling prefix: `brain-other` starts with `brain`. + ["../brain-other/secret.md", "refused"], + // Absolute: accepted only inside the root. + [join(root, "notes/a.md"), "brain/notes/a.md"], + ["/etc/passwd", "refused"], + // Windows syntax is not checked. + ["a:b", "brain/a:b"], + ["a\\b", "brain/a\\b"], + ["a\0b", "refused"], + // Links: canonical answers, escapes refused, including for a file that + // does not exist yet under a symlinked parent. + ["link-in/a.md", "brain/notes/a.md"], + ["link-in/new.md", "brain/notes/new.md"], + ["link-out/secret.md", "refused"], + ["link-out/new.md", "refused"], + // A dangling link is followed to its target, which must stay inside. + ["dangling-in", "brain/notes/missing"], + ["dangling-in/x", "brain/notes/missing/x"], + ["dangling-out", "refused"], + // 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"], + // Scratch is not special to the resolver. + [".brain", "brain/.brain"], + [".brain/scratch/s.txt", "brain/.brain/scratch/s.txt"], + [".brain/scratch/link", "brain/notes"], + [".brain/scratch/link/a.md", "brain/notes/a.md"], + ]; + for (const [rel, expected] of rows) { + test(`${JSON.stringify(rel.startsWith(base) ? "/" + relative(base, rel) : rel)} -> ${expected}`, () => { + expect(answer(safeResolve(root, rel))).toBe(expected); + }); + } + + test("a root that is itself a symlink resolves against its target", () => { + expect(answer(safeResolve(join(base, "root-link"), "notes/a.md"))).toBe("brain/notes/a.md"); + }); + + test("a root whose realpath fails refuses everything", () => { + expect(safeResolve(join(base, "nope"), "notes/a.md")).toBeNull(); + expect(safeResolve(join(root, "dangling-in"), "x")).toBeNull(); + expect(safeResolve(join(root, "file.md/x"), "x")).toBeNull(); + }); + + test("each call reads the filesystem again: a directory swapped for an escaping link is refused", () => { + const swap = join(root, "swap"); + mkdirSync(swap); + expect(answer(safeResolve(root, "swap/new.md"))).toBe("brain/swap/new.md"); + renameSync(swap, join(base, "swapped-away")); + symlinkSync(outside, swap); + expect(safeResolve(root, "swap/new.md")).toBeNull(); + rmSync(swap); + renameSync(join(base, "swapped-away"), swap); + expect(answer(safeResolve(root, "swap/new.md"))).toBe("brain/swap/new.md"); + }); +}); + +test("core's scratch area is .brain/scratch", () => { + expect(SCRATCH_DIR).toBe(".brain/scratch"); +}); diff --git a/packages/ui-sdk/src/server/bridge-tools/mask.ts b/packages/ui-sdk/src/server/bridge-tools/mask.ts index 7eeaa51f42..d76c82eef8 100644 --- a/packages/ui-sdk/src/server/bridge-tools/mask.ts +++ b/packages/ui-sdk/src/server/bridge-tools/mask.ts @@ -8,6 +8,8 @@ import type { RequestImageMaskInput, } from "../../tool-contracts/index.js"; import type { BackendBridge } from "../backend.js"; +import { isWithin } from "@schlessera/brain-common/internal/safe-path"; +import { BRAIN_SCRATCH_DIR } from "@schlessera/brain-common/internal/worker-areas"; import { resolveInRepo } from "./resolve-in-repo.js"; import { brainGitSteps } from "../maintenance-worker.js"; import { runWorkerStepsAsync, runWorkerStepsSync, type WorkerSteps } from "../worker-steps.js"; @@ -117,13 +119,15 @@ export async function handleRequestImageMask( * excluded by git. The write itself goes to a temporary sibling and is * renamed onto its name, and the host's prune runs after it. * - * Kept in lockstep with `packages/core/src/lib/scratch.ts` (`SCRATCH_DIR`, - * `scratchIgnored`, `scratchDir`, `writeScratchFile`): the SDK ports the rule, - * as it does for `resolveInRepo`, instead of depending on `@schlessera/brain`. + * The directory is the shared `BRAIN_SCRATCH_DIR` (#2506). The rules are + * core's (`packages/core/src/lib/scratch.ts`: `scratchIgnored`, `scratchDir`, + * `writeScratchFile`), applied here through descriptors and the maintenance + * worker, since the SDK does not depend on `@schlessera/brain`. */ -const SCRATCH_DIR = ".brain/scratch"; +const SCRATCH_DIR = BRAIN_SCRATCH_DIR; -const under = (dir: string, path: string) => path === dir || path.startsWith(dir + sep); +/** Whether `path` is `dir` or below it, by the platform separator. */ +export const under = (dir: string, path: string) => isWithin(dir, path, { separator: sep }); function isSymlink(path: string): boolean { try { diff --git a/packages/ui-sdk/src/server/bridge-tools/resolve-in-repo.ts b/packages/ui-sdk/src/server/bridge-tools/resolve-in-repo.ts index ab97c4f404..7b2da28def 100644 --- a/packages/ui-sdk/src/server/bridge-tools/resolve-in-repo.ts +++ b/packages/ui-sdk/src/server/bridge-tools/resolve-in-repo.ts @@ -1,64 +1,18 @@ -import { lstatSync, realpathSync, readlinkSync } from "fs"; -import { basename, dirname, isAbsolute, join, resolve, sep } from "path"; +import { resolveContainedSync, type ContainmentPolicy } from "@schlessera/brain-common/internal/safe-path"; +import { isAbsolute } from "path"; + +const SDK_CONTAINMENT: ContainmentPolicy = { missingRoot: "refuse", danglingLinks: "follow", components: "final" }; /** * Resolve a repo-relative path without allowing a symlink to escape the repo. * - * Keep these semantics in lockstep with the reference implementation at - * `packages/core/src/lib/safe-path.ts` (`safeResolve`). The SDK deliberately - * ports that implementation instead of depending on `@schlessera/brain`. + * The SDK's row of the shared resolver (`@schlessera/brain-common/internal/safe-path`, + * #2506): core's (`safeResolve`), except that an absolute path is refused + * even when it lies inside the root. Synchronous, `null` for every refusal, + * the canonical path on success. */ export function resolveInRepo(root: string, relPath: string): string | null { - if (relPath.includes("\0") || isAbsolute(relPath)) return null; - - let rootReal: string; - try { - rootReal = realpathSync(resolve(root)); - } catch { - return null; - } - - const contains = (path: string) => - path === rootReal || path.startsWith(rootReal + sep); - const fullPath = resolve(rootReal, relPath); - if (!contains(fullPath)) return null; - - let existing = fullPath; - const tail: string[] = []; - let hops = 0; - for (;;) { - let real: string; - try { - real = realpathSync(existing); - } catch { - let linkTarget: string | null = null; - try { - if (lstatSync(existing).isSymbolicLink()) { - linkTarget = readlinkSync(existing); - } - } catch { - // lstat failed too: this entry is genuinely absent. - } - if (linkTarget !== null) { - if (++hops > 40) return null; - const resolvedTarget = isAbsolute(linkTarget) - ? resolve(linkTarget) - : resolve(dirname(existing), linkTarget); - const rejoined = - tail.length > 0 ? join(resolvedTarget, ...tail) : resolvedTarget; - if (!contains(rejoined)) return null; - existing = rejoined; - tail.length = 0; - continue; - } - tail.unshift(basename(existing)); - const parent = dirname(existing); - if (parent === existing) return null; - existing = parent; - continue; - } - const candidate = tail.length > 0 ? join(real, ...tail) : real; - if (!contains(candidate)) return null; - return candidate; - } + if (isAbsolute(relPath)) return null; + const contained = resolveContainedSync(root, relPath, SDK_CONTAINMENT); + return contained.ok ? contained.canonical : null; } diff --git a/packages/ui-sdk/src/server/maintenance-env-masks.ts b/packages/ui-sdk/src/server/maintenance-env-masks.ts index 7e5b9e9aab..23c43be0ea 100644 --- a/packages/ui-sdk/src/server/maintenance-env-masks.ts +++ b/packages/ui-sdk/src/server/maintenance-env-masks.ts @@ -1,4 +1,5 @@ /** One alias resolver, driven synchronously by the host or asynchronously by its owned stage. */ +import { isWithin } from "@schlessera/brain-common/internal/safe-path"; import { lstatSync, readdirSync, readlinkSync } from "node:fs"; import { dirname, isAbsolute } from "node:path"; import { isEnvName } from "./protected-paths.js"; @@ -6,7 +7,7 @@ import { isEnvName } from "./protected-paths.js"; export type EnvMaskMetadata = { kind: "directory" | "file" | "symlink" | "other"; target?: string }; export type EnvMaskQuery = { operation: "list" | "stat"; path: string }; type Reply = string[] | EnvMaskMetadata | undefined; -const within = (dir: string, path: string) => path === dir || path.startsWith(`${dir}/`); +export const within = (dir: string, path: string) => isWithin(dir, path); /** No contents are read. Queries preserve the worker's names through held input aliases. */ export function* maintenanceEnvMaskQueries(source: string, brain: string, diff --git a/packages/ui-sdk/src/server/native-reference-pool.ts b/packages/ui-sdk/src/server/native-reference-pool.ts index e81c0cfd6b..ff61e92cf6 100644 --- a/packages/ui-sdk/src/server/native-reference-pool.ts +++ b/packages/ui-sdk/src/server/native-reference-pool.ts @@ -15,6 +15,7 @@ * allocate before work starts. Measured use replaces that reservation as it * materializes; sealing converts the rest to measured allocation. */ +import { isWithin } from "@schlessera/brain-common/internal/safe-path"; import { constants, closeSync, existsSync, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, readlinkSync, renameSync, rmdirSync, statSync, symlinkSync, unlinkSync, writeFileSync, ftruncateSync, chownSync, chmodSync, realpathSync } from "node:fs"; import { randomUUID } from "node:crypto"; @@ -58,7 +59,8 @@ export interface NativeReferencePoolConfig { export type QualifiedReferencePoolConfig = Required> & { headroomLedgerPath?: string }; const fixedPath = (path: unknown) => typeof path === "string" && isAbsolute(path) && !path.includes("\0") && !path.split("/").includes("..") && path.length > 1; -const inside = (child: string, parent: string) => child === parent || child.startsWith(parent.endsWith("/") ? parent : parent + "/"); +/** Child first: `inside(a, b)` reads as "a is inside b". */ +export const inside = (child: string, parent: string) => isWithin(parent, child, { trailingSeparator: "boundary" }); const page = (value: unknown): value is number => Number.isSafeInteger(value) && (value as number) > 0 && (value as number) % 4096 === 0; export function validateNativeReferencePoolConfig(pool: NativeReferencePoolConfig, store: { storePath: string; fsid: string; socketPath: string }): QualifiedReferencePoolConfig { diff --git a/packages/ui-sdk/src/server/worker-file-observer.ts b/packages/ui-sdk/src/server/worker-file-observer.ts index 253a645b77..f2f3575fb4 100644 --- a/packages/ui-sdk/src/server/worker-file-observer.ts +++ b/packages/ui-sdk/src/server/worker-file-observer.ts @@ -1,4 +1,5 @@ /** Read the actual host-owned mount sources; never evaluates repository code. */ +import { isWithin } from "@schlessera/brain-common/internal/safe-path"; import { createHash } from "node:crypto"; import { closeSync, constants, fstatSync, openSync, readlinkSync } from "node:fs"; import { isAbsolute, relative, resolve } from "node:path"; @@ -6,7 +7,8 @@ import { nativeFileVersionFromFd, type NativeFileVersion } from "./native-file-v export interface ObservedWorkerFile { key: string; version: NativeFileVersion } interface Source { worker: string; host: string; rel: string } -const within = (path: string, root: string) => path === root || path.startsWith(root + "/"); +/** Path first: it reads as "this path is within that root" at each call site. */ +export const within = (path: string, root: string) => isWithin(root, path); const EMPTY: NativeFileVersion = { status: "known", hash: createHash("sha256").update("").digest("hex") }; /** Sources come only from the launcher's resolved mounts, and live only until worker exit. */ diff --git a/packages/ui-sdk/src/server/worker-launcher.ts b/packages/ui-sdk/src/server/worker-launcher.ts index 76b8e3691f..6f1a5e77a7 100644 --- a/packages/ui-sdk/src/server/worker-launcher.ts +++ b/packages/ui-sdk/src/server/worker-launcher.ts @@ -1,3 +1,4 @@ +import { isWithin } from "@schlessera/brain-common/internal/safe-path"; import { maintenanceEnvMasks } from "./maintenance-env-masks.js"; import { registerWorkerRtk } from "./worker-rtk.js"; import { createWorkerStatusPipe, createWorkerStatusPipeSteps } from "./worker-status.js"; @@ -725,7 +726,7 @@ export function workerCommand(input: WorkerLaunch): string[] { } /** Whether `path` is `dir` or lies below it. */ -const within = (dir: string, path: string) => path === dir || path.startsWith(`${dir}/`); +export const within = (dir: string, path: string) => isWithin(dir, path); /** Resolve aliases even when the final installed entry is not present yet. */ function runtimeCanonicalName(requested: string): string { diff --git a/packages/ui-sdk/src/server/worker-rtk.ts b/packages/ui-sdk/src/server/worker-rtk.ts index ee44c88ad7..4daf8220b8 100644 --- a/packages/ui-sdk/src/server/worker-rtk.ts +++ b/packages/ui-sdk/src/server/worker-rtk.ts @@ -1,4 +1,5 @@ /** Optional installed RTK evidence belongs to one kernel-observed live worker. */ +import { isWithin } from "@schlessera/brain-common/internal/safe-path"; import { accessSync, constants, readFileSync, realpathSync, statSync } from "node:fs"; import { dirname, isAbsolute, resolve } from "node:path"; import { rewriteInstalledRtk } from "./rtk.js"; @@ -18,7 +19,7 @@ export function registerWorkerRtk(worker: LaunchedWorker, pid: number, input: Wo void worker.exited.then(() => { view.alive = false; }, () => { view.alive = false; }); } catch { /* An unreadable worker cannot authorize an optional rewrite. */ } } -function within(root: string, path: string): boolean { return path === root || path.startsWith(root + "/"); } +export function within(root: string, path: string): boolean { return isWithin(root, path); } /** ELF64 native static executables, including dependency-free static PIE. */ export function isStaticNativeElf(path: string): boolean { const bytes = readFileSync(path); diff --git a/packages/ui-sdk/src/server/worker-turn-temp.ts b/packages/ui-sdk/src/server/worker-turn-temp.ts index 5097b6183d..abde5d03a8 100644 --- a/packages/ui-sdk/src/server/worker-turn-temp.ts +++ b/packages/ui-sdk/src/server/worker-turn-temp.ts @@ -20,6 +20,7 @@ * while it is copied. The destination is opened the same way below * `.brain/scratch/turns//`. */ +import { isWithin } from "@schlessera/brain-common/internal/safe-path"; import { hasIdentityReadRoot, prepareRecoveredWorkerFile, recoveredWorkerFile } from "./worker-identity-reader.js"; import { closeSync, constants, fstatSync, lstatSync, mkdirSync, openSync, readdirSync, readSync, realpathSync, rmdirSync, statfsSync, unlinkSync, writeSync } from "node:fs"; @@ -45,7 +46,7 @@ const LINK_MAX_CHARS = 2000; const COPY_CHUNK = 1024 * 1024; /** Whether `path` is `dir` or lies below it. */ -const within = (dir: string, path: string) => path === dir || path.startsWith(dir.endsWith("/") ? dir : `${dir}/`); +export const within = (dir: string, path: string) => isWithin(dir, path, { trailingSeparator: "boundary" }); /** * A server-side path that opens the directory a held descriptor names. diff --git a/packages/ui-sdk/tests/bridge-tools.test.ts b/packages/ui-sdk/tests/bridge-tools.test.ts index 18204e68bc..aa813d745b 100644 --- a/packages/ui-sdk/tests/bridge-tools.test.ts +++ b/packages/ui-sdk/tests/bridge-tools.test.ts @@ -1,7 +1,7 @@ import { describe, expect, test } from "bun:test"; import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync } from "fs"; import { tmpdir } from "os"; -import { isAbsolute, join } from "path"; +import { basename, isAbsolute, join } from "path"; import { BRIDGE_TOOL_POSTURE } from "../src/tool-contracts/bridge.js"; import { piMaskFilename } from "../src/server/bridge-tools/mask.js"; @@ -68,6 +68,20 @@ describe("resolveInRepo", () => { } }); + test("rejects a sibling directory that shares the root's name as a prefix", () => { + const root = mkdtempSync(join(tmpdir(), "bridge-path-root-")); + const sibling = `${root}-other`; + mkdirSync(sibling); + try { + symlinkSync(sibling, join(root, "sibling")); + expect(resolveInRepo(root, `../${basename(sibling)}/mask.png`)).toBeNull(); + expect(resolveInRepo(root, "sibling/mask.png")).toBeNull(); + } finally { + rmSync(root, { recursive: true, force: true }); + rmSync(sibling, { recursive: true, force: true }); + } + }); + test("rejects a symlink escape, including a missing tail below it", () => { const root = mkdtempSync(join(tmpdir(), "bridge-path-root-")); const outside = mkdtempSync(join(tmpdir(), "bridge-path-outside-")); diff --git a/packages/ui-sdk/tests/containment-rows.test.ts b/packages/ui-sdk/tests/containment-rows.test.ts new file mode 100644 index 0000000000..c847b959e0 --- /dev/null +++ b/packages/ui-sdk/tests/containment-rows.test.ts @@ -0,0 +1,165 @@ +/** + * The ui-sdk's rows of the containment matrices (#2506). `resolveInRepo(root, + * rel)` is core's resolver except that it refuses an absolute `rel`; the + * predicates each keep their own argument order, equality, root `/` and + * trailing-separator answers. Written against the copies the SDK carried + * before the shared `@schlessera/brain-common/internal/safe-path`, and kept + * unchanged across the move. + */ +import { afterAll, describe, expect, test } from "bun:test"; +import { mkdirSync, mkdtempSync, realpathSync, renameSync, rmSync, symlinkSync, writeFileSync } from "fs"; +import { tmpdir } from "os"; +import { join, relative } from "path"; + +import { maskInScratch, under as maskUnder } from "../src/server/bridge-tools/mask"; +import { resolveInRepo } from "../src/server/bridge-tools/resolve-in-repo"; +import { within as envMasksWithin } from "../src/server/maintenance-env-masks"; +import { inside as poolInside } from "../src/server/native-reference-pool"; +import { within as observerWithin } from "../src/server/worker-file-observer"; +import { within as launcherWithin } from "../src/server/worker-launcher"; +import { within as rtkWithin } from "../src/server/worker-rtk"; +import { within as turnTempWithin } from "../src/server/worker-turn-temp"; + +const base = realpathSync(mkdtempSync(join(tmpdir(), "brain-kit-containment-rows-"))); +afterAll(() => rmSync(base, { recursive: true, force: true })); +const root = join(base, "brain"); +const outside = join(base, "brain-other"); + +mkdirSync(join(root, "notes/sub"), { recursive: true }); +mkdirSync(outside); +mkdirSync(join(root, ".brain/scratch"), { recursive: true }); +writeFileSync(join(root, "notes/a.md"), "a"); +writeFileSync(join(root, "file.md"), "f"); +writeFileSync(join(outside, "secret.md"), "s"); +writeFileSync(join(root, ".brain/scratch/s.txt"), "s"); +symlinkSync("notes", join(root, "link-in")); +symlinkSync(outside, join(root, "link-out")); +symlinkSync("notes/missing", join(root, "dangling-in")); +symlinkSync(join(outside, "missing"), join(root, "dangling-out")); +symlinkSync("cycle-b", join(root, "cycle-a")); +symlinkSync("cycle-a", join(root, "cycle-b")); +symlinkSync(outside, join(root, "bounce")); +symlinkSync(join(root, "notes"), join(outside, "back")); +symlinkSync("../../notes", join(root, ".brain/scratch/link")); +symlinkSync(root, join(base, "root-link")); + +/** The answer relative to the fixture base, or `refused`. */ +const answer = (path: string | null) => (path === null ? "refused" : relative(base, path) || "."); + +describe("ui-sdk resolveInRepo(root, rel): its resolver row", () => { + const rows: [string, string][] = [ + ["notes/a.md", "brain/notes/a.md"], + ["notes/new.md", "brain/notes/new.md"], + ["a/b/c.md", "brain/a/b/c.md"], + ["", "brain"], + [".", "brain"], + ["./notes/a.md", "brain/notes/a.md"], + ["notes//a.md", "brain/notes/a.md"], + ["notes/a.md/", "brain/notes/a.md"], + ["file.md/x", "brain/file.md/x"], + // `..` is accepted while the result stays inside. + ["notes/../notes/a.md", "brain/notes/a.md"], + ["notes/../../x", "refused"], + // Sibling prefix: `brain-other` starts with `brain`. + ["../brain-other/secret.md", "refused"], + // Absolute: refused even inside the root (core accepts it). + [join(root, "notes/a.md"), "refused"], + ["/etc/passwd", "refused"], + // Windows syntax is not checked. + ["a:b", "brain/a:b"], + ["a\\b", "brain/a\\b"], + ["a\0b", "refused"], + ["link-in/a.md", "brain/notes/a.md"], + ["link-in/new.md", "brain/notes/new.md"], + ["link-out/secret.md", "refused"], + ["link-out/new.md", "refused"], + ["dangling-in", "brain/notes/missing"], + ["dangling-in/x", "brain/notes/missing/x"], + ["dangling-out", "refused"], + ["cycle-a", "refused"], + ["cycle-a/x", "refused"], + ["bounce/back/a.md", "brain/notes/a.md"], + [".brain", "brain/.brain"], + [".brain/scratch/s.txt", "brain/.brain/scratch/s.txt"], + [".brain/scratch/link", "brain/notes"], + [".brain/scratch/link/a.md", "brain/notes/a.md"], + ]; + for (const [rel, expected] of rows) { + test(`${JSON.stringify(rel.startsWith(base) ? "/" + relative(base, rel) : rel)} -> ${expected}`, () => { + expect(answer(resolveInRepo(root, rel))).toBe(expected); + }); + } + + test("a root that is itself a symlink resolves against its target", () => { + expect(answer(resolveInRepo(join(base, "root-link"), "notes/a.md"))).toBe("brain/notes/a.md"); + }); + + test("a root whose realpath fails refuses everything", () => { + expect(resolveInRepo(join(base, "nope"), "notes/a.md")).toBeNull(); + expect(resolveInRepo(join(root, "dangling-in"), "x")).toBeNull(); + expect(resolveInRepo(join(root, "file.md/x"), "x")).toBeNull(); + }); + + test("each call reads the filesystem again: a directory swapped for an escaping link is refused", () => { + const swap = join(root, "swap"); + mkdirSync(swap); + expect(answer(resolveInRepo(root, "swap/new.md"))).toBe("brain/swap/new.md"); + renameSync(swap, join(base, "swapped-away")); + symlinkSync(outside, swap); + expect(resolveInRepo(root, "swap/new.md")).toBeNull(); + rmSync(swap); + renameSync(join(base, "swapped-away"), swap); + expect(answer(resolveInRepo(root, "swap/new.md"))).toBe("brain/swap/new.md"); + }); + + test("the mask's scratch area is .brain/scratch, separator-bounded", () => { + const rootReal = realpathSync(root); + expect(maskInScratch(rootReal, ".brain/scratch/m.png", join(rootReal, "notes/m.png"))).toBe(true); + expect(maskInScratch(rootReal, "notes/m.png", join(rootReal, ".brain/scratch/m.png"))).toBe(true); + expect(maskInScratch(rootReal, ".brain/scratchy/m.png", join(rootReal, ".brain/scratchy/m.png"))).toBe(false); + expect(maskInScratch(rootReal, ".brain/m.png", join(rootReal, ".brain/m.png"))).toBe(false); + }); +}); + +/** + * Each predicate as `(root, path) -> answer`, whatever its own argument order. + * Columns: equality, child, sibling prefix, parent, root `/` (absolute, + * itself, relative), trailing separator on the root, a trailing separator or + * unnormalised segment on the path. + */ +const PREDICATE_CASES: [string, string][] = [ + ["/a/b", "/a/b"], ["/a/b", "/a/b/c"], ["/a/b", "/a/bc"], ["/a/b", "/a"], + ["/", "/x"], ["/", "/"], ["/", "x"], + ["/a/b/", "/a/b/c"], ["/a/b/", "/a/b"], + ["/a/b", "/a/b/"], ["/a/b", "/a/b/../c"], ["/a/b", "/a/b/..c"], ["/a/b", "/a/b//c"], +]; +// = c sp pa /x / rel tr trE p/ .. ..c // +const LITERAL_SLASH = "T T - - - T - - - T T T T"; +const TRAILING_TOLERATED = "T T - - T T - T - T T T T"; + +const rows: [string, (root: string, path: string) => boolean, string][] = [ + ["worker-launcher within(dir, path)", launcherWithin, LITERAL_SLASH], + ["worker-rtk within(root, path)", rtkWithin, LITERAL_SLASH], + ["worker-file-observer within(path, root)", (root, path) => observerWithin(path, root), LITERAL_SLASH], + ["maintenance-env-masks within(dir, path)", envMasksWithin, LITERAL_SLASH], + ["worker-turn-temp within(dir, path)", turnTempWithin, TRAILING_TOLERATED], + ["bridge-tools/mask under(dir, path)", maskUnder, LITERAL_SLASH], + ["native-reference-pool inside(child, parent)", (root, path) => poolInside(path, root), TRAILING_TOLERATED], +]; + +describe("ui-sdk containment predicates: their matrix rows", () => { + for (const [name, predicate, expected] of rows) { + test(name, () => { + expect(PREDICATE_CASES.map(([root, path]) => (predicate(root, path) ? "T" : "-")).join(" ")).toBe(expected); + }); + } + + test("argument order matters: each predicate is asymmetric in the order it declares", () => { + expect(launcherWithin("/a", "/a/b")).toBe(true); + expect(launcherWithin("/a/b", "/a")).toBe(false); + expect(observerWithin("/a/b", "/a")).toBe(true); + expect(observerWithin("/a", "/a/b")).toBe(false); + expect(poolInside("/a/b", "/a")).toBe(true); + expect(poolInside("/a", "/a/b")).toBe(false); + }); +}); diff --git a/packages/ui-server/src/brain/host-boundary.ts b/packages/ui-server/src/brain/host-boundary.ts index 50c6ea79f4..7163beafa4 100644 --- a/packages/ui-server/src/brain/host-boundary.ts +++ b/packages/ui-server/src/brain/host-boundary.ts @@ -21,6 +21,7 @@ * only ever written through the server's own routes, as before 0.42. That * legacy host path is refused while a provider folder policy is active (#2284). */ +import { isWithin } from "@schlessera/brain-common/internal/safe-path"; import { brainWorkerPath } from "@schlessera/brain-common/internal/worker-areas"; import { existsSync, realpathSync } from "node:fs"; import { isAbsolute, join, resolve } from "node:path"; @@ -172,7 +173,7 @@ const TURN_EGRESS_INACTIVE = "This host has no managed native storage, so govern /** Whether the brain CLI's paid providers are relayed (#1673): where provider keys live on this host. */ const PROVIDERS_RELAYED = "The brain CLI's Gemini, Anthropic and OpenAI image providers go through a metered host relay, in turn and maintenance workers alike: the host holds their keys, records each request's usage and counts it toward the budgets."; const PROVIDERS_NOT_RELAYED = "The brain CLI's providers are not relayed here: governed and strict turn workers report them unavailable, and maintenance workers still receive the provider keys, so their spend is unmetered."; -const within = (dir: string, path: string) => path === dir || path.startsWith(`${dir}/`); +export const within = (dir: string, path: string) => isWithin(dir, path); const real = (path: string) => { try { return realpathSync(path); } catch { return resolve(path); } }; /** Whether `governed` can run for this server and brain, and if not, why. */ diff --git a/packages/ui-server/src/brain/operational-state.ts b/packages/ui-server/src/brain/operational-state.ts index 67a2daca6e..6ca73fc2a8 100644 --- a/packages/ui-server/src/brain/operational-state.ts +++ b/packages/ui-server/src/brain/operational-state.ts @@ -2,6 +2,7 @@ import { closeSync, constants, fstatSync, lstatSync, openSync, readdirSync, readlinkSync } from "node:fs"; import { tmpdir } from "node:os"; import { dirname, isAbsolute, join, resolve } from "node:path"; +import { isWithin } from "@schlessera/brain-common/internal/safe-path"; import { mountPointsUnder, workerIdentityHelper } from "@schlessera/brain-ui-sdk/internal"; import type { GovernedUnavailableReason } from "@schlessera/brain-ui-sdk/protocol"; import { journalDatabasePath } from "../db/journal-database.js"; @@ -29,7 +30,12 @@ function canonical(path: string, links = 0): string { } return current; } -const within = (root: string, path: string) => root === "/" || path === root || path.startsWith(`${root}/`); +/** + * A deny check: a brain at `/` holds every path, so all state counts as + * inside it. Every other root ends at `/` with nothing appended to a + * trailing one, as `canonical` never yields one. + */ +export const within = (root: string, path: string) => root === "/" || isWithin(root, path); /** An outside name does not move an inode out of the brain if another name or a bind mount remains there. */ function hasBrainAlias(brain: string, path: string, descendants = false): boolean { diff --git a/packages/ui-server/src/brain/scratch-mask-query.ts b/packages/ui-server/src/brain/scratch-mask-query.ts index 242563ae9a..1fa9d6c268 100644 --- a/packages/ui-server/src/brain/scratch-mask-query.ts +++ b/packages/ui-server/src/brain/scratch-mask-query.ts @@ -1,6 +1,7 @@ /** One read-only Git query; no stage publication or repository execution on the host. */ import { existsSync, lstatSync, realpathSync } from "node:fs"; import { dirname, join } from "node:path"; +import { BRAIN_SCRATCH_DIR } from "@schlessera/brain-common/internal/worker-areas"; import { prepareNativeWorkerStartupView, runMaintenanceWorker, type MaintenanceHost } from "@schlessera/brain-ui-sdk/internal"; import type { KeyedLock } from "@schlessera/brain-ui-sdk/server"; @@ -27,7 +28,7 @@ export function createScratchIgnoreQuery(input: { if (dir === "/") break; } const safe = ["-c", `safe.directory=${brain}`, ...(parent ? ["-c", `safe.directory=${parent}`] : [])]; - const args = [...safe, "check-ignore", "-q", "--no-index", "--", ".brain/scratch"]; + const args = [...safe, "check-ignore", "-q", "--no-index", "--", BRAIN_SCRATCH_DIR]; const command = existsSync(join(brain, ".git")) || parent ? [git, ...args] : ["/bin/sh", "-c", 'r=/tmp/brain-mask-empty-repository; "$0" init -q --bare "$r" >/dev/null 2>&1 && exec "$0" --git-dir="$r" --work-tree=. "$@"', git, ...args]; const view = await prepareNativeWorkerStartupView(brain, input.nativeManager, signal); diff --git a/packages/ui-server/src/brain/sync-mirror.ts b/packages/ui-server/src/brain/sync-mirror.ts index 9b0eb74464..9cdab8545c 100644 --- a/packages/ui-server/src/brain/sync-mirror.ts +++ b/packages/ui-server/src/brain/sync-mirror.ts @@ -8,6 +8,7 @@ import { createHash } from "node:crypto"; import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, realpathSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { dirname, join, resolve } from "node:path"; +import { isWithin } from "@schlessera/brain-common/internal/safe-path"; import { runMaintenanceWorker, prepareNativeWorkerStartupView, type MaintenanceCommand } from "@schlessera/brain-ui-sdk/internal"; import { createKeyedLock } from "@schlessera/brain-ui-sdk/server"; import { prepareMaintenanceOutput } from "./maintenance-output.js"; @@ -26,7 +27,7 @@ const MIRROR_CONFIG = `[core] \tfsckObjects = true `; const CREDENTIAL_HELPER = '!f() { printf "username=x-access-token\\npassword=%s\\n" "$BRAIN_SYNC_TOKEN"; }; f'; -const within = (root: string, path: string) => path === root || path.startsWith(`${root}/`); +export const within = (root: string, path: string) => isWithin(root, path); const mirrorLocks = createKeyedLock(); /** One host-private mirror per brain/database; standalone clients get private temporary state. */ diff --git a/packages/ui-server/src/core-queries.ts b/packages/ui-server/src/core-queries.ts index 50e098a3bf..edd2c4cff1 100644 --- a/packages/ui-server/src/core-queries.ts +++ b/packages/ui-server/src/core-queries.ts @@ -20,8 +20,9 @@ * fallback. Native connections stay inside core, opened and closed per call. */ import type { Logger } from "@opentelemetry/api-logs"; +import { isWithin } from "@schlessera/brain-common/internal/safe-path"; import { createRequire } from "module"; -import { dirname, relative, isAbsolute } from "path"; +import { dirname, sep } from "path"; import type { GraphMaintenanceResponse, GraphMetaResponse, @@ -136,9 +137,9 @@ type Resolved = | { ok: true; entry: Record } | { ok: false; reason: CoreQueriesUnavailableReason; version?: string }; -function inside(dir: string, file: string): boolean { - const rel = relative(dir, file); - return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel); +/** Strictly below `dir`, both resolved first: the package directory itself is not its entry. */ +export function inside(dir: string, file: string): boolean { + return isWithin(dir, file, { includeRoot: false, resolvePaths: true, separator: sep, trailingSeparator: "boundary" }); } function resolveEntry(loader: CoreModuleLoader): Resolved { diff --git a/packages/ui-server/src/files/walker.ts b/packages/ui-server/src/files/walker.ts index fc14387b41..3363b7252c 100644 --- a/packages/ui-server/src/files/walker.ts +++ b/packages/ui-server/src/files/walker.ts @@ -1,7 +1,9 @@ import { closeSync, constants, fstatSync, openSync, readSync, realpathSync } from "node:fs"; -import { lstat, readdir, readFile, stat, realpath } from "node:fs/promises"; +import { readdir, readFile, stat, realpath } from "node:fs/promises"; import { join, relative, resolve, sep, posix, dirname } from "node:path"; import ignore, { type Ignore } from "ignore"; +import { isWithin, resolveContained, type ContainmentPolicy } from "@schlessera/brain-common/internal/safe-path"; +import { BRAIN_SCRATCH_DIR, BRAIN_WORKSPACES_DIR } from "@schlessera/brain-common/internal/worker-areas"; import type { FileEntry, FileContentKind } from "@schlessera/brain-ui-sdk/protocol"; import { FILE_SIZE_CAP_BYTES } from "@schlessera/brain-ui-sdk/protocol"; @@ -25,15 +27,6 @@ const HARD_EXCLUDE_FILE_NAMES = new Set( ].map((n) => n.toLowerCase()) ); -const UNRESOLVABLE_PATH_CODES = new Set([ - "ENOENT", - "ENOTDIR", - "ENAMETOOLONG", - "ELOOP", - "EACCES", - "EPERM", -]); - export class PathEscapeError extends Error { constructor(rel: string) { super(`path_escape: ${rel}`); @@ -55,93 +48,59 @@ export class TooLargeError extends Error { } } +const [BRAIN_AREA, SCRATCH_NAME] = BRAIN_SCRATCH_DIR.split("/"); + /** - * Whether a normalized repo-relative path names `.brain`, the scratch area - * (core's `SCRATCH_DIR`, `.brain/scratch`) or something in it. ui-server does - * not depend on core (tests/allowed-edges.ts). + * Whether a normalized repo-relative path names `.brain` itself, the scratch + * area (`BRAIN_SCRATCH_DIR`, `.brain/scratch`) or something in it. Wider than + * the scratch area on purpose: `.brain` is included, so `safeResolve` follows + * no link anywhere on a path into scratch and the walker lists no link there. */ export function isScratchPath(rel: string): boolean { const parts = rel.split("/").filter((part) => part && part !== "."); - return parts[0] === ".brain" && (parts.length === 1 || parts[1] === "scratch"); + return parts[0] === BRAIN_AREA && (parts.length === 1 || parts[1] === SCRATCH_NAME); } +/** + * ui-server's row of the shared resolver (`@schlessera/brain-common/internal/safe-path`, + * #2506): every existing component, not only the final path, stays inside; + * a dangling link is refused wherever it points; and a root that does not + * exist yet contains the lexical path (the server resolves into a brain it + * may create). + */ +const SERVER_CONTAINMENT = { missingRoot: "lexical", danglingLinks: "refuse", components: "every" } as const satisfies ContainmentPolicy; + /** * Resolve a repo-relative path to an absolute path, rejecting any escape * outside the brain root (including via symlinks). + * + * The request is refused before resolving when it is absolute, holds a NUL, + * `:` or `\\` in a segment, or a `..` segment anywhere, even one whose result + * would stay inside. The answer is the lexical path under the root's + * realpath, links as written, not the canonical one. A refusal throws + * `PathEscapeError`; any other filesystem failure throws as it is. */ export async function safeResolve(rel: string, root: string): Promise { if (typeof rel !== "string") throw new PathEscapeError(String(rel)); const requestSegments = rel.split("/"); - // Reject absolute paths, null bytes, and Windows path syntax before resolving. if ( rel.startsWith("/") || rel.startsWith("\\") || rel.includes("\0") || - requestSegments.some((segment) => segment.includes(":") || segment.includes("\\")) + requestSegments.some((segment) => segment === ".." || segment.includes(":") || segment.includes("\\")) ) { throw new PathEscapeError(rel); } - // Normalize separators; reject ".." segments anywhere - const normalized = rel.replace(/\\/g, "/"); - for (const seg of normalized.split("/")) { - if (seg === "..") throw new PathEscapeError(rel); - } - const lexicalRoot = resolve(root); - let absRoot: string; - try { - absRoot = await realpath(lexicalRoot); - } catch (err) { - if ((err as NodeJS.ErrnoException).code !== "ENOENT") throw err; - absRoot = lexicalRoot; - } - const abs = resolve(absRoot, normalized); - if (abs !== absRoot && !abs.startsWith(absRoot + sep)) { - throw new PathEscapeError(rel); - } - // Canonicalize every existing component. Stopping at the first genuinely - // missing component permits callers to create a new path, while lstat - // distinguishes that case from a dangling symlink, which must fail closed. - let candidate = absRoot; - const candidates = [candidate]; - for (const segment of relative(absRoot, abs).split(sep)) { - if (!segment || segment === ".") continue; - candidate = join(candidate, segment); - candidates.push(candidate); - } - // The scratch area is agent-writable in a hosted worker (#1626), so nothing // under `.brain/` is followed through a link: a scratch symlink cannot make // the server serve, preview or list another file under a scratch path. - const scratchRequest = isScratchPath(normalized); - for (const existing of candidates) { - let entry; - try { - entry = await lstat(existing); - } catch (err) { - const code = (err as NodeJS.ErrnoException).code; - if (code && UNRESOLVABLE_PATH_CODES.has(code)) break; - throw err; - } - if (scratchRequest && entry.isSymbolicLink() && existing.startsWith(join(absRoot, ".brain"))) { - throw new PathEscapeError(rel); - } - - let real: string; - try { - real = await realpath(existing); - } catch (err) { - const code = (err as NodeJS.ErrnoException).code; - if (code === "ENOENT" || code === "ENOTDIR") { - throw new PathEscapeError(rel); - } - if (code && UNRESOLVABLE_PATH_CODES.has(code)) break; - throw err; - } - if (real !== absRoot && !real.startsWith(absRoot + sep)) { - throw new PathEscapeError(rel); - } - } - return abs; + const policy: ContainmentPolicy = isScratchPath(rel) + ? { ...SERVER_CONTAINMENT, refuseLinkAt: (path, absRoot) => isWithin(join(absRoot, BRAIN_AREA!), path, { separator: sep }) } + : SERVER_CONTAINMENT; + const result = await resolveContained(root, rel, policy); + if (result.ok) return result.lexical; + if (result.reason === "error") throw result.error; + throw new PathEscapeError(rel); } /** @@ -197,7 +156,7 @@ async function canonicalRoot(root: string): Promise { } /** Directories a hosted agent can write (#1626): `.brain/scratch` and `workspaces`. */ -const AGENT_WRITABLE = [".brain/scratch", "workspaces"]; +const AGENT_WRITABLE = [BRAIN_SCRATCH_DIR, BRAIN_WORKSPACES_DIR]; /** * When the requested path or the file it resolves to lies in an @@ -210,14 +169,11 @@ const AGENT_WRITABLE = [".brain/scratch", "workspaces"]; async function areaSnapshot(rel: string, abs: string, root: string) { if (process.platform !== "linux") return null; const absRoot = await canonicalRoot(root); - const inArea = (path: string) => AGENT_WRITABLE.some((area) => { - const dir = join(absRoot, area); - return path === dir || path.startsWith(dir + sep); - }); + const inArea = (path: string) => AGENT_WRITABLE.some((area) => isWithin(join(absRoot, area), path, { separator: sep })); let real: string; try { real = await realpath(abs); } catch { throw new NotFoundError(rel); } if (!inArea(abs) && !inArea(real) && !isScratchPath(rel)) return null; - if (real !== absRoot && !real.startsWith(absRoot + sep)) throw new PathEscapeError(rel); + if (!isWithin(absRoot, real, { separator: sep })) throw new PathEscapeError(rel); return { real, ...readAnchoredSnapshot(real, absRoot, rel)! }; } diff --git a/packages/ui-server/src/storage/collect.ts b/packages/ui-server/src/storage/collect.ts index f08961bd3d..8ed8b11286 100644 --- a/packages/ui-server/src/storage/collect.ts +++ b/packages/ui-server/src/storage/collect.ts @@ -1,6 +1,7 @@ import { createHmac } from "node:crypto"; import { basename, dirname, resolve } from "node:path"; import { INDEX_DIR } from "@schlessera/brain-common/internal/index-location"; +import { BRAIN_SCRATCH_DIR, BRAIN_WORKSPACES_DIR } from "@schlessera/brain-common/internal/worker-areas"; import { z } from "zod"; import type { StorageFileEntry, StorageRoot, StorageSnapshot, StorageOwner, StorageBytes } from "@schlessera/brain-ui-sdk/protocol"; import { SHARE_STAGING_DIR } from "@schlessera/brain-ui-sdk/protocol"; @@ -76,7 +77,7 @@ export async function collectStorage(options: StorageCollectOptions, id: string, } if (view.id === brain.id) { for (const [prefix, label, category, owner] of [ - [".git", "Git metadata", "git", "brain"], [SHARE_STAGING_DIR, "Upload staging", "staging", "app"], [".brain/scratch", "Scratch", "scratch", "brain"], ["workspaces", "Workspaces", "workspace", "brain"], + [".git", "Git metadata", "git", "brain"], [SHARE_STAGING_DIR, "Upload staging", "staging", "app"], [BRAIN_SCRATCH_DIR, "Scratch", "scratch", "brain"], [BRAIN_WORKSPACES_DIR, "Workspaces", "workspace", "brain"], ] as const) if (path === prefix || path.startsWith(`${prefix}/`)) { view = root(prefix, label, category, owner); sources.set(view.id, { root: view, path: resolve(options.brainPath, prefix), recursive: false, optional: true }); path = path.slice(prefix.length).replace(/^\//, ""); break; } if (view.id === brain.id && (path === INDEX_DIR || path.startsWith(`${INDEX_DIR}/`))) { view = root("index", "Content index", "index", "brain"); diff --git a/packages/ui-server/src/storage/process.ts b/packages/ui-server/src/storage/process.ts index 9f66cde46e..4dd0dde539 100644 --- a/packages/ui-server/src/storage/process.ts +++ b/packages/ui-server/src/storage/process.ts @@ -1,9 +1,11 @@ import { processStart } from "../brain/writer-gate.js"; +import { isWithin } from "@schlessera/brain-common/internal/safe-path"; import { fileURLToPath } from "node:url"; -import { dirname, relative, isAbsolute } from "node:path"; +import { dirname, sep } from "node:path"; import { realpathSync, readFileSync } from "node:fs"; import type { MetadataRoot, MetadataResult } from "./metadata.js"; -const inside = (root: string, path: string) => { const rel = relative(root, path); return !rel || (!isAbsolute(rel) && rel !== ".." && !rel.startsWith("../")); }; +/** `root` or below it, both resolved first. */ +export const inside = (root: string, path: string) => isWithin(root, path, { resolvePaths: true, separator: sep, trailingSeparator: "boundary" }); /** Verify the installed public reader, never code or executables from content. */ export function coreReader(brainPath: string, subpath: "storage" | "queries"): string { const manifestPath = realpathSync(fileURLToPath(import.meta.resolve("@schlessera/brain/package.json"))); diff --git a/packages/ui-server/tests/containment-rows.test.ts b/packages/ui-server/tests/containment-rows.test.ts new file mode 100644 index 0000000000..6381f63cf5 --- /dev/null +++ b/packages/ui-server/tests/containment-rows.test.ts @@ -0,0 +1,171 @@ +/** + * ui-server's rows of the containment matrices (#2506). `safeResolve(rel, + * root)` is asynchronous and throws `PathEscapeError`; it refuses absolute + * paths, `..` anywhere, `:` or `\\` in a segment and dangling links; every + * existing component must stay inside, not only the final path; a missing + * root falls back to the lexical root; it answers the lexical path, not the + * canonical one; and under `.brain` a scratch request follows no link. The + * predicates each keep their own argument order, equality, root `/` and + * normalisation answers. Written against the copies ui-server carried before + * the shared `@schlessera/brain-common/internal/safe-path`. + */ +import { afterAll, describe, expect, test } from "bun:test"; +import { mkdirSync, mkdtempSync, realpathSync, renameSync, rmSync, symlinkSync, writeFileSync } from "fs"; +import { tmpdir } from "os"; +import { join, relative } from "path"; + +import { inside as coreQueriesInside } from "../src/core-queries"; +import { within as hostBoundaryWithin } from "../src/brain/host-boundary"; +import { within as operationalStateWithin } from "../src/brain/operational-state"; +import { within as syncMirrorWithin } from "../src/brain/sync-mirror"; +import { isScratchPath, safeResolve } from "../src/files/walker"; +import { inside as processInside } from "../src/storage/process"; + +const base = realpathSync(mkdtempSync(join(tmpdir(), "brain-kit-containment-rows-"))); +afterAll(() => rmSync(base, { recursive: true, force: true })); +const root = join(base, "brain"); +const outside = join(base, "brain-other"); + +mkdirSync(join(root, "notes/sub"), { recursive: true }); +mkdirSync(outside); +mkdirSync(join(root, ".brain/scratch"), { recursive: true }); +writeFileSync(join(root, "notes/a.md"), "a"); +writeFileSync(join(root, "file.md"), "f"); +writeFileSync(join(outside, "secret.md"), "s"); +writeFileSync(join(root, ".brain/scratch/s.txt"), "s"); +symlinkSync("notes", join(root, "link-in")); +symlinkSync(outside, join(root, "link-out")); +symlinkSync("notes/missing", join(root, "dangling-in")); +symlinkSync(join(outside, "missing"), join(root, "dangling-out")); +symlinkSync("cycle-b", join(root, "cycle-a")); +symlinkSync("cycle-a", join(root, "cycle-b")); +symlinkSync(outside, join(root, "bounce")); +symlinkSync(join(root, "notes"), join(outside, "back")); +symlinkSync("../../notes", join(root, ".brain/scratch/link")); +symlinkSync(root, join(base, "root-link")); + +/** The answer relative to the fixture base, `refused` for a path escape, or the error's code. */ +async function answer(rel: string, at = root): Promise { + try { + return relative(base, await safeResolve(rel, at)) || "."; + } catch (error) { + if ((error as Error).name === "PathEscapeError") return "refused"; + return `error ${(error as NodeJS.ErrnoException).code}`; + } +} + +describe("ui-server safeResolve(rel, root): its resolver row", () => { + const rows: [string, string][] = [ + ["notes/a.md", "brain/notes/a.md"], + ["notes/new.md", "brain/notes/new.md"], + ["a/b/c.md", "brain/a/b/c.md"], + ["", "brain"], + [".", "brain"], + ["./notes/a.md", "brain/notes/a.md"], + ["notes//a.md", "brain/notes/a.md"], + ["notes/a.md/", "brain/notes/a.md"], + ["file.md/x", "brain/file.md/x"], + // `..` is refused anywhere, even when the result stays inside. + ["notes/../notes/a.md", "refused"], + ["notes/../../x", "refused"], + ["../brain-other/secret.md", "refused"], + // Absolute is refused, even inside the root. + [join(root, "notes/a.md"), "refused"], + ["/etc/passwd", "refused"], + ["\\etc", "refused"], + // Windows syntax and NUL are refused. + ["a:b", "refused"], + ["a\\b", "refused"], + ["a\0b", "refused"], + // The answer is the lexical path; links stay as written. + ["link-in/a.md", "brain/link-in/a.md"], + ["link-in/new.md", "brain/link-in/new.md"], + ["link-out/secret.md", "refused"], + ["link-out/new.md", "refused"], + // A dangling link is refused even when its target would be inside. + ["dangling-in", "refused"], + ["dangling-in/x", "refused"], + ["dangling-out", "refused"], + // A symlink cycle is refused (#2506). The copy ui-server carried accepted + // it, answering a path that resolves nowhere; core and the SDK refused it, + // and the shared resolver keeps that stricter answer. + ["cycle-a", "refused"], + ["cycle-a/x", "refused"], + // Every existing component must stay inside: out and back is refused. + ["bounce/back/a.md", "refused"], + // `.brain` is a scratch request (`isScratchPath`): no link under it is followed. + [".brain", "brain/.brain"], + [".brain/scratch/s.txt", "brain/.brain/scratch/s.txt"], + [".brain/scratch/link", "refused"], + [".brain/scratch/link/a.md", "refused"], + ]; + for (const [rel, expected] of rows) { + test(`${JSON.stringify(rel.startsWith(base) ? "/" + relative(base, rel) : rel)} -> ${expected}`, async () => { + expect(await answer(rel)).toBe(expected); + }); + } + + test("a root that is itself a symlink resolves against its target", async () => { + expect(await answer("notes/a.md", join(base, "root-link"))).toBe("brain/notes/a.md"); + }); + + test("a missing root falls back to the lexical root; a dangling or unreadable one does not", async () => { + expect(await answer("notes/a.md", join(base, "nope"))).toBe("nope/notes/a.md"); + expect(await answer("x", join(root, "dangling-in"))).toBe("refused"); + expect(await answer("x", join(root, "file.md/x"))).toBe("error ENOTDIR"); + }); + + test("each call reads the filesystem again: a directory swapped for an escaping link is refused", async () => { + const swap = join(root, "swap"); + mkdirSync(swap); + expect(await answer("swap/new.md")).toBe("brain/swap/new.md"); + renameSync(swap, join(base, "swapped-away")); + symlinkSync(outside, swap); + expect(await answer("swap/new.md")).toBe("refused"); + rmSync(swap); + renameSync(join(base, "swapped-away"), swap); + expect(await answer("swap/new.md")).toBe("brain/swap/new.md"); + }); + + test("isScratchPath covers .brain itself as well as the scratch area", () => { + expect(isScratchPath(".brain")).toBe(true); + expect(isScratchPath(".brain/")).toBe(true); + expect(isScratchPath("./.brain/scratch")).toBe(true); + expect(isScratchPath(".brain/scratch/x/y")).toBe(true); + expect(isScratchPath(".brain/other")).toBe(false); + expect(isScratchPath(".brain/scratchy")).toBe(false); + expect(isScratchPath(".brainy/scratch")).toBe(false); + expect(isScratchPath("notes/.brain/scratch")).toBe(false); + }); +}); + +/** As in the ui-sdk test: `(root, path)` cases and their `T`/`-` answers. */ +const PREDICATE_CASES: [string, string][] = [ + ["/a/b", "/a/b"], ["/a/b", "/a/b/c"], ["/a/b", "/a/bc"], ["/a/b", "/a"], + ["/", "/x"], ["/", "/"], ["/", "x"], + ["/a/b/", "/a/b/c"], ["/a/b/", "/a/b"], + ["/a/b", "/a/b/"], ["/a/b", "/a/b/../c"], ["/a/b", "/a/b/..c"], ["/a/b", "/a/b//c"], +]; +// = c sp pa /x / rel tr trE p/ .. ..c // +const LITERAL_SLASH = "T T - - - T - - - T T T T"; + +const rows: [string, (root: string, path: string) => boolean, string][] = [ + // relative()-based: both sides resolved; the root itself is excluded. A + // child named `..c` is inside (#2506): the copy refused it, reading any + // relative path that starts with `..` as an escape. + ["core-queries inside(dir, file)", coreQueriesInside, "- T - - T - T T - - - T T"], + // relative()-based: both sides resolved; the root itself is included. + ["storage/process inside(root, path)", processInside, "T T - - T T T T T T - T T"], + // Literal, except that root `/` holds everything. + ["operational-state within(root, path)", operationalStateWithin, "T T - - T T T - - T T T T"], + ["sync-mirror within(root, path)", syncMirrorWithin, LITERAL_SLASH], + ["host-boundary within(dir, path)", hostBoundaryWithin, LITERAL_SLASH], +]; + +describe("ui-server containment predicates: their matrix rows", () => { + for (const [name, predicate, expected] of rows) { + test(name, () => { + expect(PREDICATE_CASES.map(([root, path]) => (predicate(root, path) ? "T" : "-")).join(" ")).toBe(expected); + }); + } +}); diff --git a/packages/ui-server/tests/files-walker.test.ts b/packages/ui-server/tests/files-walker.test.ts index 6e2d15ed21..7a603ff693 100644 --- a/packages/ui-server/tests/files-walker.test.ts +++ b/packages/ui-server/tests/files-walker.test.ts @@ -1,6 +1,6 @@ import { describe, test, expect, beforeAll, afterAll, spyOn } from "bun:test"; import * as fsp from "node:fs/promises"; -import { mkdir, writeFile, symlink, rm } from "node:fs/promises"; +import { mkdir, writeFile, symlink, rm, realpath } from "node:fs/promises"; import { join, win32 } from "node:path"; import { tmpdir } from "node:os"; import { @@ -102,6 +102,17 @@ describe("safeResolve", () => { test("rejects symlink escape", async () => { await expect(safeResolve("escape-link", root)).rejects.toBeInstanceOf(PathEscapeError); }); + test("rejects a link into a sibling directory that shares the root's name as a prefix", async () => { + const sibling = `${await realpath(root)}-other`; + await mkdir(sibling, { recursive: true }); + try { + await symlink(sibling, join(root, "sibling-link")); + await expect(safeResolve("sibling-link/x.md", root)).rejects.toBeInstanceOf(PathEscapeError); + } finally { + await rm(join(root, "sibling-link"), { force: true }); + await rm(sibling, { recursive: true, force: true }); + } + }); test("accepts repo-relative path", async () => { await expect(safeResolve("notes/foo.md", root)).resolves.toBeTruthy(); }); diff --git a/tests/allowed-edges.ts b/tests/allowed-edges.ts index 5b0213d4ed..5d8789d823 100644 --- a/tests/allowed-edges.ts +++ b/tests/allowed-edges.ts @@ -26,8 +26,9 @@ export const ALLOWED_EDGES: Record = { // byte-identical copies each package carried, plus the worker write-area // rules core and the ui-sdk both state (#1693). It depends on no internal // package. #1744 also shares data-only governance parsing between core - // and server, preserving the server’s optional core peer. Further helpers - // still need their own issue. + // and server, preserving the server’s optional core peer. #2493 adds the + // Claude subscription billing guard and #2506 symlink-safe path + // containment, each with its own issue. Further helpers still need theirs. "@schlessera/brain-common": { dependencies: [], optionalPeers: [] }, // core owns the render template (the CLI's `brain render` uses it); the // Puppeteer renderer is heavyweight and optional, so it may never be hard. From c2b42d7886bc4634844ba6fe053dd3377a3d7248 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 3 Nov 2026 13:18:09 +0100 Subject: [PATCH 2/4] refactor(common): read the governance policy through one descriptor-anchored reader (#2508) (#3418) * refactor(common): read the governance policy through one descriptor-anchored reader (#2508) checkGovernancePolicy and ui-server's policy writer each walked context/policies/governance.md through held directory descriptors, with different hardening. Both now use openGovernancePolicyAnchored and verifyGovernancePolicyAnchored from @schlessera/brain-common/internal/governance-policy, which keep the stricter rule of each copy: the bounded read and short-read check from common, the per-directory dev/ino ancestry check from the writer (now on Linux too), and a removed ancestor reported as a change rather than a missing policy. The writer maps the shared refusals onto its unchanged review states and messages. Co-Authored-By: Claude Opus 5.5 * docs(common): record the shared governance policy reader and move its citation (#2508) Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- .changeset/governance-policy-read-once.md | 7 + api-report/common.txt | 6 + docs/decisions/governed-writable-workers.md | 2 +- packages/common/README.md | 2 +- packages/common/src/governance-policy.ts | 169 +++++++++++++--- .../tests/governance-policy-read.test.ts | 173 +++++++++++++++++ .../ui-server/src/brain/policy-proposal.ts | 72 ++----- .../tests/policy-proposal-read.test.ts | 181 ++++++++++++++++++ 8 files changed, 527 insertions(+), 85 deletions(-) create mode 100644 .changeset/governance-policy-read-once.md create mode 100644 packages/common/tests/governance-policy-read.test.ts create mode 100644 packages/ui-server/tests/policy-proposal-read.test.ts diff --git a/.changeset/governance-policy-read-once.md b/.changeset/governance-policy-read-once.md new file mode 100644 index 0000000000..2e481599ab --- /dev/null +++ b/.changeset/governance-policy-read-once.md @@ -0,0 +1,7 @@ +--- +"@schlessera/brain-common": patch +"@schlessera/brain-ui-server": patch +"@schlessera/brain": patch +--- + +The governance policy file is read through one descriptor-anchored reader (#2508). `brain policy`, the indexer, `brain stats`, the hosted server's policy reader and its policy writer now share `openGovernancePolicyAnchored` and `verifyGovernancePolicyAnchored` in `@schlessera/brain-common/internal/governance-policy`, so a hardening fix reaches all of them. Each keeps the stricter rule of the two former copies. The writer no longer loads a file that grows past the 1 MiB bound after its size check, and it refuses a short read as a change. `checkGovernancePolicy` now refuses an ancestor directory replaced during the read on Linux as well, and reports an ancestor removed during the read as invalid rather than missing. The writer's review states and messages are unchanged. diff --git a/api-report/common.txt b/api-report/common.txt index 155e0b5d5a..9bb9440cc0 100644 --- a/api-report/common.txt +++ b/api-report/common.txt @@ -35,18 +35,24 @@ export "./internal/frontmatter" (./src/frontmatter-parse.ts) parseFrontmatter export "./internal/governance-policy" (./src/governance-policy.ts) + type AnchoredGovernancePolicy BUILTIN_GOVERNANCE_POLICY type EffectiveGovernancePolicy GOVERNANCE_POLICY_MAX_BYTES GOVERNANCE_POLICY_PATH type GovernanceCommandRuleIndices type GovernancePolicyCheck + type GovernancePolicyDirectory type GovernancePolicyInput + GovernancePolicyReadError + type GovernancePolicyReadRefusal GovernancePolicySchema checkGovernancePolicy + openGovernancePolicyAnchored parseGovernancePolicy providerAllows resolveGovernancePolicy + verifyGovernancePolicyAnchored export "./internal/index-location" (./src/index-location.ts) EMBEDDING_LOCK_FAMILY diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index d4362c808a..23e8f86629 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -1151,7 +1151,7 @@ principal authority remain the caller's responsibility. The policy publisher creates, writes, fsyncs and removes its operation-owned staging name entirely inside that synchronous callback, between the two serialized observations (`await options.observeUserPolicy`, -`packages/ui-server/src/brain/policy-proposal.ts:217-244`). First publication +`packages/ui-server/src/brain/policy-proposal.ts:185-212`). First publication also removes the temporary hardlink before the final observation. No filename prefix is ignored; a similarly named real agent change is still retained. Failed staging preserves the original policy, while failed recording after diff --git a/packages/common/README.md b/packages/common/README.md index c004c6cba3..ad1ec100f9 100644 --- a/packages/common/README.md +++ b/packages/common/README.md @@ -13,7 +13,7 @@ one; it arrives as their dependency. | `@schlessera/brain-common/internal/frontmatter` | `parseFrontmatter`, the only door to gray-matter's parser. It always passes an options object, so gray-matter's process-wide cache is never read or written ([decision](../../docs/decisions/frontmatter-parsing.md)). | | `@schlessera/brain-common/internal/worker-areas` | The hosted worker's write-area names and the rules stated about them: turn temp is never linked, the link rule, and the read-only-brain rule. The ui-sdk's sandbox note and core's `brain` CLI refusal both render them, so the refusal repeats the note word for word (#1654, admitted by #1693). | | `@schlessera/brain-common/internal/protected-paths` | The protected worker path tiers shared by core policy validation and the sandbox. | -| `@schlessera/brain-common/internal/governance-policy` | Data-only policy schema, defaults, parsing and anchored reads shared by the core CLI and hosted server (#1744). The server can read policy without installing its optional core peer. | +| `@schlessera/brain-common/internal/governance-policy` | Data-only policy schema, defaults, parsing and anchored reads shared by the core CLI and hosted server (#1744). The server can read policy without installing its optional core peer. Its policy writer reads and re-checks the file through the same descriptor-anchored reader (#2508). | | `@schlessera/brain-common/internal/index-location` | Where the disposable search index lives: the `.brain-index/` directory holding `brain.db` and its SQLite sidecars, and the legacy root-level names a brain migrates away from by rebuilding (#1668). | | `@schlessera/brain-common/internal/claude-subscription` | The subscription billing guard both Claude runners apply: the cleared credential variables, the neutralised flag settings, the settings refusal and the account verdict. core's CLI runner and the chat backend import it, so a newly found credential or routing variable is added once (#2493). | | `@schlessera/brain-common/internal/safe-path` | Symlink-safe path containment: `isWithin`, the containment primitive whose equality, separator, trailing-separator and normalisation answers are explicit parameters, and `resolveContained`/`resolveContainedSync`, one canonicalisation algorithm that resolves a request under the root's realpath through its nearest existing ancestor. core's `safeResolve`, the SDK's `resolveInRepo` and the server's `safeResolve` are thin wrappers that each keep their own request refusals and policy, so a hardening fix lands once (#2506). | diff --git a/packages/common/src/governance-policy.ts b/packages/common/src/governance-policy.ts index 8483545724..3527ab82c5 100644 --- a/packages/common/src/governance-policy.ts +++ b/packages/common/src/governance-policy.ts @@ -1,6 +1,6 @@ /** Read-only, data-only governance policy input. Enforcement belongs to its owning siblings. */ import { createHash } from "node:crypto"; -import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, realpathSync } from "node:fs"; +import { closeSync, constants, fstatSync, lstatSync, mkdirSync, openSync, readSync, realpathSync } from "node:fs"; import { join } from "node:path"; import { z } from "zod"; import { parseFrontmatter } from "./frontmatter-parse.js"; @@ -122,43 +122,150 @@ export function parseGovernancePolicy(bytes: Uint8Array): GovernancePolicyCheck } } -/** Descriptor-anchored, no links or FIFO reads; never loads brain configuration or executes code. */ -export function checkGovernancePolicy(brainPath: string): GovernancePolicyCheck { - const fds: number[] = []; - const directories: Array<{ path: string; fd: number }> = []; +/** + * Why the anchored reader refused the policy. Each has one message here; + * the policy writer maps them onto its own review states and wording. + * - `not_regular`: not an ordinary file, or a file with hardlink aliases. + * - `oversize`: the file reports more than {@link GOVERNANCE_POLICY_MAX_BYTES}. + * - `changed`: size, timestamps or the bytes read disagree within one read. + * - `ancestry`: a held directory no longer has its name, or is not a directory. + * - `mismatch`: a re-check read bytes other than the expected hash. + */ +export type GovernancePolicyReadRefusal = "not_regular" | "oversize" | "changed" | "ancestry" | "mismatch"; +const READ_REFUSALS: Record = { + not_regular: "Policy must be a regular file without hardlink aliases", + oversize: "Policy exceeds the 1 MiB input bound", + changed: "Policy changed while it was read; retry the check or repair the edit", + ancestry: "Policy ancestry changed while it was read", + mismatch: "Policy changed since it was read", +}; +export class GovernancePolicyReadError extends Error { + constructor(readonly refusal: GovernancePolicyReadRefusal) { super(READ_REFUSALS[refusal]); this.name = "GovernancePolicyReadError"; } +} + +/** One held directory of the policy's ancestry: the brain root, `context`, `context/policies`. */ +export interface GovernancePolicyDirectory { readonly fd: number; readonly path: string; readonly dev: number; readonly ino: number } +/** + * The policy as read through held directory descriptors. `at` names the file + * relative to the innermost held directory (`/proc/self/fd//governance.md` + * on Linux), so a write staged beside it lands in the directory that was checked. + * `bytes` is null when the file does not exist. Close it exactly once. + */ +export interface AnchoredGovernancePolicy { + readonly directories: readonly GovernancePolicyDirectory[]; + readonly at: string; + readonly bytes: Buffer | null; + /** Permission bits of the file read; absent when there is none. */ + readonly mode?: number; + close(): void; +} + +const DIRECTORY_FLAGS = constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW; +const anchoredName = (parent: GovernancePolicyDirectory, name: string, visible: string) => + process.platform === "linux" ? `/proc/self/fd/${parent.fd}/${name}` : visible; + +/** + * Bounded read of the file at `at`, never following a link or blocking on a + * FIFO. Null when it does not exist. Allocates at most one byte past the bound, + * so a file growing after its size check is caught without loading it. + */ +function readAnchoredFile(at: string): { bytes: Buffer | null; mode?: number } { + let fd: number; + try { fd = openSync(at, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); } + catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return { bytes: null }; throw error; } try { - let path = realpathSync(brainPath); - let fd = openSync(path, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW); fds.push(fd); - directories.push({ path, fd }); - const parts = GOVERNANCE_POLICY_PATH.split("/"); - for (const part of parts.slice(0, -1)) { - path = join(path, part); - fd = openSync(process.platform === "linux" ? `/proc/self/fd/${fd}/${part}` : path, - constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW); fds.push(fd); - directories.push({ path, fd }); - } - fd = openSync(process.platform === "linux" ? `/proc/self/fd/${fd}/${parts.at(-1)!}` : join(path, parts.at(-1)!), - constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); fds.push(fd); const info = fstatSync(fd); - if (!info.isFile() || info.nlink !== 1) throw new Error("Policy must be a regular file without hardlink aliases"); - if (info.size > GOVERNANCE_POLICY_MAX_BYTES) throw new Error("Policy exceeds the 1 MiB input bound"); + if (!info.isFile() || info.nlink !== 1) throw new GovernancePolicyReadError("not_regular"); + if (info.size > GOVERNANCE_POLICY_MAX_BYTES) throw new GovernancePolicyReadError("oversize"); const bytes = Buffer.alloc(GOVERNANCE_POLICY_MAX_BYTES + 1); let length = 0; while (length < bytes.length) { const read = readSync(fd, bytes, length, bytes.length - length, null); if (!read) break; length += read; } const after = fstatSync(fd); - if (after.size !== info.size || after.mtimeMs !== info.mtimeMs || after.ctimeMs !== info.ctimeMs || length !== info.size) throw new Error("Policy changed while it was read; retry the check or repair the edit"); - // Non-Linux CLI readers cannot use /proc descriptor traversal. They open - // each component without following links and reject changed ancestry. - // Hosted workers require Linux, where every open above is descriptor-relative. - if (process.platform !== "linux") for (const directory of directories) { - const named = lstatSync(directory.path), held = fstatSync(directory.fd); - if (!named.isDirectory() || named.dev !== held.dev || named.ino !== held.ino) throw new Error("Policy ancestry changed while it was read"); + // A short or long read is a change even when the timestamps did not move. + if (length !== info.size || after.size !== info.size || after.mtimeMs !== info.mtimeMs || after.ctimeMs !== info.ctimeMs) + throw new GovernancePolicyReadError("changed"); + return { bytes: Buffer.from(bytes.subarray(0, length)), mode: info.mode & 0o7777 }; + } finally { closeSync(fd); } +} + +/** Every held directory still has its name, as a directory, with the identity it was opened with. */ +function checkAncestry(directories: readonly GovernancePolicyDirectory[]) { + for (const directory of directories) { + // A removed ancestor is a change, not a missing policy: bytes were already read. + const named = lstatSync(directory.path, { throwIfNoEntry: false }); + if (!named?.isDirectory() || named.dev !== directory.dev || named.ino !== directory.ino) throw new GovernancePolicyReadError("ancestry"); + } +} + +/** + * Opens the policy's ancestry under `root` without following links, holding + * each directory, and reads the policy through the innermost one. `root` is + * used as given (callers resolve it once) and must itself not be a link. + * On Linux every open after the root is relative to the held parent + * descriptor; elsewhere each component is opened by name and the ancestry + * check below rejects a swap. + * + * With `create`, missing ancestor directories are made (mode 0755) and their + * visible paths appended to `created`, so a caller can remove them again. + * Without it, a missing ancestor throws `ENOENT`. A missing file is + * `bytes: null`. Other refusals throw {@link GovernancePolicyReadError}; + * errors of the system calls (a link: `ELOOP`/`ENOTDIR`) propagate as they are. + * The ancestry is checked after the read, so a directory swapped while the + * bytes were read is refused. + */ +export function openGovernancePolicyAnchored(root: string, options: { create?: boolean; created?: string[] } = {}): AnchoredGovernancePolicy { + const directories: GovernancePolicyDirectory[] = []; + const release = () => { for (const directory of directories.splice(0).reverse()) closeSync(directory.fd); }; + try { + const parts = GOVERNANCE_POLICY_PATH.split("/"), name = parts.pop()!; + let visible = root, at = root; + for (let i = 0; i <= parts.length; i++) { + if (i > 0) { + visible = join(visible, parts[i - 1]!); at = anchoredName(directories.at(-1)!, parts[i - 1]!, visible); + if (options.create) { + try { mkdirSync(at, { mode: 0o755 }); options.created?.push(visible); } + catch (error) { if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; } + } + } + const fd = openSync(at, DIRECTORY_FLAGS); + try { const info = fstatSync(fd); directories.push({ fd, path: visible, dev: info.dev, ino: info.ino }); } + catch (error) { closeSync(fd); throw error; } } - return parseGovernancePolicy(bytes.subarray(0, length)); + const file = anchoredName(directories.at(-1)!, name, join(visible, name)); + const read = readAnchoredFile(file); + checkAncestry(directories); + let closed = false; + return { directories, at: file, ...read, close() { if (!closed) { closed = true; release(); } } }; + } catch (error) { release(); throw error; } +} + +/** + * Re-checks a held policy: the ancestry still has its names, and the file + * now at `handle.at` reads (with the same bounds) to `expectedHash`, the + * SHA-256 of its bytes, or is absent when `expectedHash` is null. Returns the + * bytes read; throws {@link GovernancePolicyReadError} otherwise. + */ +export function verifyGovernancePolicyAnchored(handle: AnchoredGovernancePolicy, expectedHash: string | null): Buffer | null { + checkAncestry(handle.directories); + const current = readAnchoredFile(handle.at).bytes; + if ((current === null ? null : createHash("sha256").update(current).digest("hex")) !== expectedHash) throw new GovernancePolicyReadError("mismatch"); + return current; +} + +/** Descriptor-anchored, no links or FIFO reads; never loads brain configuration or executes code. */ +export function checkGovernancePolicy(brainPath: string): GovernancePolicyCheck { + let handle: AnchoredGovernancePolicy | undefined; + try { + handle = openGovernancePolicyAnchored(realpathSync(brainPath)); + if (handle.bytes === null) return missingGovernancePolicy(); + return parseGovernancePolicy(handle.bytes); } catch (error) { - const missing = (error as NodeJS.ErrnoException).code === "ENOENT"; - return { schema_version: 1, ok: missing, status: missing ? "missing" : "invalid", content_hash: null, - errors: missing ? [] : [error instanceof Error ? error.message : String(error)], warnings: [], effective: resolveGovernancePolicy({ schema_version: 1 }) }; - } finally { for (const fd of fds.reverse()) closeSync(fd); } + if ((error as NodeJS.ErrnoException).code === "ENOENT") return missingGovernancePolicy(); + return { schema_version: 1, ok: false, status: "invalid", content_hash: null, + errors: [error instanceof Error ? error.message : String(error)], warnings: [], effective: resolveGovernancePolicy({ schema_version: 1 }) }; + } finally { handle?.close(); } +} +function missingGovernancePolicy(): GovernancePolicyCheck { + return { schema_version: 1, ok: true, status: "missing", content_hash: null, errors: [], warnings: [], effective: resolveGovernancePolicy({ schema_version: 1 }) }; } /** Matching rules intersect their allowlists; unknown recipients never authorize a match. */ diff --git a/packages/common/tests/governance-policy-read.test.ts b/packages/common/tests/governance-policy-read.test.ts new file mode 100644 index 0000000000..7700b4a365 --- /dev/null +++ b/packages/common/tests/governance-policy-read.test.ts @@ -0,0 +1,173 @@ +/** + * The descriptor-anchored governance policy read (#2508). `checkGovernancePolicy` + * and ui-server's policy writer both read the protected file through it; the + * writer's own characterization lives in + * `packages/ui-server/tests/policy-proposal-read.test.ts`. + * + * Races are staged through `node:fs` spies on the descriptor's `fstatSync`, so + * the same hooks drive every implementation without knowing how it reads. + */ +import { afterEach, expect, test } from "bun:test"; +import * as fs from "node:fs"; +import { linkSync, mkdirSync, mkdtempSync, renameSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { createHash } from "node:crypto"; +import { spyOn } from "bun:test"; +import { checkGovernancePolicy, GOVERNANCE_POLICY_MAX_BYTES, GOVERNANCE_POLICY_PATH } from "../src/governance-policy"; + +const policy = "---\nschema_version: 1\nprofiles:\n interactive: governed\n---\nPenelope keeps the policy.\n"; +const replacement = "---\nschema_version: 1\nprofiles:\n interactive: strict\n---\nThe suitors rewrote the policy.\n"; +const sha = (text: string | Uint8Array) => createHash("sha256").update(text).digest("hex"); +const cleanup: Array<() => void> = []; +afterEach(() => { for (const fn of cleanup.splice(0).reverse()) fn(); }); + +function brain(content: string | null = policy) { + const root = mkdtempSync(join(tmpdir(), "governance-read-")); + cleanup.push(() => rmSync(root, { recursive: true, force: true })); + mkdirSync(join(root, "context/policies"), { recursive: true }); + const path = join(root, GOVERNANCE_POLICY_PATH); + if (content !== null) writeFileSync(path, content); + return { root, path }; +} + +/** + * Runs `hook` once, when the reader first fstats a regular file (the policy + * descriptor before its bytes are read), and lets `size` override what every + * regular-file fstat reports. Restored in teardown. + */ +function onPolicyStat(hook?: () => void, size?: (real: number) => number) { + const original = fs.fstatSync; + let fired = false; + const spy = spyOn(fs, "fstatSync").mockImplementation(((fd: number, options?: fs.StatOptions) => { + const info = original(fd, options as never) as fs.Stats; + if (!info.isFile()) return info; + if (!fired && hook) { fired = true; hook(); } + if (size) Object.defineProperty(info, "size", { value: size(info.size) }); + return info; + }) as typeof fs.fstatSync); + cleanup.push(() => spy.mockRestore()); + return () => fired; +} + +/** Largest single result either read API handed back for a descriptor. */ +function readHighWater() { + const readSync = fs.readSync, readFileSync = fs.readFileSync; + let most = 0; + const a = spyOn(fs, "readSync").mockImplementation(((...args: Parameters) => { + const n = (readSync as (...x: unknown[]) => number)(...args); most = Math.max(most, n); return n; + }) as typeof fs.readSync); + const b = spyOn(fs, "readFileSync").mockImplementation(((...args: Parameters) => { + const out = (readFileSync as (...x: unknown[]) => Buffer | string)(...args); + if (typeof args[0] === "number") most = Math.max(most, out.length); + return out; + }) as typeof fs.readFileSync); + cleanup.push(() => { a.mockRestore(); b.mockRestore(); }); + return () => most; +} + +function withPlatform(platform: NodeJS.Platform) { + const descriptor = Object.getOwnPropertyDescriptor(process, "platform")!; + Object.defineProperty(process, "platform", { ...descriptor, value: platform }); + cleanup.push(() => Object.defineProperty(process, "platform", descriptor)); +} + +/** Moves `context` aside and puts a fresh tree holding `replacement` at the old name. */ +function replaceAncestry(root: string) { + renameSync(join(root, "context"), join(root, "old-context")); + mkdirSync(join(root, "context/policies"), { recursive: true }); + writeFileSync(join(root, GOVERNANCE_POLICY_PATH), replacement); +} + +test("a valid policy is read with the hash of its exact bytes", () => { + const { root } = brain(); + const checked = checkGovernancePolicy(root); + expect(checked.status).toBe("valid"); + expect(checked.content_hash).toBe(sha(policy)); +}); + +test("a missing file and a missing ancestor both select defaults as missing", () => { + expect(checkGovernancePolicy(brain(null).root)).toMatchObject({ ok: true, status: "missing", content_hash: null, errors: [] }); + const { root } = brain(null); + rmSync(join(root, "context"), { recursive: true }); + expect(checkGovernancePolicy(root)).toMatchObject({ ok: true, status: "missing", content_hash: null }); +}); + +test("a symlinked policy file is refused, not followed", () => { + const { root, path } = brain(null); + writeFileSync(join(root, "elsewhere.md"), policy); + symlinkSync(join(root, "elsewhere.md"), path); + const checked = checkGovernancePolicy(root); + expect(checked).toMatchObject({ ok: false, status: "invalid", content_hash: null }); + expect(checked.errors[0]).toMatch(/ELOOP|symbolic link/i); +}); + +test("a symlinked ancestor is refused, not followed", () => { + const { root } = brain(); + renameSync(join(root, "context"), join(root, "real-context")); + symlinkSync(join(root, "real-context"), join(root, "context")); + expect(checkGovernancePolicy(root)).toMatchObject({ ok: false, status: "invalid", content_hash: null }); +}); + +test("a hardlinked policy file is refused", () => { + const { root, path } = brain(); + linkSync(path, join(root, "alias.md")); + expect(checkGovernancePolicy(root)).toMatchObject({ ok: false, status: "invalid", errors: ["Policy must be a regular file without hardlink aliases"] }); +}); + +test("a FIFO at the policy name is refused without blocking", () => { + const { path, root } = brain(null); + const made = Bun.spawnSync(["mkfifo", path]); + expect(made.exitCode).toBe(0); + expect(checkGovernancePolicy(root)).toMatchObject({ ok: false, status: "invalid", errors: ["Policy must be a regular file without hardlink aliases"] }); +}); + +test("an oversized policy is refused before its bytes are read", () => { + const { root } = brain("x".repeat(GOVERNANCE_POLICY_MAX_BYTES + 1)); + expect(checkGovernancePolicy(root)).toMatchObject({ ok: false, status: "invalid", errors: ["Policy exceeds the 1 MiB input bound"] }); +}); + +test("a short read (fewer bytes than the descriptor reported) is refused as a change", () => { + const { root } = brain(); + onPolicyStat(undefined, real => real + 16); + expect(checkGovernancePolicy(root)).toMatchObject({ ok: false, status: "invalid", errors: ["Policy changed while it was read; retry the check or repair the edit"] }); +}); + +test("a file that grows during the read is refused as a change", () => { + const { root, path } = brain(); + onPolicyStat(() => fs.appendFileSync(path, "Antinous appended this.\n")); + expect(checkGovernancePolicy(root)).toMatchObject({ ok: false, status: "invalid", errors: ["Policy changed while it was read; retry the check or repair the edit"] }); +}); + +test("a file that grows past the bound after its size check never loads more than the bound", () => { + const { root, path } = brain(); + const highWater = readHighWater(); + onPolicyStat(() => fs.appendFileSync(path, "x".repeat(4 * GOVERNANCE_POLICY_MAX_BYTES)), () => policy.length); + expect(checkGovernancePolicy(root)).toMatchObject({ ok: false, status: "invalid" }); + expect(highWater()).toBeLessThanOrEqual(GOVERNANCE_POLICY_MAX_BYTES + 1); +}); + +test("an ancestor replaced while the policy is read is refused on Linux (the writer's rule)", () => { + if (process.platform !== "linux") return; + const { root } = brain(); + const fired = onPolicyStat(() => replaceAncestry(root)); + const checked = checkGovernancePolicy(root); + expect(fired()).toBe(true); + expect(checked, "GOVERNANCE_READ_LINUX_ANCESTRY_RECHECK").toMatchObject({ ok: false, status: "invalid", errors: ["Policy ancestry changed while it was read"] }); +}); + +test("an ancestor removed while the policy is read is refused, not reported missing (non-Linux traversal)", () => { + const { root } = brain(); + withPlatform("darwin"); + const fired = onPolicyStat(() => renameSync(join(root, "context"), join(root, "old-context"))); + const checked = checkGovernancePolicy(root); + expect(fired()).toBe(true); + expect(checked, "GOVERNANCE_READ_REMOVED_ANCESTOR_IS_NOT_MISSING").toMatchObject({ ok: false, status: "invalid", errors: ["Policy ancestry changed while it was read"] }); +}); + +test("an ancestor replaced while the policy is read is refused (non-Linux traversal)", () => { + const { root } = brain(); + withPlatform("darwin"); + onPolicyStat(() => replaceAncestry(root)); + expect(checkGovernancePolicy(root)).toMatchObject({ ok: false, status: "invalid", errors: ["Policy ancestry changed while it was read"] }); +}); diff --git a/packages/ui-server/src/brain/policy-proposal.ts b/packages/ui-server/src/brain/policy-proposal.ts index 45a13cbd8d..8d22efe5c5 100644 --- a/packages/ui-server/src/brain/policy-proposal.ts +++ b/packages/ui-server/src/brain/policy-proposal.ts @@ -1,12 +1,11 @@ /** The only privileged policy writer. Worker input is never approval authority. */ -import { closeSync, constants, fchmodSync, fstatSync, fsyncSync, linkSync, lstatSync, mkdirSync, - openSync, readFileSync, realpathSync, renameSync, rmdirSync, unlinkSync, writeFileSync } from "node:fs"; -import { join } from "node:path"; +import { closeSync, constants, fchmodSync, fsyncSync, linkSync, openSync, realpathSync, renameSync, rmdirSync, unlinkSync, writeFileSync } from "node:fs"; import { createHash } from "node:crypto"; import type { SessionHistoryMessage } from "@schlessera/brain-ui-sdk/protocol"; import type { Database } from "bun:sqlite"; import { parseFrontmatter } from "@schlessera/brain-common/internal/frontmatter"; -import { parseGovernancePolicy, GOVERNANCE_POLICY_PATH, GOVERNANCE_POLICY_MAX_BYTES } from "@schlessera/brain-common/internal/governance-policy"; +import { parseGovernancePolicy, GOVERNANCE_POLICY_PATH, GovernancePolicyReadError, openGovernancePolicyAnchored, verifyGovernancePolicyAnchored, + type AnchoredGovernancePolicy, type GovernancePolicyReadRefusal } from "@schlessera/brain-common/internal/governance-policy"; import { BRAIN_LOCK_KEY, type KeyedLock } from "@schlessera/brain-ui-sdk/server"; import { PROPOSE_POLICY_CHANGE_INPUT_SCHEMA, type PolicyChangeInput, type PolicyChangeReview } from "@schlessera/brain-ui-sdk/tool-contracts"; import { admitHeld, AuthorityHeld, retryHeld, type AuthorityHold } from "./authority-hold.js"; @@ -15,53 +14,22 @@ import * as proposalWrites from "./policy-proposal-writes.js"; const hash = (bytes: string | Uint8Array) => createHash("sha256").update(bytes).digest("hex"); class Refusal extends Error { constructor(readonly state: "stale" | "invalid" | "refused", message: string) { super(message); } } -interface Dir { fd: number; path: string; dev: number; ino: number } -interface Target { chain: Dir[]; at: string; bytes: Buffer | null; mode?: number } -const flags = constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW; -function read(at: string): { bytes: Buffer | null; mode?: number } { - let fd: number; - try { fd = openSync(at, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); } - catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return { bytes: null }; throw error; } - try { - const info = fstatSync(fd); - if (!info.isFile() || info.nlink !== 1) throw new Refusal("refused", "Policy must be an ordinary file with one link. Nothing was written."); - if (info.size > GOVERNANCE_POLICY_MAX_BYTES) throw new Refusal("refused", "Policy exceeds the 1 MiB bound. Nothing was written."); - const bytes = readFileSync(fd), after = fstatSync(fd); - if (bytes.length > GOVERNANCE_POLICY_MAX_BYTES || after.size !== info.size || after.mtimeMs !== info.mtimeMs || after.ctimeMs !== info.ctimeMs) - throw new Refusal("stale", "Policy changed during review. Nothing was written."); - return { bytes, mode: info.mode & 0o7777 }; - } finally { closeSync(fd); } -} -function close(target: Target) { for (const dir of target.chain.reverse()) closeSync(dir.fd); } -function open(root: string, create = false, created: string[] = []): Target { - const chain: Dir[] = []; - try { - let visible = root; - const parts = GOVERNANCE_POLICY_PATH.split("/"); - for (let i = 0; i < parts.length; i++) { - const anchored = i === 0 ? root : `/proc/self/fd/${chain.at(-1)!.fd}/${parts[i - 1]}`; - if (create && i > 0) { - try { mkdirSync(anchored, { mode: 0o755 }); created.push(visible); } - catch (error) { if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; } - } - const fd = openSync(anchored, flags), info = fstatSync(fd); - chain.push({ fd, path: visible, dev: info.dev, ino: info.ino }); - visible = join(visible, parts[i]!); - } - const at = `/proc/self/fd/${chain.at(-1)!.fd}/governance.md`; - return { chain, at, ...read(at) }; - } catch (error) { for (const dir of chain.reverse()) closeSync(dir.fd); throw error; } -} -function verify(target: Target, expected: string | null) { - for (const dir of target.chain) { - const named = lstatSync(dir.path, { throwIfNoEntry: false }); - if (!named?.isDirectory() || named.isSymbolicLink() || named.dev !== dir.dev || named.ino !== dir.ino) - throw new Refusal("refused", "Policy ancestry changed. Nothing was written."); - } - const current = read(target.at).bytes; - if ((current === null ? null : hash(current)) !== expected) - throw new Refusal("stale", "The policy changed since this was proposed. Nothing was written. A fresh proposal is required."); +type Target = AnchoredGovernancePolicy; +/** The writer's review states and wording for common's anchored-read refusals. */ +const REFUSALS: Record = { + not_regular: ["refused", "Policy must be an ordinary file with one link. Nothing was written."], + oversize: ["refused", "Policy exceeds the 1 MiB bound. Nothing was written."], + changed: ["stale", "Policy changed during review. Nothing was written."], + ancestry: ["refused", "Policy ancestry changed. Nothing was written."], + mismatch: ["stale", "The policy changed since this was proposed. Nothing was written. A fresh proposal is required."], +}; +function refusing(read: () => T): T { + try { return read(); } + catch (error) { if (error instanceof GovernancePolicyReadError) throw new Refusal(...REFUSALS[error.refusal]); throw error; } } +const open = (root: string, create = false, created: string[] = []): Target => refusing(() => openGovernancePolicyAnchored(root, { create, created })); +const verify = (target: Target, expected: string | null) => { refusing(() => verifyGovernancePolicyAnchored(target, expected)); }; +const close = (target: Target) => target.close(); function base(root: string): Buffer | null { let target: Target; try { target = open(root); } @@ -220,7 +188,7 @@ export function createPolicyProposals(options: { // The operation owns the staging inode for this synchronous // callback only. Both journal observations are outside its // lifetime; no path/prefix ignore can hide real worker files. - const staging = `/proc/self/fd/${target!.chain.at(-1)!.fd}/.brain-policy-${crypto.randomUUID()}`; + const staging = `/proc/self/fd/${target!.directories.at(-1)!.fd}/.brain-policy-${crypto.randomUUID()}`; let publicationFailed = false, publicationError: unknown; try { const fd = openSync(staging, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, target!.mode ?? 0o644); @@ -240,7 +208,7 @@ export function createPolicyProposals(options: { } } if (publicationFailed) throw publicationError; - fsyncSync(target!.chain.at(-1)!.fd); + fsyncSync(target!.directories.at(-1)!.fd); }); review.state = "updated"; review.message = "Policy updated. Applies from the next turn."; await options.recordEvent(review, turn); diff --git a/packages/ui-server/tests/policy-proposal-read.test.ts b/packages/ui-server/tests/policy-proposal-read.test.ts new file mode 100644 index 0000000000..c8a443457e --- /dev/null +++ b/packages/ui-server/tests/policy-proposal-read.test.ts @@ -0,0 +1,181 @@ +/** + * How the policy writer reads the protected policy file (#2508): the base + * snapshot taken when a change is proposed, and the re-checks around the + * publication. Both go through common's descriptor-anchored reader + * (`packages/common/tests/governance-policy-read.test.ts`); these cases pin + * the writer's refusal states and messages on top of it. + * + * Races are staged through `node:fs` spies on the descriptor's `fstatSync`, + * so the same hooks drive the writer however it reads the bytes. + */ +import { afterEach, expect, spyOn, test } from "bun:test"; +import * as fs from "node:fs"; +import { linkSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { createHash } from "node:crypto"; +import { createKeyedLock } from "@schlessera/brain-ui-sdk/server"; +import { GOVERNANCE_POLICY_MAX_BYTES } from "@schlessera/brain-common/internal/governance-policy"; +import type { PolicyChangeReview } from "@schlessera/brain-ui-sdk/tool-contracts"; +import { createUiDb } from "../src/db/client.js"; +import { createPolicyProposals, type PolicyProposalTurn } from "../src/brain/policy-proposal.js"; + +const original = "---\nschema_version: 1\nprofiles:\n interactive: governed\n---\nOdysseus reviews the policy.\n"; +const proposed = original.replace("interactive: governed", "interactive: strict"); +const replacement = original.replace("reviews", "rewrites"); +const input = { content: proposed, rationale: "Use strict for the next turn." }; +const sha = (text: string | Uint8Array) => createHash("sha256").update(text).digest("hex"); +const cleanup: Array<() => void> = []; +afterEach(() => { for (const fn of cleanup.splice(0).reverse()) fn(); }); + +function fixture(content: string | null = original, patch: Partial[0]> = {}) { + const root = mkdtempSync(join(tmpdir(), "policy-read-")); cleanup.push(() => rmSync(root, { recursive: true, force: true })); + mkdirSync(join(root, "context/policies"), { recursive: true }); + const path = join(root, "context/policies/governance.md"); + if (content !== null) writeFileSync(path, content); + const db = createUiDb(":memory:"); cleanup.push(() => db.close()); + const reviews: PolicyChangeReview[] = []; + let allow = false; + const service = createPolicyProposals({ root, db, lock: createKeyedLock(), observeUserPolicy: (_id, write) => write(), recordEvent: () => {}, ...patch }); + const turn: PolicyProposalTurn = { principalId: "odysseus", turnId: "policy-read-turn", sessionId: () => null, signal: new AbortController().signal, + isAuthorized: () => true, isAvailable: () => true, approve: async review => { reviews.push(structuredClone(review)); return allow; }, emit() {} }; + return { root, path, service, turn, reviews, approve: () => { allow = true; } }; +} + +/** Runs `hook` once, on the first regular-file fstat; `size` overrides every regular-file size. */ +function onPolicyStat(hook?: () => void, size?: (real: number) => number) { + const original = fs.fstatSync; + let fired = false; + const spy = spyOn(fs, "fstatSync").mockImplementation(((fd: number, options?: fs.StatOptions) => { + const info = original(fd, options as never) as fs.Stats; + if (!info.isFile()) return info; + if (!fired && hook) { fired = true; hook(); } + if (size) Object.defineProperty(info, "size", { value: size(info.size) }); + return info; + }) as typeof fs.fstatSync); + cleanup.push(() => spy.mockRestore()); + return () => fired; +} + +/** Largest single result either read API handed back for a descriptor. */ +function readHighWater() { + const readSync = fs.readSync, readFileSync = fs.readFileSync; + let most = 0; + const a = spyOn(fs, "readSync").mockImplementation(((...args: Parameters) => { + const n = (readSync as (...x: unknown[]) => number)(...args); most = Math.max(most, n); return n; + }) as typeof fs.readSync); + const b = spyOn(fs, "readFileSync").mockImplementation(((...args: Parameters) => { + const out = (readFileSync as (...x: unknown[]) => Buffer | string)(...args); + if (typeof args[0] === "number") most = Math.max(most, out.length); + return out; + }) as typeof fs.readFileSync); + cleanup.push(() => { a.mockRestore(); b.mockRestore(); }); + return () => most; +} + +function replaceAncestry(root: string) { + renameSync(join(root, "context"), join(root, "old-context")); + mkdirSync(join(root, "context/policies"), { recursive: true }); + writeFileSync(join(root, "context/policies/governance.md"), replacement); +} + +test("the base snapshot hashes the exact current bytes", async () => { + const f = fixture(); + expect((await f.service.propose(f.turn, "base", input)).state).toBe("declined"); + expect(f.reviews[0]!.baseHash).toBe(sha(original)); +}); + +test("a missing file and a missing ancestor both propose against no base", async () => { + const a = fixture(null); + await a.service.propose(a.turn, "no-file", input); + expect(a.reviews[0]!.baseHash).toBeNull(); + const b = fixture(null); + rmSync(join(b.root, "context"), { recursive: true }); + await b.service.propose(b.turn, "no-ancestor", input); + expect(b.reviews[0]!.baseHash).toBeNull(); +}); + +test("a symlinked policy file or ancestor is refused before review", async () => { + const a = fixture(null); + writeFileSync(join(a.root, "elsewhere.md"), original); symlinkSync(join(a.root, "elsewhere.md"), a.path); + await expect(a.service.propose(a.turn, "symlink", input)).rejects.toThrow(/ELOOP|symbolic link/i); + const b = fixture(); + renameSync(join(b.root, "context"), join(b.root, "real-context")); symlinkSync(join(b.root, "real-context"), join(b.root, "context")); + await expect(b.service.propose(b.turn, "ancestor", input)).rejects.toThrow(); + expect(a.reviews.length + b.reviews.length).toBe(0); +}); + +test("a hardlinked policy file or a FIFO is refused as not an ordinary file", async () => { + const a = fixture(); + linkSync(a.path, join(a.root, "alias.md")); + await expect(a.service.propose(a.turn, "hardlink", input)).rejects.toThrow("Policy must be an ordinary file with one link. Nothing was written."); + const b = fixture(null); + expect(Bun.spawnSync(["mkfifo", b.path]).exitCode).toBe(0); + await expect(b.service.propose(b.turn, "fifo", input)).rejects.toThrow("Policy must be an ordinary file with one link. Nothing was written."); +}); + +test("an oversized policy is refused before its bytes are read", async () => { + const f = fixture("x".repeat(GOVERNANCE_POLICY_MAX_BYTES + 1)); + await expect(f.service.propose(f.turn, "oversize", input)).rejects.toThrow("Policy exceeds the 1 MiB bound. Nothing was written."); +}); + +test("a short read (fewer bytes than the descriptor reported) is refused as stale", async () => { + const f = fixture(); + onPolicyStat(undefined, real => real + 16); + await expect(f.service.propose(f.turn, "short", input), "POLICY_WRITER_SHORT_READ").rejects.toThrow("Policy changed during review. Nothing was written."); + expect(f.reviews).toHaveLength(0); +}); + +test("a file that grows during the read is refused as stale", async () => { + const f = fixture(); + onPolicyStat(() => fs.appendFileSync(f.path, "Antinous appended this.\n")); + await expect(f.service.propose(f.turn, "grows", input)).rejects.toThrow("Policy changed during review. Nothing was written."); +}); + +test("a file that grows past the bound after its size check never loads more than the bound", async () => { + const f = fixture(); + const highWater = readHighWater(); + onPolicyStat(() => fs.appendFileSync(f.path, "x".repeat(4 * GOVERNANCE_POLICY_MAX_BYTES)), () => original.length); + await expect(f.service.propose(f.turn, "unbounded", input)).rejects.toThrow("Policy changed during review. Nothing was written."); + expect(highWater(), "POLICY_WRITER_BOUNDED_READ").toBeLessThanOrEqual(GOVERNANCE_POLICY_MAX_BYTES + 1); +}); + +test("an ancestor replaced while the base is read is refused", async () => { + const f = fixture(); + const fired = onPolicyStat(() => replaceAncestry(f.root)); + await expect(f.service.propose(f.turn, "ancestry", input)).rejects.toThrow("Policy ancestry changed. Nothing was written."); + expect(fired()).toBe(true); +}); + +test("an ancestor replaced between the publication's open and its verify is refused", async () => { + const f = fixture(original, { beforeCommit: () => replaceAncestry(f.root) }); + f.approve(); + const review = await f.service.propose(f.turn, "ancestry-publish", input); + expect(review).toMatchObject({ state: "refused", message: "Policy ancestry changed. Nothing was written." }); + expect(readFileSync(join(f.root, "old-context/policies/governance.md"), "utf8")).toBe(original); + expect(readFileSync(f.path, "utf8")).toBe(replacement); +}); + +test("a policy file replaced by rename between the publication's open and its verify is stale", async () => { + const f = fixture(original, { beforeCommit: () => { writeFileSync(join(f.root, "next.md"), replacement); renameSync(join(f.root, "next.md"), f.path); } }); + f.approve(); + const review = await f.service.propose(f.turn, "replaced-publish", input); + expect(review).toMatchObject({ state: "stale", message: "The policy changed since this was proposed. Nothing was written. A fresh proposal is required." }); + expect(readFileSync(f.path, "utf8")).toBe(replacement); +}); + +test("a policy file hardlinked between the publication's open and its verify is refused", async () => { + const f = fixture(original, { beforeCommit: () => linkSync(f.path, join(f.root, "alias.md")) }); + f.approve(); + const review = await f.service.propose(f.turn, "hardlink-publish", input); + expect(review).toMatchObject({ state: "refused", message: "Policy must be an ordinary file with one link. Nothing was written." }); + expect(readFileSync(f.path, "utf8")).toBe(original); +}); + +test("publication creates the missing ancestry and the file", async () => { + const f = fixture(null); + rmSync(join(f.root, "context"), { recursive: true }); + f.approve(); + expect((await f.service.propose(f.turn, "create", input)).state).toBe("updated"); + expect(readFileSync(f.path, "utf8")).toBe(proposed); +}); From dbcab6461e653f61b4d1a3fabadd12d66957ef1e Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 3 Nov 2026 13:58:23 +0100 Subject: [PATCH 3/4] fix(core,ui-react): find frontmatter fences through one shared frontmatterBlock (#2507) (#3462) * feat(common): add frontmatterBlock, the fence rule parseFrontmatter reads by (#2507) Co-Authored-By: Claude Opus 5.5 * fix(core,ui-react): find frontmatter fences through frontmatterBlock at every site (#2507) validate, import --stamp, the OKF check and hygiene now read a block after a byte order mark; tags --apply and the key editor share one bounds and scalar reader; ui-react splitFrontmatter reads a closing fence at end of file. Hygiene keeps a stricter closing rule because it rewrites the body. Co-Authored-By: Claude Opus 5.5 * feat(lint): refuse frontmatter fences detected by hand in package source (#2507) Co-Authored-By: Claude Opus 5.5 * docs(decisions): record the frontmatter fence ruling and move citations (#2507) Co-Authored-By: Claude Opus 5.5 * test: spell the byte order mark as an escape in the fence tests (#2507) Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- .changeset/frontmatter-block-once.md | 8 ++ api-report/common.txt | 5 ++ api-report/ui-sdk.txt | 2 + docs/decisions/frontmatter-parsing.md | 43 +++++++++- docs/decisions/hygiene-review.md | 22 ++--- docs/decisions/mechanical-hygiene.md | 6 +- .../decisions/module-instruction-ownership.md | 2 +- docs/decisions/voice-permission.md | 2 +- .../audit-capability-investigation.md | 6 +- packages/common/README.md | 1 + packages/common/package.json | 5 ++ packages/common/src/frontmatter-block.ts | 63 ++++++++++++++ .../common/tests/frontmatter-block.test.ts | 52 ++++++++++++ packages/core/src/cli/commands/import.ts | 6 +- packages/core/src/lib/document-parts.ts | 20 ++--- packages/core/src/lib/frontmatter-edit.ts | 62 +++++++++----- packages/core/src/lib/generated-regions.ts | 18 ++-- packages/core/src/lib/hygiene.ts | 23 +++-- packages/core/src/lib/okf-exporter.ts | 4 +- packages/core/src/lib/tags-apply.ts | 56 +----------- packages/core/src/lib/validate.ts | 6 +- packages/core/tests/cli-onboarding.test.ts | 16 ++++ .../core/tests/frontmatter-fences.test.ts | 85 +++++++++++++++++++ packages/core/tests/hygiene.test.ts | 18 ++++ packages/core/tests/okf-exporter.test.ts | 10 +++ packages/core/tests/validate.test.ts | 11 +++ packages/ui-react/src/lib/frontmatter.ts | 24 +++--- packages/ui-react/tests/frontmatter.test.ts | 36 ++++++++ packages/ui-sdk/src/internal-client.ts | 1 + scripts/check-frontmatter-parse.ts | 80 +++++++++++++++-- tests/frontmatter-parse-gate.test.ts | 70 ++++++++++++++- 31 files changed, 615 insertions(+), 148 deletions(-) create mode 100644 .changeset/frontmatter-block-once.md create mode 100644 packages/common/src/frontmatter-block.ts create mode 100644 packages/common/tests/frontmatter-block.test.ts create mode 100644 packages/core/tests/frontmatter-fences.test.ts diff --git a/.changeset/frontmatter-block-once.md b/.changeset/frontmatter-block-once.md new file mode 100644 index 0000000000..453c062ef6 --- /dev/null +++ b/.changeset/frontmatter-block-once.md @@ -0,0 +1,8 @@ +--- +"@schlessera/brain-common": patch +"@schlessera/brain": patch +"@schlessera/brain-ui-sdk": patch +"@schlessera/brain-ui-react": patch +--- + +Where a document's frontmatter block starts and ends now has one implementation, `frontmatterBlock` in the new internal entry `@schlessera/brain-common/internal/frontmatter-block` (#2507). It follows the rule `parseFrontmatter` reads by. `frontmatterLength` moved there too, and core re-exports it. Five fixes follow. `brain validate` accepts a document whose frontmatter follows a byte order mark, and reports a `----` first line as missing frontmatter. `brain import --stamp` skips a file whose frontmatter follows a byte order mark instead of stamping a second block over it. The OKF bundle check sees frontmatter after a byte order mark. `brain hygiene` reads and keeps such a log file's frontmatter instead of rewriting it as body. `brain tags --apply` and the frontmatter key editor share one bounds and scalar reader. One rule is stricter than before: hygiene now refuses a log file whose closing fence has text after the dashes (`----`, `---x`). The public `splitFrontmatter` from `@schlessera/brain-ui-react` now reads a block that follows a byte order mark, has trailing whitespace after its opening fence, or is closed by a fence at the end of the file. It still returns an unclosed block as body. `bun run lint` refuses a frontmatter fence detected by hand in package source. The new entry, and its re-export from the ui-sdk's `internal/client`, are internal and carry no compatibility promise. diff --git a/api-report/common.txt b/api-report/common.txt index 9bb9440cc0..cb47c3621a 100644 --- a/api-report/common.txt +++ b/api-report/common.txt @@ -34,6 +34,11 @@ export "./internal/frontmatter" (./src/frontmatter-parse.ts) type ParsedFrontmatter parseFrontmatter +export "./internal/frontmatter-block" (./src/frontmatter-block.ts) + type FrontmatterBlock + frontmatterBlock + frontmatterLength + export "./internal/governance-policy" (./src/governance-policy.ts) type AnchoredGovernancePolicy BUILTIN_GOVERNANCE_POLICY diff --git a/api-report/ui-sdk.txt b/api-report/ui-sdk.txt index 170ac517a5..01e19f5414 100644 --- a/api-report/ui-sdk.txt +++ b/api-report/ui-sdk.txt @@ -1269,6 +1269,7 @@ export "./internal" (./src/internal.ts) workerSandboxWarnings export "./internal/client" (./src/internal-client.ts) + type FrontmatterBlock type LinkEdit type ShareTargetError askUserFormPayload @@ -1281,6 +1282,7 @@ export "./internal/client" (./src/internal-client.ts) defaultAsrClientRegistry defaultToolRendererRegistry describeRetry + frontmatterBlock handleShareTargetRequest isShareTargetRequest pruneStoredShares diff --git a/docs/decisions/frontmatter-parsing.md b/docs/decisions/frontmatter-parsing.md index 410cd3cf75..db2380ab91 100644 --- a/docs/decisions/frontmatter-parsing.md +++ b/docs/decisions/frontmatter-parsing.md @@ -54,7 +54,7 @@ maintainer chose option B on #142 on 2026-09-28. - Rule 1: gray-matter may be loaded (`import`, `import type`, `export … from`, `import x = require()`, `require()`, `import()`, subpaths) only by the files in its `ALLOWED` list (`ALLOWED`, - `scripts/check-frontmatter-parse.ts:40-62`). + `scripts/check-frontmatter-parse.ts:50-72`). - Rule 2: inside those files, the default binding may only be called with an object literal where gray-matter takes its options, or named in a type. Aliases, re-exports, `matter.read`, `matter.cache` and variable options @@ -105,6 +105,44 @@ This repairs the documented data-only input guarantee. It changes no supported YAML meaning, envelope, approval authority, descriptor read, size limit or last-valid fallback. See the [file-layer contract](../integration-contract/frontmatter.md#file-layer-contracts). +## Where the block starts and ends (#2507, 2026-11-03) + +Finding the fences without parsing the YAML has one answer too: +`frontmatterBlock` (`frontmatterBlock`, +`packages/common/src/frontmatter-block.ts:42-55`), reached through +`@schlessera/brain-common/internal/frontmatter-block`. It returns the offsets +of the opening fence, the inner YAML lines and the end of the block, plus +whether a closing fence was found, by gray-matter's rule: an optional byte +order mark, `---` not followed by a fourth `-`, the first `\n---` after it, and +one line ending after that. It imports nothing, so ui-react reaches it through +ui-sdk's browser-safe `internal/client` entry. `frontmatterLength` moved with +it; core re-exports it. A table-driven test holds it to `parseFrontmatter` on a +byte order mark, CRLF, trailing whitespace after either fence, a closing fence +at the end of the file, `----`, a leading blank line, an unclosed block, an +empty block and a `...` line. + +Nine places had their own rule. Each now asks `frontmatterBlock`, and each +default is the parser's answer, except where a stricter answer protects a +write: + +| Site | Disagreed on | Rule now | +| --- | --- | --- | +| `brain validate` | BOM (reported `frontmatter-missing`); `----` counted as a fence | the parser's | +| `brain import --stamp` | BOM (stamped a second block over the first, which became body) | the parser's | +| OKF bundle check | BOM (rejected explicitly: a marked concept "missing frontmatter", a marked `index.md` block let through) | the parser's | +| generated regions | none in effect; its search ignored the BOM offset | the parser's, still refusing an unclosed block | +| `brain tags --apply` and the key editor | two `frontmatterBounds`/`readScalar` pairs; the tags copy searched back from the block's end and took the closing fence into the block when a `---` rule followed it | one pair, in `frontmatter-edit.ts`; an unclosed block has no bounds | +| hygiene log files | BOM (frontmatter read as body and rewritten) | the parser's opening; **stricter closing**: a block not closed by a `---` line with only whitespace after it is refused, including `----`, `---x` and `...` closers the parser would end at or run past, because hygiene rewrites the body | +| ui-react `splitFrontmatter` | BOM; a closing fence at the end of the file | the parser's, except that an unclosed block is shown as body rather than swallowed, so the viewer never hides text | +| ui-server policy review `split` | accepts a `...` closer | unchanged for now; open on #2507 | + +Rule 3 of the gate (`scanFences`, `scripts/check-frontmatter-parse.ts:222-252`) +refuses a hand-written detector in package source: a non-multiline regex +anchored at a leading `---` (a BOM before it included), `startsWith("---…")` +and `indexOf`/`lastIndexOf("\n---…")`. Files that emit or post-process a fence +they wrote, and the pending policy splitter, are listed in `FENCE_ALLOWED` +with a reason each. + ## Rejected alternatives - **Pass `{}` at every call site (O1).** This was already half-done, and the @@ -158,6 +196,9 @@ file is parsed once per run. - An edit to the helper is made once, in `packages/common`. - A new entry in `ALLOWED` needs a reason that says why the file cannot reach the cache. "It only parses once" is not one: the cache is process-wide. +- A new entry in `FENCE_ALLOWED` needs a reason that says why the file is not + reading an arbitrary document's fences: it emits them, or it post-processes + text it emitted. ## Superseded: a copy per parsing package diff --git a/docs/decisions/hygiene-review.md b/docs/decisions/hygiene-review.md index 9bbb297a99..366642bde0 100644 --- a/docs/decisions/hygiene-review.md +++ b/docs/decisions/hygiene-review.md @@ -43,8 +43,8 @@ or a snooze reset by an unrelated edit, makes the owner's decision temporary. Reuse the existing markdown log and deterministic CLI operations. A candidate already carries category, path and stable evidence (`HygieneCandidate`, -`packages/core/src/lib/hygiene.ts:68-84`), and its ID derives from those fields -(`hygieneId`, `packages/core/src/lib/hygiene.ts:181-184`). Those primitives do not +`packages/core/src/lib/hygiene.ts:69-85`), and its ID derives from those fields +(`hygieneId`, `packages/core/src/lib/hygiene.ts:182-185`). Those primitives do not by themselves supply validation-to-hygiene equivalence, priority selection or review dispositions. The CLI exposes reconciliation, listing and deterministic selection (`hygieneCommand`, `packages/core/src/cli/commands/hygiene.ts:221-223`). @@ -135,11 +135,11 @@ shapes are in [the integration contract](../integration-contract/package-api.md# **Equivalence map.** Each `brain validate` rule becomes a candidate with a category and ID evidence (`VALIDATION_JOIN`, -`packages/core/src/lib/hygiene.ts:199-212`). Validation gives the join a +`packages/core/src/lib/hygiene.ts:200-213`). Validation gives the join a structured detail, so the message is never read (`export interface ValidationDetail`, -`packages/core/src/lib/validate.ts:43-51`). Candidates are one finding exactly +`packages/core/src/lib/validate.ts:44-52`). Candidates are one finding exactly when category, path and evidence agree, and the join does not depend on their -order (`canonicalFindings`, `packages/core/src/lib/hygiene.ts:283-333`). +order (`canonicalFindings`, `packages/core/src/lib/hygiene.ts:284-334`). | Validation rule | Category | ID evidence | Joins | | --- | --- | --- | --- | @@ -161,7 +161,7 @@ a source states it; otherwise it stays unknown. **Evidence fingerprints.** A fingerprint is 12 hex digits of SHA-1 over the category and a hash of each field below (`FINGERPRINT_FIELDS`, -`packages/core/src/lib/hygiene.ts:246-259`). Line numbers, messages, other +`packages/core/src/lib/hygiene.ts:247-260`). Line numbers, messages, other document content and age are never in it. | Category | Fingerprint fields | @@ -180,7 +180,7 @@ an invalidation can name the fields that changed. entries in `context/hygiene/dismissed.md`, snoozed ones in `snoozed.md`. Each records its time and the fingerprint it applied to. `until:` takes an ISO date-time or a date; a date is due at the start of that UTC day, as before -(`function dueAt`, `packages/core/src/lib/hygiene.ts:863-873`). A recorded +(`function dueAt`, `packages/core/src/lib/hygiene.ts:872-882`). A recorded fingerprint that no longer matches reopens the finding at once, with an `invalidated:` receipt naming the changed fields and the disposition's date. A snooze that comes due reopens it with no receipt. @@ -190,7 +190,7 @@ identity), the new finding carries the receipt only when the pairing is unambiguous. In one run, exactly one disposition in force with that category and path stops being detected, and exactly one new finding with them appears (`if (prior.length === 1 && siblings.length === 1)`, -`packages/core/src/lib/hygiene.ts:1513`). Otherwise the new finding opens +`packages/core/src/lib/hygiene.ts:1522`). Otherwise the new finding opens without one. Either way the old disposition does not suppress it. Entries moved by hand carry no fingerprint, so they keep their earlier behaviour. @@ -209,11 +209,11 @@ made (K1 A). It lives in `context/hygiene/kept.md`, which is never created empty. It holds only while the original's fingerprint is unchanged and its copy is a contained regular file outside `.brain/` and `workspaces/` that `media.track` keeps. Otherwise the original reopens with an `invalidated:` -receipt (`keptInvalidity`, `packages/core/src/lib/hygiene.ts:998-1008`). +receipt (`keptInvalidity`, `packages/core/src/lib/hygiene.ts:1007-1017`). Sync's count and review use one read-only function that applies these predicates to the log as it stands rather than trusting the file an entry sits -in (K2 B; `mediaReviewCounts`, `packages/core/src/lib/hygiene.ts:1753-1768`). +in (K2 B; `mediaReviewCounts`, `packages/core/src/lib/hygiene.ts:1762-1777`). Leave pending is a per-pass deferral in review state, never a log state: it skips the finding while its fingerprint holds, and the finding still counts. @@ -241,7 +241,7 @@ permission, premise revalidation and a real post-apply check before success. Do not implement dismissal by marking a still-detected finding resolved: existing reconciliation reopens such an entry (`const prev = field(entry, "resolved-by")`, -`packages/core/src/lib/hygiene.ts:1487-1490`). Keep review disposition distinct from +`packages/core/src/lib/hygiene.ts:1496-1499`). Keep review disposition distinct from actual check success and from notification acknowledgement. Markdown remains authoritative for findings, dispositions and confirmed content diff --git a/docs/decisions/mechanical-hygiene.md b/docs/decisions/mechanical-hygiene.md index 980bb9807d..57a88d2af7 100644 --- a/docs/decisions/mechanical-hygiene.md +++ b/docs/decisions/mechanical-hygiene.md @@ -36,10 +36,10 @@ scratch state are excluded from source-byte scoring; an input hygiene file remains protected. The prototype reuses table detection (`indexTableLag`, -`packages/core/src/lib/hygiene.ts:541-583`), scalar table rendering +`packages/core/src/lib/hygiene.ts:542-584`), scalar table rendering (`renderRegistry`, `packages/core/src/lib/index-registry.ts:117-185`) and the surgical frontmatter editor (`editFrontmatter`, -`packages/core/src/lib/frontmatter-edit.ts:216-224`). It intentionally refuses +`packages/core/src/lib/frontmatter-edit.ts:232-240`). It intentionally refuses wiki links and an entire index containing an unsafe row. ## Held-out quality and reliability @@ -134,7 +134,7 @@ one explicit providerless CLI planner/apply operation for this supported grammar, with `--json` and dry-run output, followed by the existing reconciliation. Re-read every consulted input and use the existing unchanged-source writer (`replaceIfUnchanged`, -`packages/core/src/lib/hygiene.ts:1236-1246`) before application. Keep registry +`packages/core/src/lib/hygiene.ts:1245-1255`) before application. Keep registry ownership, inbox/archive exclusions and all unhandled cases visible as log-only. The skill delegates these two mechanical operations; canonical judgment remains with it. That follow-up needs the additive contract documentation and normal diff --git a/docs/decisions/module-instruction-ownership.md b/docs/decisions/module-instruction-ownership.md index fd8e77c703..0848854686 100644 --- a/docs/decisions/module-instruction-ownership.md +++ b/docs/decisions/module-instruction-ownership.md @@ -30,7 +30,7 @@ The existing module mechanism builds contributions from validated config (`ModuleContribution`, `packages/core/src/lib/module-types.ts:136-164`). The generated-region helper replaces a whole named block and preserves bytes outside it (`replaceGeneratedRegion`, -`packages/core/src/lib/generated-regions.ts:99-120`). Neither a shared block +`packages/core/src/lib/generated-regions.ts:100-121`). Neither a shared block nor its heading establishes which module owns each paragraph. The CLI needs an authoritative source and explicit ownership to remove, regenerate and measure module instructions deterministically. diff --git a/docs/decisions/voice-permission.md b/docs/decisions/voice-permission.md index 98f58d7964..012ab4c409 100644 --- a/docs/decisions/voice-permission.md +++ b/docs/decisions/voice-permission.md @@ -255,7 +255,7 @@ as its allowlist and declares both `enforceAllowedTools` and `noGrantSurface`. | `mcp__brain__brain_graph` | Read-only. | | `mcp__brain__jobs_review` | Read-only query over the owner's local jobs queue, returning at most 50 summaries. No egress: it does not scrape, fetch listing URLs, change review decisions or create a missing database. Admitted 2026-10-01 (#605). | | `mcp__brain-ui__brain_add` | Creates a new document. The single most valuable eyes-free action there is — capture. A create destroys nothing: the worst case is a document the user did not want, which appears in Files and is removable. | -| `mcp__brain-ui__brain_update` | Edits an existing document. "Add this to my note about X" is the second most valuable eyes-free action, and the handler's shape is why it is safe enough to allow: it **never rewrites the body**, it only appends to it (`const appendTo`, `packages/core/src/lib/frontmatter-edit.ts:303-308`), so no prose can be lost. The exact bound on what it *can* destroy: the six frontmatter params are independent optionals on one call (`summary: z.string()`, `packages/core/src/mcp-server.ts:428-433`), applied independently (`input.summary !== undefined`, `packages/core/src/lib/ops/write.ts:88-100`), so **a single call can overwrite all six** — and `tags` replaces the whole tag list rather than merging into it (the terminal MCP accepts a comma-separated string, while the hosted route accepts a string array; `input.tags !== undefined`, `packages/core/src/lib/ops/write.ts:91`), while `deadline` and `next_review` take `""` as *delete the field* (`input.deadline !== undefined`, `packages/core/src/lib/ops/write.ts:92-99`). `updated` is bumped unconditionally (`updates.updated = updated`, `packages/core/src/lib/ops/write.ts:115`). None of it is checkpointed, so git recovers a prior value only if the document was committed. The claim this row rests on is therefore "loses no prose, and at most the six declared frontmatter fields, recoverable only if committed" — not "recoverable". `status` is the field that matters and it is handled separately below. | +| `mcp__brain-ui__brain_update` | Edits an existing document. "Add this to my note about X" is the second most valuable eyes-free action, and the handler's shape is why it is safe enough to allow: it **never rewrites the body**, it only appends to it (`const appendTo`, `packages/core/src/lib/frontmatter-edit.ts:319-324`), so no prose can be lost. The exact bound on what it *can* destroy: the six frontmatter params are independent optionals on one call (`summary: z.string()`, `packages/core/src/mcp-server.ts:428-433`), applied independently (`input.summary !== undefined`, `packages/core/src/lib/ops/write.ts:88-100`), so **a single call can overwrite all six** — and `tags` replaces the whole tag list rather than merging into it (the terminal MCP accepts a comma-separated string, while the hosted route accepts a string array; `input.tags !== undefined`, `packages/core/src/lib/ops/write.ts:91`), while `deadline` and `next_review` take `""` as *delete the field* (`input.deadline !== undefined`, `packages/core/src/lib/ops/write.ts:92-99`). `updated` is bumped unconditionally (`updates.updated = updated`, `packages/core/src/lib/ops/write.ts:115`). None of it is checkpointed, so git recovers a prior value only if the document was committed. The claim this row rests on is therefore "loses no prose, and at most the six declared frontmatter fields, recoverable only if committed" — not "recoverable". `status` is the field that matters and it is handled separately below. | | `Read`, `Glob`, `Grep` | Read-only over the brain repo, for the questions the brain tools do not cover. No mutation, no egress. | | `WebSearch`, `WebFetch` | Read-only egress. Kept, with the exposure stated below. | | the bridge tools, minus the mask editor | `ask_user`, `get_current_location`, `query_activity`, `show_block`, `turn_temp` are auto-allowed today and none of them is a permission decision (the same `allowed.push` block, from `const allowed`, `sdk-options.ts:194-219`). `request_image_mask` needs the user to paint a region, so it needs eyes; it is out. | diff --git a/docs/investigations/audit-capability-investigation.md b/docs/investigations/audit-capability-investigation.md index 76b61f09dc..84758d461a 100644 --- a/docs/investigations/audit-capability-investigation.md +++ b/docs/investigations/audit-capability-investigation.md @@ -74,7 +74,7 @@ Planning parses complete child metadata (`planRegistry`, `packages/core/src/lib/index-registry.ts:210-262`). Tag migration is real code (`applyTagChanges`, -`packages/core/src/lib/tags-apply.ts:435-497`): configured alias chains and +`packages/core/src/lib/tags-apply.ts:381-443`): configured alias chains and eligible variant groups determine the plan; raw tag entries are changed while other bytes, including `updated`, remain. The CLI opens its index before writes, then reindexes and accepts only the exact rewritten bytes. Literal configured @@ -150,8 +150,8 @@ Unsupported, missing, invalid and no-op cases stay manual/unavailable. Reindex after authoritative Markdown changes, then rerun the finding's actual check; partial repair or a failed check never becomes success. -Reuse (`candidateFromAudit`, `packages/core/src/lib/hygiene.ts:351-391`) and -(`hygieneId`, `packages/core/src/lib/hygiene.ts:181-184`) without inventing another +Reuse (`candidateFromAudit`, `packages/core/src/lib/hygiene.ts:352-392`) and +(`hygieneId`, `packages/core/src/lib/hygiene.ts:182-185`) without inventing another identity or disposition store. The [hygiene-review policy](../decisions/hygiene-review.md) binds #597's canonical equivalence, severity/known-urgency ordering and relevant evidence invalidation. This investigation chooses no mappings, review controls diff --git a/packages/common/README.md b/packages/common/README.md index ad1ec100f9..3e6d19da57 100644 --- a/packages/common/README.md +++ b/packages/common/README.md @@ -11,6 +11,7 @@ one; it arrives as their dependency. | --- | --- | | `@schlessera/brain-common/internal/env` | The environment descriptor contract (`EnvVarSpec`, `DynamicEnvReadSpec`), `readEnvVar`, and the boolean parsers `envFlag` and `envPresent`. Each package keeps its own `src/config/env.ts` chokepoint on top of it. | | `@schlessera/brain-common/internal/frontmatter` | `parseFrontmatter`, the only door to gray-matter's parser. It always passes an options object, so gray-matter's process-wide cache is never read or written ([decision](../../docs/decisions/frontmatter-parsing.md)). | +| `@schlessera/brain-common/internal/frontmatter-block` | `frontmatterBlock` and `frontmatterLength`: where a frontmatter block starts and ends, by the rule `parseFrontmatter` reads by, without parsing it. It imports nothing, so browser code can use it; every package that needs only the fences asks it (#2507). | | `@schlessera/brain-common/internal/worker-areas` | The hosted worker's write-area names and the rules stated about them: turn temp is never linked, the link rule, and the read-only-brain rule. The ui-sdk's sandbox note and core's `brain` CLI refusal both render them, so the refusal repeats the note word for word (#1654, admitted by #1693). | | `@schlessera/brain-common/internal/protected-paths` | The protected worker path tiers shared by core policy validation and the sandbox. | | `@schlessera/brain-common/internal/governance-policy` | Data-only policy schema, defaults, parsing and anchored reads shared by the core CLI and hosted server (#1744). The server can read policy without installing its optional core peer. Its policy writer reads and re-checks the file through the same descriptor-anchored reader (#2508). | diff --git a/packages/common/package.json b/packages/common/package.json index 314678be3e..50b30e59d8 100644 --- a/packages/common/package.json +++ b/packages/common/package.json @@ -36,6 +36,11 @@ "types": "./dist/frontmatter-parse.d.ts", "default": "./dist/frontmatter-parse.js" }, + "./internal/frontmatter-block": { + "bun": "./src/frontmatter-block.ts", + "types": "./dist/frontmatter-block.d.ts", + "default": "./dist/frontmatter-block.js" + }, "./internal/worker-areas": { "bun": "./src/worker-areas.ts", "types": "./dist/worker-areas.d.ts", diff --git a/packages/common/src/frontmatter-block.ts b/packages/common/src/frontmatter-block.ts new file mode 100644 index 0000000000..13f15f5212 --- /dev/null +++ b/packages/common/src/frontmatter-block.ts @@ -0,0 +1,63 @@ +// Internal to brain-kit: reached through +// `@schlessera/brain-common/internal/frontmatter-block`, with no compatibility +// promise. Where a document's frontmatter block starts and ends, by the rule +// `parseFrontmatter` (gray-matter 4.0.3) reads it. It imports nothing, so a +// browser bundle can use it (ui-react reaches it through ui-sdk's +// `internal/client`). Every site that needs the fences, but not the YAML, +// asks this instead of writing its own regex (#2507); +// scripts/check-frontmatter-parse.ts refuses a hand-written one. + +/** + * Offsets of a frontmatter block in the original text: + * + * - `start`: where the opening `---` is (1 after a byte order mark, else 0). + * - `innerStart`: after the opening fence's line ending (the end of the text + * when that line has none). + * - `innerEnd`: up to the closing fence, its preceding line ending included, + * so `text.slice(innerStart, innerEnd)` is the block's YAML lines; the end + * of the text when the block is not closed. + * - `end`: after the closing fence and one line ending following it, which is + * where `parseFrontmatter`'s `content` starts; the end of the text when the + * block is not closed. + * - `closed`: whether a closing fence was found. gray-matter reads an + * unclosed block to the end of the file; a writer should refuse one. + */ +export interface FrontmatterBlock { + start: number; + innerStart: number; + innerEnd: number; + end: number; + closed: boolean; +} + +/** + * The frontmatter block, or null when the text has none. gray-matter's rule: + * after a byte order mark, which it strips, the text opens with `---` not + * followed by a fourth `-` (anything else on that line is a language name); + * the block runs to the first `\n---` after it, wherever on its line that + * `---` is followed by more text, and one `\r` and one `\n` after the fence + * belong to it. A leading blank line means no frontmatter; a `...` line does + * not close it. + */ +export function frontmatterBlock(text: string): FrontmatterBlock | null { + const start = text.charCodeAt(0) === 0xfeff ? 1 : 0; + if (!text.startsWith("---", start) || text.charAt(start + 3) === "-") return null; + const newline = text.indexOf("\n", start); + const close = text.indexOf("\n---", start + 3); + if (close === -1) { + return { start, innerStart: newline === -1 ? text.length : newline + 1, innerEnd: text.length, end: text.length, closed: false }; + } + let end = close + 4; + if (text[end] === "\r") end++; + if (text[end] === "\n") end++; + return { start, innerStart: newline + 1, innerEnd: close + 1, end, closed: true }; +} + +/** + * Length of the frontmatter block, `frontmatterBlock(text).end`, or 0 when + * there is none. The length counts a byte order mark, so it is an offset into + * the original text. + */ +export function frontmatterLength(text: string): number { + return frontmatterBlock(text)?.end ?? 0; +} diff --git a/packages/common/tests/frontmatter-block.test.ts b/packages/common/tests/frontmatter-block.test.ts new file mode 100644 index 0000000000..ee92820e7b --- /dev/null +++ b/packages/common/tests/frontmatter-block.test.ts @@ -0,0 +1,52 @@ +/** + * `frontmatterBlock` finds the fences `parseFrontmatter` reads by (#2507). + * Every row is checked against the parser itself, so a change to either side + * that makes them disagree fails here. + */ + +import { describe, expect, test } from "bun:test"; + +import { frontmatterBlock, frontmatterLength } from "../src/frontmatter-block"; +import { parseFrontmatter } from "../src/frontmatter-parse"; + +const BOM = "\uFEFF"; + +const rows: Array<{ name: string; text: string; block: ReturnType; data?: Record }> = [ + { name: "plain LF", text: "---\ntitle: a\n---\nbody\n", block: { start: 0, innerStart: 4, innerEnd: 13, end: 17, closed: true }, data: { title: "a" } }, + { name: "byte order mark", text: `${BOM}---\ntitle: a\n---\nbody\n`, block: { start: 1, innerStart: 5, innerEnd: 14, end: 18, closed: true }, data: { title: "a" } }, + { name: "CRLF", text: "---\r\ntitle: a\r\n---\r\nbody\r\n", block: { start: 0, innerStart: 5, innerEnd: 15, end: 20, closed: true }, data: { title: "a" } }, + { name: "trailing whitespace after the opening fence", text: "--- \ntitle: a\n---\nbody\n", block: { start: 0, innerStart: 5, innerEnd: 14, end: 18, closed: true }, data: { title: "a" } }, + // gray-matter ends the block at the dashes; the whitespace starts the content. + { name: "trailing whitespace after the closing fence", text: "---\ntitle: a\n--- \nbody\n", block: { start: 0, innerStart: 4, innerEnd: 13, end: 16, closed: true }, data: { title: "a" } }, + { name: "closing fence at the end of the file", text: "---\ntitle: a\n---", block: { start: 0, innerStart: 4, innerEnd: 13, end: 16, closed: true }, data: { title: "a" } }, + { name: "four dashes are not a fence", text: "----\ntitle: a\n----\nbody\n", block: null }, + { name: "a leading blank line means no frontmatter", text: "\n---\ntitle: a\n---\nbody\n", block: null }, + { name: "no frontmatter", text: "# Title\n", block: null }, + { name: "unclosed block runs to the end", text: "---\ntitle: a\n", block: { start: 0, innerStart: 4, innerEnd: 13, end: 13, closed: false }, data: { title: "a" } }, + { name: "empty block", text: "---\n---\nbody\n", block: { start: 0, innerStart: 4, innerEnd: 4, end: 8, closed: true }, data: {} }, + // The first `\n---` closes; the next `---` line is a rule in the body. + { name: "a rule right after the closing fence", text: "---\ntitle: a\n---\n---\nbody\n", block: { start: 0, innerStart: 4, innerEnd: 13, end: 17, closed: true }, data: { title: "a" } }, + // A `...` line does not close a block: everything to the end is frontmatter. + { name: "a ... line is not a closer", text: "---\ntitle: a\n...\n", block: { start: 0, innerStart: 4, innerEnd: 17, end: 17, closed: false }, data: { title: "a" } }, +]; + +describe("frontmatterBlock agrees with parseFrontmatter", () => { + for (const row of rows) { + test(row.name, () => { + const block = frontmatterBlock(row.text); + expect(block).toEqual(row.block); + expect(frontmatterLength(row.text)).toBe(block?.end ?? 0); + const parsed = parseFrontmatter(row.text, { dataOnly: true }); + if (!block) { + expect(parsed.matter).toBe(""); + expect(parsed.data).toEqual({}); + return; + } + // What the parser treats as body is exactly what follows the block. + expect(parsed.content).toBe(row.text.slice(block.end)); + // What it treats as YAML is exactly the block's inner lines. + expect(parsed.matter.trim()).toBe(row.text.slice(block.innerStart, block.innerEnd).trim()); + expect(parsed.data).toEqual(row.data!); + }); + } +}); diff --git a/packages/core/src/cli/commands/import.ts b/packages/core/src/cli/commands/import.ts index 4c88a47772..a6f8bf8f55 100644 --- a/packages/core/src/cli/commands/import.ts +++ b/packages/core/src/cli/commands/import.ts @@ -2,6 +2,8 @@ import { readFileSync, statSync } from "fs"; import { resolve } from "path"; import { Glob } from "bun"; +import { frontmatterBlock } from "@schlessera/brain-common/internal/frontmatter-block"; + import { stringifyDocument } from "../../lib/frontmatter.js"; import { safeResolve, writeFileSafely } from "../../lib/safe-path.js"; import type { CoreCommand } from "../types.js"; @@ -48,7 +50,9 @@ export const importCommand: CoreCommand = { const full = resolve(base, rel); try { const raw = readFileSync(full, "utf-8"); - if (raw.startsWith("---")) { + // Frontmatter as the indexer finds it (#2507): a byte order mark + // before the fence still counts, so that block is never stamped over. + if (frontmatterBlock(raw)) { skipped.push(rel); continue; } diff --git a/packages/core/src/lib/document-parts.ts b/packages/core/src/lib/document-parts.ts index c5c96ec409..e9b1624913 100644 --- a/packages/core/src/lib/document-parts.ts +++ b/packages/core/src/lib/document-parts.ts @@ -3,6 +3,8 @@ import remarkGfm from "remark-gfm"; import remarkParse from "remark-parse"; import { unified } from "unified"; +import { frontmatterLength } from "@schlessera/brain-common/internal/frontmatter-block"; + import { caseFold } from "./case-fold.js"; import { estimateTokens } from "./chunker.js"; @@ -65,22 +67,10 @@ const parser = unified().use(remarkParse).use(remarkGfm); /** * Length of the frontmatter block, by the rule gray-matter applies when core - * reads a document: after a byte order mark, which gray-matter strips, the - * file opens with `---` not followed by a fourth `-`, and the block runs to - * the first `\n---` (to the end of the file if there is none), plus one line - * ending after it. The length counts the mark, so it is an offset into the - * original text. + * reads a document. It lives with `frontmatterBlock` next to `parseFrontmatter` + * in brain-common, so every site that finds the fences agrees (#2507). */ -export function frontmatterLength(text: string): number { - const bom = text.charCodeAt(0) === 0xfeff ? 1 : 0; - if (!text.startsWith("---", bom) || text.charAt(bom + 3) === "-") return 0; - const close = text.indexOf("\n---", bom + 3); - if (close === -1) return text.length; - let end = close + 4; - if (text[end] === "\r") end++; - if (text[end] === "\n") end++; - return end; -} +export { frontmatterLength } from "@schlessera/brain-common/internal/frontmatter-block"; interface LocatedHeading { level: number; diff --git a/packages/core/src/lib/frontmatter-edit.ts b/packages/core/src/lib/frontmatter-edit.ts index 94b370b2e4..f0e07cdfd9 100644 --- a/packages/core/src/lib/frontmatter-edit.ts +++ b/packages/core/src/lib/frontmatter-edit.ts @@ -14,48 +14,64 @@ */ import { parseFrontmatter } from "@schlessera/brain-common/internal/frontmatter"; +import { frontmatterBlock, frontmatterLength } from "@schlessera/brain-common/internal/frontmatter-block"; -import { frontmatterLength } from "./document-parts.js"; import { stringifyDocument } from "./frontmatter.js"; /** A new value: a string, a list of strings (written in flow style), or null to remove the key. */ export type FrontmatterValue = string | string[] | null; -interface Token { +/** A scalar's offsets in the block, quotes included, its quote, and its value with quotes and escapes read. */ +export interface ScalarToken { start: number; end: number; quote: '"' | "'" | null; + value: string; } -/** The frontmatter's inner text: after the opening `---` line, up to the closing `---` line. */ -function frontmatterBounds(text: string): { start: number; end: number } | null { - const length = frontmatterLength(text); - if (length === 0) return null; - // The first `\n---` after the opening fence, as frontmatterLength finds it: - // a later `---` or `----` line is a horizontal rule in the body. - const bom = text.charCodeAt(0) === 0xfeff ? 1 : 0; - const close = text.indexOf("\n---", bom + 3); - const start = text.indexOf("\n") + 1; - return close !== -1 && start > 0 && start <= close + 1 ? { start, end: close + 1 } : null; +type Token = Omit; + +/** + * The frontmatter's inner text: after the opening `---` line, up to the + * closing `---` line, by the fences `parseFrontmatter` reads (#2507). Null + * when there is no block, or when it is never closed: an edit cannot know + * where the body starts. `brain tags --apply` uses the same bounds. + */ +export function frontmatterBounds(text: string): { start: number; end: number } | null { + const block = frontmatterBlock(text); + return block?.closed ? { start: block.innerStart, end: block.innerEnd } : null; } -/** One scalar at `i`: quoted to its closing quote, or plain up to the line end or ` #`. */ -function readScalar(block: string, i: number): Token | null { - const quote = block[i]; +/** + * One scalar at `i`: quoted to its closing quote on the same line, or plain up + * to the line end, a character in `stops`, or ` #`. Null when there is none. + * Shared with `brain tags --apply`, which stops a flow entry at `,` and `]`. + */ +export function readScalar(text: string, i: number, stops = ""): ScalarToken | null { + const quote = text[i]; if (quote === '"' || quote === "'") { - for (let j = i + 1; j < block.length; j++) { - const c = block[j]; + let value = ""; + for (let j = i + 1; j < text.length; j++) { + const c = text[j]; if (c === "\n" || c === "\r") return null; - if (quote === '"' && c === "\\") j++; - else if (quote === "'" && c === "'" && block[j + 1] === "'") j++; - else if (c === quote) return { start: i, end: j + 1, quote }; + if (quote === '"' && c === "\\") { + const next = text[++j]; + value += next === "n" ? "\n" : next === "t" ? "\t" : next ?? ""; + } else if (quote === "'" && c === "'" && text[j + 1] === "'") { + value += "'"; + j++; + } else if (c === quote) { + return { start: i, end: j + 1, quote, value }; + } else { + value += c; + } } return null; } let j = i; - while (j < block.length && block[j] !== "\n" && block[j] !== "\r" && !/^[ \t]#/.test(block.slice(j, j + 2))) j++; - const raw = block.slice(i, j).replace(/[ \t]+$/, ""); - return raw ? { start: i, end: i + raw.length, quote: null } : null; + while (j < text.length && !stops.includes(text[j]!) && text[j] !== "\n" && text[j] !== "\r" && !/^[ \t]#/.test(text.slice(j, j + 2))) j++; + const raw = text.slice(i, j).replace(/[ \t]+$/, ""); + return raw ? { start: i, end: i + raw.length, quote: null, value: raw } : null; } /** A one-line flow sequence at `i`: up to its `]`, quoted entries skipped whole. */ diff --git a/packages/core/src/lib/generated-regions.ts b/packages/core/src/lib/generated-regions.ts index ae90c39ea0..75531dfee4 100644 --- a/packages/core/src/lib/generated-regions.ts +++ b/packages/core/src/lib/generated-regions.ts @@ -15,7 +15,8 @@ * and dashboard tables. */ -import { frontmatterLength } from "./document-parts.js"; +import { frontmatterBlock } from "@schlessera/brain-common/internal/frontmatter-block"; + import { codeRanges } from "./markdown-code.js"; /** A region name: lowercase letters, digits and dashes. */ @@ -124,14 +125,17 @@ export function replaceGeneratedRegion(body: string, name: string, content: stri * Split a file into its frontmatter block, kept verbatim (`---` fences * included), and its body. Frontmatter is never re-serialized: hand-written * YAML keeps its layout. Where the block starts follows the rule core reads - * documents by (`frontmatterLength`); a block that opens and never closes - * throws, since which part is the body cannot be known. + * documents by (`frontmatterBlock`, #2507); a block that opens and never + * closes throws, since which part is the body cannot be known. The + * frontmatter ends with the closing fence's three dashes; its line ending + * starts the body. */ export function splitFrontmatterBlock(raw: string): { frontmatter: string; body: string } { - if (frontmatterLength(raw) === 0) return { frontmatter: "", body: raw }; - const close = raw.indexOf("\n---", 3); - if (close === -1) throw new Error("frontmatter has no closing --- line"); - return { frontmatter: raw.slice(0, close + 4), body: raw.slice(close + 4) }; + const block = frontmatterBlock(raw); + if (!block) return { frontmatter: "", body: raw }; + if (!block.closed) throw new Error("frontmatter has no closing --- line"); + const fenceEnd = block.innerEnd + 3; + return { frontmatter: raw.slice(0, fenceEnd), body: raw.slice(fenceEnd) }; } /** diff --git a/packages/core/src/lib/hygiene.ts b/packages/core/src/lib/hygiene.ts index c0c97daaef..ddcd9581b6 100644 --- a/packages/core/src/lib/hygiene.ts +++ b/packages/core/src/lib/hygiene.ts @@ -17,6 +17,7 @@ import type { Database } from "bun:sqlite"; import { createHash } from "crypto"; import { closeSync, constants, existsSync, fstatSync, lstatSync, mkdirSync, openSync, readFileSync, readSync, realpathSync } from "fs"; +import { frontmatterBlock } from "@schlessera/brain-common/internal/frontmatter-block"; import { parseFrontmatter } from "@schlessera/brain-common/internal/frontmatter"; import { join, posix, resolve } from "path"; import remarkGfm from "remark-gfm"; @@ -712,7 +713,6 @@ export class HygieneLogError extends Error {} /** An entry heading: `### ` and one token ending in the ID's `-hash4`. */ const ENTRY_HEADING = /^### +(\S+-[0-9a-f]{4})[ \t]*\r?$/; -const FRONTMATTER = /^---[ \t]*\r?\n[\s\S]*?\r?\n---[ \t]*(?:\r?\n|$)/; /** A `## ` section of a log file, or (heading null) the text before the first one. */ interface Segment { @@ -735,14 +735,23 @@ interface LogFile { } /** - * The frontmatter and body of a log file. A file that opens a frontmatter - * block it does not close, or whose block is not a YAML mapping, is refused: - * rewriting it would mean guessing where the frontmatter ends. + * The frontmatter and body of a log file, by the fences the indexer reads + * (`frontmatterBlock`, #2507): a byte order mark before the opening fence + * still opens a block. A file that opens a block it does not close with a + * `---` line, or whose block is not a YAML mapping, is refused: rewriting it + * would mean guessing where the frontmatter ends. That is stricter than the + * indexer on purpose, because this rewrites the body. A closing fence with + * more than whitespace after its dashes (`----`, `---x`) is refused too: the + * indexer ends the block there, an author probably did not. The frontmatter + * keeps the closing line's trailing whitespace and line ending. */ function splitFrontmatter(text: string, rel: string): { frontmatter: string; body: string } { - if (!/^---[ \t]*\r?\n/.test(text)) return { frontmatter: "", body: text }; - const frontmatter = FRONTMATTER.exec(text)?.[0]; - if (!frontmatter) throw new HygieneLogError(`${rel}: the frontmatter is never closed with ---; fix it by hand, brain hygiene will not rewrite it`); + const block = frontmatterBlock(text); + if (!block) return { frontmatter: "", body: text }; + // After the closing dashes: optional whitespace, then a line ending or the end of the file. + const rest = block.closed ? /^[ \t]*(?:\r?\n|$)/.exec(text.slice(block.innerEnd + 3)) : null; + if (!rest) throw new HygieneLogError(`${rel}: the frontmatter is never closed with a --- line; fix it by hand, brain hygiene will not rewrite it`); + const frontmatter = text.slice(0, block.innerEnd + 3 + rest[0].length); let data: unknown; try { data = parseFrontmatter(frontmatter, { dataOnly: true }).data; diff --git a/packages/core/src/lib/okf-exporter.ts b/packages/core/src/lib/okf-exporter.ts index a3f4128191..46b5cc8330 100644 --- a/packages/core/src/lib/okf-exporter.ts +++ b/packages/core/src/lib/okf-exporter.ts @@ -1,4 +1,5 @@ import { Glob } from "bun"; +import { frontmatterBlock } from "@schlessera/brain-common/internal/frontmatter-block"; import { parseFrontmatter, type ParsedFrontmatter } from "@schlessera/brain-common/internal/frontmatter"; import { existsSync, @@ -488,8 +489,9 @@ export async function exportOkfBundle(options: OkfExportOptions): Promise 0 && start <= close + 1 ? { start, end: close + 1 } : null; -} - -interface Token { - /** Offsets of the scalar in the block text, quotes included. */ - start: number; - end: number; - value: string; -} - -/** Read one scalar at `i`: quoted, or plain up to a stop character or ` #`. */ -function readScalar(text: string, i: number, stops: string): Token | null { - const quote = text[i]; - if (quote === '"' || quote === "'") { - let j = i + 1; - let value = ""; - while (j < text.length) { - const c = text[j]; - if (quote === "'" && c === "'" && text[j + 1] === "'") { - value += "'"; - j += 2; - } else if (quote === '"' && c === "\\") { - const next = text[j + 1]; - value += next === "n" ? "\n" : next === "t" ? "\t" : next; - j += 2; - } else if (c === quote) { - return { start: i, end: j + 1, value }; - } else if (c === "\n" || c === "\r") { - return null; - } else { - value += c; - j++; - } - } - return null; - } - let j = i; - while (j < text.length && !stops.includes(text[j]) && !"\r\n".includes(text[j]) && !/^[ \t]#/.test(text.slice(j, j + 2))) { - j++; - } - const raw = text.slice(i, j).replace(/[ \t]+$/, ""); - return raw ? { start: i, end: i + raw.length, value: raw } : null; -} - /** A tag as YAML: plain when that reads back as the same string, else double-quoted. */ function yamlScalar(tag: string): string { const plain = diff --git a/packages/core/src/lib/validate.ts b/packages/core/src/lib/validate.ts index 9c531ae46e..e3504670ed 100644 --- a/packages/core/src/lib/validate.ts +++ b/packages/core/src/lib/validate.ts @@ -14,6 +14,7 @@ * the taxonomy so validation and the indexer's link graph agree exactly. */ +import { frontmatterBlock } from "@schlessera/brain-common/internal/frontmatter-block"; import { parseFrontmatter } from "@schlessera/brain-common/internal/frontmatter"; import { readFileSync, existsSync } from "fs"; import { resolve } from "path"; @@ -148,8 +149,9 @@ export function validateDetailed(root: string, taxonomy: Taxonomy): DetailedVali const fullPath = resolve(root, filePath); const raw = readFileSync(fullPath, "utf-8"); - // Check for frontmatter - if (!raw.startsWith("---")) { + // Check for frontmatter, by the fences the indexer reads (#2507): a + // byte order mark before them is fine, a `----` line is not a fence. + if (!frontmatterBlock(raw)) { issues.push({ file: filePath, level: "error", diff --git a/packages/core/tests/cli-onboarding.test.ts b/packages/core/tests/cli-onboarding.test.ts index 48f315ed4b..8f729ba0cc 100644 --- a/packages/core/tests/cli-onboarding.test.ts +++ b/packages/core/tests/cli-onboarding.test.ts @@ -110,6 +110,22 @@ test("import --stamp adds frontmatter to bare markdown", async () => { expect(stamped).toContain("status: draft"); }); +test("import --stamp skips frontmatter after a byte order mark instead of stamping over it (#2507)", async () => { + const root = tempBrain(); + const importDir = join(root, "import", "vault"); + mkdirSync(importDir, { recursive: true }); + const marked = "\uFEFF---\ntype: note\ntitle: Already\n---\nbody\n"; + writeFileSync(join(importDir, "marked.md"), marked); + writeFileSync(join(importDir, "rule.md"), "----\n\nA rule, not a fence.\n"); + + const { stdout, code } = await runCli(root, ["import", "--stamp", "import/vault", "--json"]); + expect(code).toBe(0); + const out = JSON.parse(stdout); + expect(out.skipped).toEqual(["marked.md"]); + expect(out.stamped).toEqual(["rule.md"]); + expect(readFileSync(join(importDir, "marked.md"), "utf-8")).toBe(marked); +}); + test("skills lint fails on a broken fixture skill", async () => { const root = tempBrain(); const skillDir = join(root, ".agents", "skills", "broken-skill"); diff --git a/packages/core/tests/frontmatter-fences.test.ts b/packages/core/tests/frontmatter-fences.test.ts new file mode 100644 index 0000000000..5637c4a060 --- /dev/null +++ b/packages/core/tests/frontmatter-fences.test.ts @@ -0,0 +1,85 @@ +/** + * Core's raw frontmatter editors find the block through `frontmatterBlock`, + * the rule `parseFrontmatter` reads by (#2507): the generated-region splitter, + * the key editor and `brain tags --apply` (which share one `frontmatterBounds` + * and one `readScalar`). + */ + +import { describe, expect, test } from "bun:test"; + +import { editFrontmatter, frontmatterBounds, readScalar, type ScalarToken } from "../src/lib/frontmatter-edit"; +import { splitFrontmatterBlock } from "../src/lib/generated-regions"; +import { rewriteTags } from "../src/lib/tags-apply"; + +const BOM = "\uFEFF"; + +describe("splitFrontmatterBlock", () => { + test.each([ + ["LF", "---\ntitle: a\n---\nbody\n", "---\ntitle: a\n---", "\nbody\n"], + ["a byte order mark", `${BOM}---\ntitle: a\n---\nbody\n`, `${BOM}---\ntitle: a\n---`, "\nbody\n"], + ["CRLF", "---\r\ntitle: a\r\n---\r\nbody\r\n", "---\r\ntitle: a\r\n---", "\r\nbody\r\n"], + ["a closing fence at the end of the file", "---\ntitle: a\n---", "---\ntitle: a\n---", ""], + ["a rule right after the closing fence", "---\ntitle: a\n---\n---\nbody\n", "---\ntitle: a\n---", "\n---\nbody\n"], + ["a leading blank line", "\n---\ntitle: a\n---\n", "", "\n---\ntitle: a\n---\n"], + ["a four-dash first line", "----\ntitle: a\n", "", "----\ntitle: a\n"], + ])("%s", (_, raw, frontmatter, body) => { + expect(splitFrontmatterBlock(raw)).toEqual({ frontmatter, body }); + }); + + test("a block that is never closed is refused", () => { + expect(() => splitFrontmatterBlock("---\ntitle: a\nbody\n")).toThrow("no closing --- line"); + expect(() => splitFrontmatterBlock(`${BOM}---\ntitle: a\n`)).toThrow("no closing --- line"); + }); +}); + +describe("frontmatterBounds, shared by the key editor and brain tags --apply", () => { + test.each([ + ["LF", "---\ntitle: a\n---\nbody\n", "title: a\n"], + ["a byte order mark", `${BOM}---\ntitle: a\n---\nbody\n`, "title: a\n"], + ["CRLF", "---\r\ntitle: a\r\n---\r\nbody\r\n", "title: a\r\n"], + ["a closing fence at the end of the file", "---\ntitle: a\n---", "title: a\n"], + // The copy in tags-apply searched back from the block's end, so this one + // took the closing fence into the block. + ["a rule right after the closing fence", "---\ntitle: a\n---\n---\nbody\n", "title: a\n"], + ["an empty block", "---\n---\nbody\n", ""], + ])("%s", (_, text, inner) => { + const bounds = frontmatterBounds(text); + expect(bounds && text.slice(bounds.start, bounds.end)).toBe(inner); + }); + + test("no block, or one never closed, has no bounds", () => { + for (const text of ["\n---\ntitle: a\n---\n", "----\ntitle: a\n----\n", "---\ntitle: a\n", "---\ntitle: a\n...\n"]) { + expect(frontmatterBounds(text)).toBeNull(); + } + }); + + test("the key editor keeps a byte order mark and an end-of-file fence", () => { + expect(editFrontmatter(`${BOM}---\ntitle: a\n---\nbody\n`, { title: "b" })).toBe(`${BOM}---\ntitle: b\n---\nbody\n`); + expect(editFrontmatter("---\ntitle: a\n---", { title: "b" })).toBe("---\ntitle: b\n---"); + }); + + test("brain tags --apply rewrites the tags after a byte order mark and before a rule", () => { + expect(rewriteTags(`${BOM}---\ntitle: T\ntags: [old]\n---\nbody\n`, () => ["new"])).toEqual({ + text: `${BOM}---\ntitle: T\ntags: [new]\n---\nbody\n`, from: ["old"], to: ["new"], + }); + expect(rewriteTags("---\ntitle: T\ntags:\n - old\n---\n---\nbody\n", () => ["new"])).toEqual({ + text: "---\ntitle: T\ntags:\n - new\n---\n---\nbody\n", from: ["old"], to: ["new"], + }); + }); +}); + +describe("readScalar, the one scalar reader both editors use", () => { + test.each<[string, string, string, ScalarToken]>([ + ["a plain scalar up to a comment", "abc # note", "", { start: 0, end: 3, quote: null, value: "abc" }], + ["a plain scalar up to a stop", "abc, def", ",]", { start: 0, end: 3, quote: null, value: "abc" }], + ["a double-quoted scalar with escapes", '"a\\"b\\n"', "", { start: 0, end: 8, quote: '"', value: 'a"b\n' }], + ["a single-quoted scalar with a doubled quote", "'it''s'", "", { start: 0, end: 7, quote: "'", value: "it's" }], + ])("%s", (_, text, stops, token) => { + expect(readScalar(text, 0, stops)).toEqual(token); + }); + + test("a quote not closed on its line, or nothing to read, is null", () => { + expect(readScalar('"open\n"', 0)).toBeNull(); + expect(readScalar(" # only a comment", 0)).toBeNull(); + }); +}); diff --git a/packages/core/tests/hygiene.test.ts b/packages/core/tests/hygiene.test.ts index 8bef8de11d..485363cb91 100644 --- a/packages/core/tests/hygiene.test.ts +++ b/packages/core/tests/hygiene.test.ts @@ -651,9 +651,27 @@ describe("writing the log", () => { expect(read(root, "resolved.md")).toContain(`### ${idOf(goes)}\n${seen}\n\nAsked about this on Monday.\n- resolved-by: auto-disappeared`); }); + test("a log file whose frontmatter follows a byte order mark keeps it as frontmatter (#2507)", () => { + const root = tempRoot(); + const seen = "- **First seen**: 2026-06-01 · **Last seen**: 2026-06-01"; + const frontmatter = '\uFEFF---\ntype: context\ntitle: "Open"\ncreated: 2026-01-01\nupdated: 2026-01-01\n---\n'; + mkdirSync(join(root, "context/hygiene"), { recursive: true }); + writeFileSync(log(root, "open.md"), `${frontmatter}\n## TODO markers\n\n${entry(idOf(goes), seen)}\n`); + expect(reconcile(root, [], docs, { now: NOW })).toMatchObject({ resolved: 1 }); + // The block is read where the indexer reads it: kept, mark included, with only `updated` set. + expect(read(root, "open.md")).toStartWith(frontmatter.replace("updated: 2026-01-01", `updated: ${TODAY}`)); + expect(read(root, "open.md")).not.toContain(`### ${idOf(goes)}`); + expect(read(root, "resolved.md")).toContain(`### ${idOf(goes)}`); + }); + test.each([ ["frontmatter that is not valid YAML", '---\ntitle: "unclosed\nupdated: 2026-01-01\n---\n\n## Resolved\n', "not valid YAML"], ["frontmatter that is never closed", "---\ntitle: Resolved\n\n## Resolved\n", "never closed"], + // The indexer ends these blocks at the dashes; an author probably did not (#2507). + ["a closing fence with text after its dashes", "---\ntitle: Resolved\n---x\n\n## Resolved\n---\n", "never closed"], + ["a four-dash closing line", "---\ntitle: Resolved\n----\n\n## Resolved\n---\n", "never closed"], + ["a ... closing line", "---\ntitle: Resolved\n...\n\n## Resolved\n", "never closed"], + ["a byte order mark before a block that is never closed", "\uFEFF---\ntitle: Resolved\n\n## Resolved\n", "never closed"], ["frontmatter that is a list, not a mapping", "---\n- one\n- two\n---\n\n## Resolved\n", "not a YAML mapping"], ["a section holding entries and other text", "## Parked\n\nA note.\n\n### todo-notes-goes-abcd\n- resolved-by: manual\n", 'section "## Parked"'], ])("a log file with %s is refused, and nothing is written", (_, text, message) => { diff --git a/packages/core/tests/okf-exporter.test.ts b/packages/core/tests/okf-exporter.test.ts index a476460af1..ee0c1e81d2 100644 --- a/packages/core/tests/okf-exporter.test.ts +++ b/packages/core/tests/okf-exporter.test.ts @@ -348,4 +348,14 @@ describe("OKF checker", () => { expect(errorReport.ok).toBe(false); expect(errorReport.errors).toBeGreaterThanOrEqual(4); }); + + test("finds frontmatter after a byte order mark, as the parser reads it (#2507)", () => { + const root = makeBrain({ + "index.md": "\uFEFF---\ntitle: Not allowed\n---\n# Bundle\n\n* [Concept](concept.md)\n", + "concept.md": `\uFEFF${document("Concept", "Body.")}`, + }); + const messages = checkOkfBundle(root).issues.map((issue) => `${issue.path}: ${issue.message}`); + expect(messages).toContain("index.md: index.md must not have frontmatter (except root okf_version only)"); + expect(messages).not.toContain("concept.md: concept document is missing YAML frontmatter"); + }); }); diff --git a/packages/core/tests/validate.test.ts b/packages/core/tests/validate.test.ts index c5c8a73538..c5a785be05 100644 --- a/packages/core/tests/validate.test.ts +++ b/packages/core/tests/validate.test.ts @@ -62,6 +62,17 @@ describe("validate", () => { }); }); + test("accepts frontmatter after a byte order mark, as the indexer reads it (#2507)", () => { + const fields = { type: "identity", title: "Identity", created: '"2026-01-01"', updated: '"2026-01-02"', tags: "[me]" }; + const root = makeCorpus({ "me/identity.md": `\uFEFF${doc(fields)}` }); + expect(validate(root, taxonomy).filter((i) => i.level === "error")).toEqual([]); + }); + + test("a four-dash first line is not frontmatter (#2507)", () => { + const root = makeCorpus({ "notes/raw.md": "----\ntitle: x\n----\nbody\n" }); + expect(validate(root, taxonomy)).toContainEqual({ file: "notes/raw.md", level: "error", message: "Missing YAML frontmatter" }); + }); + test("reports an invalid type and lists the taxonomy's valid types", () => { const root = makeCorpus({ "notes/x.md": doc({ type: "bogus", title: "X", tags: "[a]" }), diff --git a/packages/ui-react/src/lib/frontmatter.ts b/packages/ui-react/src/lib/frontmatter.ts index 452fc8f845..be305ac97a 100644 --- a/packages/ui-react/src/lib/frontmatter.ts +++ b/packages/ui-react/src/lib/frontmatter.ts @@ -5,8 +5,17 @@ * array (`tags: [a, b, c]`) and quoted string. We don't need a full YAML * parser — a small focused split keeps the bundle tiny and the behaviour * predictable. + * + * Where the block starts and ends is not decided here: `frontmatterBlock` + * (brain-common, through the ui-sdk) finds the fences by the rule the indexer + * reads documents by, so a byte order mark, CRLF and a closing fence at the + * end of the file read as they do everywhere else (#2507). One deliberate + * difference: a block that is never closed is shown as body, not swallowed as + * frontmatter, so a viewer never hides text it cannot delimit. */ +import { frontmatterBlock } from "@schlessera/brain-ui-sdk/internal/client"; + export interface FrontmatterField { key: string; /** Raw value as it appears in the file (quotes stripped). */ @@ -20,18 +29,11 @@ export interface FrontmatterSplit { body: string; } -const OPEN = /^---\r?\n/; - export function splitFrontmatter(md: string): FrontmatterSplit { - if (!OPEN.test(md)) return { fields: [], body: md }; - // Find closing `---` on its own line after the opener. - const afterOpen = md.replace(OPEN, ""); - const closeMatch = afterOpen.match(/\r?\n---\r?\n/); - if (!closeMatch || closeMatch.index === undefined) { - return { fields: [], body: md }; - } - const rawFrontmatter = afterOpen.slice(0, closeMatch.index); - const body = afterOpen.slice(closeMatch.index + closeMatch[0].length); + const block = frontmatterBlock(md); + if (!block?.closed) return { fields: [], body: md }; + const rawFrontmatter = md.slice(block.innerStart, block.innerEnd); + const body = md.slice(block.end); const fields: FrontmatterField[] = []; for (const line of rawFrontmatter.split(/\r?\n/)) { diff --git a/packages/ui-react/tests/frontmatter.test.ts b/packages/ui-react/tests/frontmatter.test.ts index 52c6a619a6..c51e78c573 100644 --- a/packages/ui-react/tests/frontmatter.test.ts +++ b/packages/ui-react/tests/frontmatter.test.ts @@ -90,4 +90,40 @@ describe("splitFrontmatter", () => { const r = splitFrontmatter(md); expect(r.body).toBe("\n\nbody line\n"); }); + + // The fences are found by frontmatterBlock, the rule the indexer reads by (#2507). + test("a closing fence at the end of the file closes the block", () => { + const r = splitFrontmatter("---\ntitle: a\n---"); + expect(r.fields).toEqual([{ key: "title", value: "a" }]); + expect(r.body).toBe(""); + }); + + test("frontmatter after a byte order mark is read", () => { + const r = splitFrontmatter("\uFEFF---\ntitle: a\n---\nbody\n"); + expect(r.fields).toEqual([{ key: "title", value: "a" }]); + expect(r.body).toBe("body\n"); + }); + + test("CRLF fences are read and the body keeps its line endings", () => { + const r = splitFrontmatter("---\r\ntitle: a\r\n---\r\nbody\r\n"); + expect(r.fields).toEqual([{ key: "title", value: "a" }]); + expect(r.body).toBe("body\r\n"); + }); + + test("trailing whitespace after the opening fence still opens a block", () => { + const r = splitFrontmatter("--- \ntitle: a\n---\nbody\n"); + expect(r.fields).toEqual([{ key: "title", value: "a" }]); + expect(r.body).toBe("body\n"); + }); + + test("a block that is never closed is shown as body, not hidden", () => { + const md = "---\ntitle: a\nbody\n"; + expect(splitFrontmatter(md)).toEqual({ fields: [], body: md }); + }); + + test("a leading blank line or a four-dash line is not frontmatter", () => { + for (const md of ["\n---\ntitle: a\n---\nbody\n", "----\ntitle: a\n----\nbody\n"]) { + expect(splitFrontmatter(md)).toEqual({ fields: [], body: md }); + } + }); }); diff --git a/packages/ui-sdk/src/internal-client.ts b/packages/ui-sdk/src/internal-client.ts index 522a2da0a5..6f5d5e720c 100644 --- a/packages/ui-sdk/src/internal-client.ts +++ b/packages/ui-sdk/src/internal-client.ts @@ -10,4 +10,5 @@ export { canonicalModelId, describeRetry, resolveThinkingLevel } from "./protoco export { pruneStoredShares, bindStoredShare, boundStoredShares, clearBoundStoredShares } from "./client/share-store.js"; export { handleShareTargetRequest, isShareTargetRequest, type ShareTargetError } from "./client/share-target-handler.js"; export { askUserFormPayload, askUserFormSpec, resolveAskUserFormLimits } from "./tool-contracts/form.js"; +export { frontmatterBlock, type FrontmatterBlock } from "@schlessera/brain-common/internal/frontmatter-block"; export { rewriteLinkDestinations, rewriteLinkDestinationsWithEdits, rebaseMessageBlocks, type LinkEdit } from "./markdown-links.js"; diff --git a/scripts/check-frontmatter-parse.ts b/scripts/check-frontmatter-parse.ts index a5b727264c..5ff903014c 100644 --- a/scripts/check-frontmatter-parse.ts +++ b/scripts/check-frontmatter-parse.ts @@ -27,6 +27,16 @@ // refused too. A `cache-probe` file is the exception: it is the test that // proves the helper ignores the cache, and must seed and read it. // +// 3. Where a frontmatter block starts and ends is answered by +// `frontmatterBlock` (`@schlessera/brain-common/internal/frontmatter-block`, +// #2507), the rule `parseFrontmatter` reads by. Package source may not +// detect a fence by hand: no regex anchored at the start of the text +// that opens with `---` (a BOM group before it included), no +// `startsWith("---…")` and no `indexOf`/`lastIndexOf("\n---…")`. Writers +// that emit or post-process a fence they produced are in FENCE_ALLOWED, +// each with its reason. A multiline (`m`) regex matches lines, not the +// start of a document, and is not a fence detector. +// // Detection is AST-based (the TypeScript compiler API), so comments and string // literals mentioning gray-matter do not trip it. @@ -61,6 +71,28 @@ export const ALLOWED: ReadonlyArray<{ pattern: RegExp; role: Role; reason: strin }, ]; +/** + * Package source that may spell a `---` fence by hand, and why. Everything + * else asks `frontmatterBlock`. + */ +export const FENCE_ALLOWED: ReadonlyArray<{ pattern: RegExp; reason: string }> = [ + { + pattern: /^packages\/common\/src\/frontmatter-block\.ts$/, + reason: "the shared fence rule itself", + }, + { + pattern: /^packages\/core\/src\/lib\/frontmatter\.ts$/, + reason: "stringifyDocument post-processes the LF-only block gray-matter's stringify just emitted", + }, + { + pattern: /^packages\/ui-server\/src\/brain\/policy-proposal\.ts$/, + reason: "pending: its review splitter still accepts a `...` closer; moving it onto frontmatterBlock is open work on #2507", + }, +]; + +/** Package source, where rule 3 applies. */ +const FENCE_SCOPE = /^packages\/[^/]+\/src\//; + const SCANNED = [ "packages/*/src/**/*.{ts,tsx,js,mjs,cjs}", "packages/*/tests/**/*.{ts,tsx,js,mjs,cjs}", @@ -74,7 +106,7 @@ export interface Finding { file: string; line: number; column: number; - rule: 1 | 2; + rule: 1 | 2 | 3; message: string; } @@ -109,7 +141,7 @@ export function scanSource(file: string, text: string): Finding[] { file.endsWith(".tsx") ? ts.ScriptKind.TSX : /\.[mc]?js$/.test(file) ? ts.ScriptKind.JS : ts.ScriptKind.TS); const allowed = ALLOWED.find((entry) => entry.pattern.test(file)); const findings: Finding[] = []; - const record = (node: ts.Node, rule: 1 | 2, message: string) => { + const record = (node: ts.Node, rule: 1 | 2 | 3, message: string) => { const { line, character } = source.getLineAndCharacterOfPosition(node.getStart(source)); findings.push({ file, line: line + 1, column: character + 1, rule, message }); }; @@ -137,6 +169,7 @@ export function scanSource(file: string, text: string): Finding[] { ts.forEachChild(node, visitLoads); }; visitLoads(source); + if (FENCE_SCOPE.test(file) && !FENCE_ALLOWED.some((entry) => entry.pattern.test(file))) scanFences(source, record); if (!allowed || ["cache-probe", "engine-probe"].includes(allowed.role) || bindings.size === 0) return findings; // Rule 2: every reference to the binding is a literal-options call or a type. @@ -182,6 +215,42 @@ export function scanSource(file: string, text: string): Finding[] { return findings; } +/** A regex source that anchors `---` at the start of the text, optionally after a BOM. */ +const FENCE_SOURCE = /^\^(?:\(\?:)?(?:\\uFEFF|\\ufeff|\uFEFF)?(?:\)\??|\?)?-{3}/; + +/** Rule 3: a frontmatter fence detected by hand instead of through `frontmatterBlock`. */ +function scanFences(source: ts.SourceFile, record: (node: ts.Node, rule: 3, message: string) => void): void { + const literal = (node: ts.Expression | undefined) => + node && ts.isStringLiteralLike(unwrap(node)) ? (unwrap(node) as ts.StringLiteralLike).text : undefined; + const refuse = (node: ts.Node, what: string) => + record(node, 3, `${what} detects a frontmatter fence by hand — use frontmatterBlock from ` + + "@schlessera/brain-common/internal/frontmatter-block, which reads the fences as parseFrontmatter does (#2507)"); + const visit = (node: ts.Node) => { + if (ts.isRegularExpressionLiteral(node)) { + const slash = node.text.lastIndexOf("/"); + const body = node.text.slice(1, slash), flags = node.text.slice(slash + 1); + if (!flags.includes("m") && FENCE_SOURCE.test(body)) refuse(node, "a regex anchored at a leading ---"); + } else if ((ts.isNewExpression(node) || ts.isCallExpression(node)) && ts.isIdentifier(node.expression) && + node.expression.text === "RegExp") { + const body = literal(node.arguments?.[0]); + const flags = literal(node.arguments?.[1]) ?? ""; + if (body !== undefined && !flags.includes("m") && FENCE_SOURCE.test(body)) refuse(node, "a RegExp anchored at a leading ---"); + } else if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression)) { + const method = node.expression.name.text; + const arg = literal(node.arguments[0]); + if (arg === undefined) { + // not a literal search string + } else if (method === "startsWith" && arg.startsWith("---")) { + refuse(node, `startsWith(${JSON.stringify(arg)})`); + } else if ((method === "indexOf" || method === "lastIndexOf") && /^\r?\n---/.test(arg)) { + refuse(node, `${method}(${JSON.stringify(arg)})`); + } + } + ts.forEachChild(node, visit); + }; + visit(source); +} + export function scanTree(root: string): Finding[] { const files = new Set(); for (const pattern of SCANNED) { @@ -200,16 +269,17 @@ if (import.meta.main) { const root = resolve(process.argv[2] ?? process.cwd()); const findings = scanTree(root); if (findings.length === 0) { - console.log("All frontmatter parsing goes through parseFrontmatter; gray-matter is loaded only by its designated files."); + console.log("All frontmatter parsing goes through parseFrontmatter; gray-matter is loaded only by its designated files; no package source finds a fence by hand."); process.exit(0); } - console.error("Frontmatter parsing that can reach gray-matter's global cache:"); + console.error("Frontmatter parsing that can reach gray-matter's global cache, or a fence found by hand:"); for (const f of findings) { console.error(` ${relative(root, resolve(root, f.file))}:${f.line}:${f.column}: [rule ${f.rule}] ${f.message}`); } console.error( `\n${findings.length} finding(s). Parse with parseFrontmatter ` + - "(@schlessera/brain-common/internal/frontmatter); see docs/decisions/frontmatter-parsing.md." + "(@schlessera/brain-common/internal/frontmatter) and find fences with frontmatterBlock " + + "(@schlessera/brain-common/internal/frontmatter-block); see docs/decisions/frontmatter-parsing.md." ); process.exit(1); } diff --git a/tests/frontmatter-parse-gate.test.ts b/tests/frontmatter-parse-gate.test.ts index c0f1293d26..086b3445df 100644 --- a/tests/frontmatter-parse-gate.test.ts +++ b/tests/frontmatter-parse-gate.test.ts @@ -8,7 +8,7 @@ import { describe, expect, test } from "bun:test"; import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "fs"; import { tmpdir } from "os"; import { dirname, join, resolve } from "path"; -import { scanSource, scanTree } from "../scripts/check-frontmatter-parse"; +import { FENCE_ALLOWED, scanSource, scanTree } from "../scripts/check-frontmatter-parse"; const ROOT = resolve(import.meta.dir, ".."); const OTHER = "packages/core/src/lib/indexer/parse.ts"; @@ -115,6 +115,74 @@ describe("rule 2: inside a designated file, only literal-options calls", () => { }); }); +describe("rule 3: fences are found by frontmatterBlock (#2507)", () => { + const CORE = "packages/core/src/lib/x.ts"; + + test("a hand-written fence detector in package source is refused", () => { + for (const code of [ + "const OPEN = /^---\\n/;", + "const OPEN = /^---[ \\t]*\\r?\\n/;", + "const FM = /^(?:\\uFEFF)?---[ \\t]*\\r?\\n/;", + "const FM = /^\\uFEFF?---/;", + 'const FM = new RegExp("^---\\\\r?\\\\n");', + 'if (raw.startsWith("---")) skip();', + "if (raw.startsWith(`---\\n`)) skip();", + 'const close = raw.indexOf("\\n---", 3);', + 'const close = raw.lastIndexOf("\\n---", end);', + 'const close = raw.indexOf("\\r\\n---");', + ]) { + for (const file of [CORE, "packages/ui-react/src/lib/a.tsx", "packages/ui-server/src/a.js"]) { + expect({ code, file, rules: rules(file, code) }).toEqual({ code, file, rules: [3] }); + } + } + }); + + test("lines, emitted fences, other dashes and non-source files are not detectors", () => { + for (const code of [ + "s.replace(/^---+$/gm, '');", // a horizontal rule, line by line + "const fence = `---\\n${yaml}\\n---\\n`;", // emitting a fence + 'if (line === "---") end();', + 'const cell = "---";', + 'if (raw.startsWith("--")) x();', + 'if (raw.startsWith(prefix)) x();', + "const re = /a^---/;", + '// raw.startsWith("---")', + ]) { + expect({ code, rules: rules(CORE, code) }).toEqual({ code, rules: [] }); + } + for (const file of ["packages/core/tests/a.test.ts", "scripts/a.ts", "tests/a.test.ts"]) { + expect(rules(file, "const OPEN = /^---\\n/;")).toEqual([]); + } + }); + + test("only the shared rule and the listed writers may spell a fence", () => { + const planted = "const OPEN = /^---\\n/;"; + expect(rules("packages/common/src/frontmatter-block.ts", planted)).toEqual([]); + expect(rules(SERIALIZER, planted)).toEqual([]); + for (const file of ["packages/common/src/other.ts", "packages/core/src/lib/frontmatter-block.ts", "packages/common/src/lib/frontmatter-block.ts"]) { + expect({ file, rules: rules(file, planted) }).toEqual({ file, rules: [3] }); + } + for (const entry of FENCE_ALLOWED) expect(entry.reason.length).toBeGreaterThan(20); + }); + + test("the tree passes, and the CLI fails on a planted detector", () => { + expect(scanTree(ROOT).filter((f) => f.rule === 3)).toEqual([]); + const root = mkdtempSync(join(tmpdir(), "frontmatter-gate-")); + try { + mkdirSync(join(root, "packages/core/src/lib"), { recursive: true }); + writeFileSync(join(root, "packages/core/src/lib/planted.ts"), 'export const x = 1;\nconst OPEN = /^---\\n/;\n'); + const child = Bun.spawnSync({ + cmd: [process.execPath, resolve(import.meta.dir, "../scripts/check-frontmatter-parse.ts"), root], + stdout: "pipe", stderr: "pipe", + }); + expect(child.exitCode).toBe(1); + expect(child.stderr.toString()).toContain("packages/core/src/lib/planted.ts:2:14: [rule 3]"); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); +}); + describe("the tree", () => { test("discovers violations across source roots and excludes generated and unrelated files", () => { const root = mkdtempSync(join(tmpdir(), "frontmatter-gate-")); From 3fce93b2918a4eb80027b9a852a2becad96d4c39 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 3 Nov 2026 16:18:59 +0100 Subject: [PATCH 4/4] CONTRACT: fix(core,ui-sdk,ui-server): give the strictest containment answer in every resolver row (#3422) (#3465) * 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 * 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 * CONTRACT: docs(contract): describe the CLI conversion of absolute in-brain path arguments (#3422) Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- .changeset/strict-containment-answers.md | 26 +++++ api-report/core.txt | 5 +- 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 +- .../paid-cli-provider-qualification.md | 2 +- docs/integration-contract.md | 21 ++++ docs/integration-contract/package-api.md | 42 +++++++ docs/modules.md | 2 +- docs/plans/module-renderers.md | 2 +- docs/plans/storage-accounting.md | 2 +- 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/module-settings.ts | 4 +- packages/core/src/lib/module-toggle.ts | 4 +- packages/core/src/lib/safe-path.ts | 88 +++++++++++++-- packages/core/src/module.ts | 2 +- .../core/tests/cli-path-arguments.test.ts | 87 +++++++++++++++ packages/core/tests/containment-rows.test.ts | 104 ++++++++++++++---- packages/core/tests/eval-cli.test.ts | 8 ++ packages/core/tests/safe-path.test.ts | 4 +- packages/module-diagrams/src/export-cli.ts | 8 +- packages/module-diagrams/tests/export.test.ts | 15 +++ packages/module-images/src/cli.ts | 5 +- packages/module-images/tests/scratch.test.ts | 14 +++ packages/module-travel/src/cli.ts | 4 +- packages/module-travel/src/route.ts | 13 ++- .../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 ++++++--- 47 files changed, 614 insertions(+), 168 deletions(-) create mode 100644 .changeset/strict-containment-answers.md create mode 100644 packages/core/tests/cli-path-arguments.test.ts diff --git a/.changeset/strict-containment-answers.md b/.changeset/strict-containment-answers.md new file mode 100644 index 0000000000..f969c5399b --- /dev/null +++ b/.changeset/strict-containment-answers.md @@ -0,0 +1,26 @@ +--- +"@schlessera/brain": minor +"@schlessera/brain-ui-sdk": patch +"@schlessera/brain-ui-server": patch +"@schlessera/brain-module-diagrams": patch +"@schlessera/brain-module-travel": patch +"@schlessera/brain-module-images": 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 still accepts an absolute path argument inside the brain. Before resolving one, it converts it to a brain-relative path with the new `brainRelativeArgument(root, arg)`, which `@schlessera/brain/module` also exports for module commands. This covers `--out`, document paths and the other CLI path flags. An absolute path outside the brain is still refused, and so is one that reaches the outside through a symlink inside the brain or has a `..` segment. + +Migration for module authors: pass paths relative to the brain root. A module command that takes a path argument from the user passes it through `brainRelativeArgument(ctx.root, arg)` first, as the first-party commands do. 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..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) @@ -1578,7 +1581,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 1c35d6245c..d7196c7de5 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:1637`). + (`FRESH_PROC_REFUSED`, `packages/ui-sdk/src/server/worker-launcher.ts:1646`). 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 23e8f86629..11b55f56d0 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 @@ -1029,7 +1029,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, @@ -2208,7 +2208,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:1912`): +(`export function restrictedReadPaths`, `packages/ui-sdk/src/server/worker-launcher.ts:1921`): - the Bun executable; - the backend entry's package, its `node_modules` chains and linked workspace @@ -2308,9 +2308,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 @@ -3479,11 +3479,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 @@ -3918,7 +3918,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 cec19f1f42..07392791dc 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 25f573a775..bfa8bb5ad4 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/hosting/paid-cli-provider-qualification.md b/docs/hosting/paid-cli-provider-qualification.md index 03457678c2..8278505999 100644 --- a/docs/hosting/paid-cli-provider-qualification.md +++ b/docs/hosting/paid-cli-provider-qualification.md @@ -56,7 +56,7 @@ SDK conversion without adding a public embedding-provider seam. The image CLI preserves `bytes`, `costIsEstimate`, `costUsd`, `model`, `note`, `output`, `outputs`, `provider`, `reason` and `renamed` -(`const payload`, `packages/module-images/src/cli.ts:407-419`). Its help example +(`const payload`, `packages/module-images/src/cli.ts:408-420`). Its help example is abbreviated; it is not the complete machine contract. Internal image raw usage does not imply that this envelope exposes it. diff --git a/docs/integration-contract.md b/docs/integration-contract.md index 6ab59be06a..28eda3a530 100644 --- a/docs/integration-contract.md +++ b/docs/integration-contract.md @@ -20,6 +20,27 @@ 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 is not affected for paths inside the brain. Before calling them, it +converts an absolute path argument inside the brain (`--out`, document paths +and the other CLI path flags) to a brain-relative path, through the additive +`brainRelativeArgument` export. An absolute argument outside the brain is still +refused, and so is one through a symlink that leaves it. The maintainer rulings +are recorded [on the issue](https://github.com/schlessera/brain-kit/issues/3422#issuecomment-6599244174) +and, for the CLI, [on the PR](https://github.com/schlessera/brain-kit/pull/3465#issuecomment-6602766385). 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. + ## Explicit local chat deletion (additive, #3230) An authenticated owner can delete its own chat's local history with diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index b3fc1c3de3..7f7731e1d1 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -437,6 +437,45 @@ 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 keeps accepting absolute path arguments inside the brain +([maintainer ruling](https://github.com/schlessera/brain-kit/pull/3465#issuecomment-6602766385)). +Before resolving one, it converts it with the new, additive +`brainRelativeArgument(root, arg): string`, also exported from +`@schlessera/brain/module` for module commands. An absolute argument lexically +under the root as given or under its realpath becomes repo-relative (`.` for +the root itself). Any other argument comes back unchanged, so `safeResolve` +still refuses an absolute path outside the brain and one with a `..` segment. +The converted path still goes through `safeResolve`, so an absolute path +through a symlink that leaves the brain is refused. The arguments it covers: + +- `brain read`, `archive` and `process` ``; +- `import --stamp`; +- `render` `` and `--out`; +- `eval --out`; +- `geo` track paths, `--compare`, `--along` and `map --out`; +- `okf export --out`; +- `image --out`, `--ref` and `--mask`; +- `diagram export|build` `` and `--out`; +- `travel photo --to`, and `travel route` `` and `--to`. + **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 @@ -1827,6 +1866,9 @@ unload a module or cancel running sessions. document paths are repo-relative (no absolute, `~`, `..`, or control characters) and resolved through a symlink-aware canonicalizer, so neither a symlinked directory nor a dangling symlink redirects a write out of the repo. + A CLI path argument may also be absolute: one inside the brain root is + converted to a repo-relative path first, and one outside it is refused + (0.45.0, #3422). - **Mutating commands require an initialized brain.** `add`, `import`, `index`, `archive`, `accept-mtime`, `process`, `maintain`, `sync`, `skills sync`, and `setup`, plus `okf export`, exit 1 when no `brain.config` is found rather than initializing a diff --git a/docs/modules.md b/docs/modules.md index b18b3e0437..30f4b37199 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)). A path argument from the command line goes through `brainRelativeArgument(root, arg)` first, which makes an absolute path inside the brain brain-relative | | 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 213e6d8076..dfac46edbf 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:303-339`), 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:31-40`). - F: session location (`piSessionDirectory`, `packages/ui-backend-pi/src/session-storage.ts:10-30`). - G: staging location (`shareStagingRoot`, `packages/ui-server/src/share/staging.ts:143-145`) 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 a6f8bf8f55..ead82fde31 100644 --- a/packages/core/src/cli/commands/import.ts +++ b/packages/core/src/cli/commands/import.ts @@ -5,7 +5,7 @@ import { Glob } from "bun"; import { frontmatterBlock } from "@schlessera/brain-common/internal/frontmatter-block"; 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"; @@ -35,7 +35,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/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..d316febefe 100644 --- a/packages/core/src/lib/safe-path.ts +++ b/packages/core/src/lib/safe-path.ts @@ -2,27 +2,93 @@ 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; +} + +/** + * 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. * @@ -33,8 +99,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/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 df986182a6..c36ffd9054 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 { 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 })); @@ -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,66 @@ 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(); + }); +}); + +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 6a8463ef89..de66f85069 100644 --- a/packages/core/tests/eval-cli.test.ts +++ b/packages/core/tests/eval-cli.test.ts @@ -278,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/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..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,12 +15,12 @@ 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}; } -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; @@ -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-diagrams/tests/export.test.ts b/packages/module-diagrams/tests/export.test.ts index 8c34f3c076..cd213f0efc 100644 --- a/packages/module-diagrams/tests/export.test.ts +++ b/packages/module-diagrams/tests/export.test.ts @@ -78,3 +78,18 @@ test("FIFO and directory leaves cannot block diagram source or derived inspectio writeFileSync(join(root,"brain.config.ts"),'import {defineConfig} from "@schlessera/brain";export default defineConfig({});\n');expect((await boundedAudit(root)).map((issue:{category:string})=>issue.category)).toEqual(["diagram-source"]); }finally{cleanup(root);} }); + +test("absolute CLI paths inside the brain are converted to brain-relative; outside, or through a link out, they are refused (#3422)",async()=>{ + const root=makeTempBrain({empty:true}),outside=makeTempBrain({empty:true}); + try{ + configure(root);writeFileSync(join(root,"release.diagram.yaml"),source);symlinkSync(outside,join(root,"escape"),"dir"); + const inside=await command(root,["diagram","export",join(root,"release.diagram.yaml"),"--out",join(root,"release.abs.svg"),"--json"]); + expect(inside.code,inside.stderr).toBe(0);expect(inside.value.input).toBe("release.diagram.yaml");expect(inside.value.output).toBe("release.abs.svg"); + expect(existsSync(join(root,"release.abs.svg"))).toBe(true); + for(const out of [join(outside,"result.svg"),join(root,"escape","result.svg")]){ + const refused=await command(root,["diagram","export","release.diagram.yaml","--out",out,"--json"]); + expect(refused.code).toBe(1);expect(refused.value.output).toBeNull();expect(refused.value.errors[0].message).toContain("must remain inside the brain"); + } + expect(existsSync(join(outside,"result.svg"))).toBe(false); + }finally{cleanup(root);cleanup(outside);} +}); 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 db46d6eec4..a0415247bd 100644 --- a/packages/module-images/tests/scratch.test.ts +++ b/packages/module-images/tests/scratch.test.ts @@ -216,6 +216,20 @@ describe("brain image --scratch", () => { 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 c1b1b47cc6..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"; @@ -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, @@ -159,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