From ecd7422f6b0cf3b80c9b275d8525af1ddb96c363 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Przemys=C5=82aw=20Galarowicz?= Date: Wed, 25 Nov 2026 17:31:07 +0100 Subject: [PATCH 1/4] fix(tar-extract): unpack only the manifest's listed paths, skip every other entry (CORE-386) pharn-oss v7.25.3-v7.25.5 commit seven symlinks under .claude/skills/, outside pharn-install.json, and the extractor refused any non-file entry anywhere in the archive, so every init/add/update/status failed on every channel. The extractor now selects, then judges: two streamed passes over the archive write only the files the CLI reads itself (CLONE_READ_FILES) and then, once the manifest has validated, only the paths it lists. Every other entry is skipped and never written, whatever its type or name. A listed path keeps every rule (regular file, strict UTF-8, no control/format char, no absolute/../\/:, one root, no duplicate) and a pax/GNU-modified entry at a listed path is refused; verifyUpstreamManifest still fails a listed file that is missing or altered. The tar is streamed through createGunzip, so the 128 MB cap now bounds bytes written; headers (200k) and decompressed bytes (1 GiB) bound the walk. extractPharnArchive takes a buffer, for a later local verify-archive mode. Docs (CLAUDE.md, architecture, contributing, SECURITY, THREAT-MODEL via the user's patch) and CHANGELOG [Unreleased] updated. Co-Authored-By: Claude Opus 5.5 --- .../GRILL.md | 38 + .../core-386-unpack-listed-paths-only/PLAN.md | 169 +++ .../REGRESSION.md | 19 + .../REVIEW.md | 33 + .../core-386-unpack-listed-paths-only/SHIP.md | 16 + .../VERIFY.md | 22 + .../regression-report.json | 44 + .../verify-report.json | 14 + CHANGELOG.md | 8 + CLAUDE.md | 11 +- SECURITY.md | 4 +- THREAT-MODEL.md | 83 +- docs/architecture.md | 11 +- docs/contributing.md | 20 +- src/lib/repo.ts | 113 +- src/lib/tar-extract.ts | 438 ++++--- src/lib/upstream-manifest.ts | 33 +- tests/commands/init.test.ts | 7 +- tests/project-lock.test.ts | 18 +- tests/repo.test.ts | 198 ++- tests/tar-extract.test.ts | 1101 +++++++++-------- tests/upstream-manifest.test.ts | 26 +- 22 files changed, 1647 insertions(+), 779 deletions(-) create mode 100644 .dev/features/core-386-unpack-listed-paths-only/GRILL.md create mode 100644 .dev/features/core-386-unpack-listed-paths-only/PLAN.md create mode 100644 .dev/features/core-386-unpack-listed-paths-only/REGRESSION.md create mode 100644 .dev/features/core-386-unpack-listed-paths-only/REVIEW.md create mode 100644 .dev/features/core-386-unpack-listed-paths-only/SHIP.md create mode 100644 .dev/features/core-386-unpack-listed-paths-only/VERIFY.md create mode 100644 .dev/features/core-386-unpack-listed-paths-only/regression-report.json create mode 100644 .dev/features/core-386-unpack-listed-paths-only/verify-report.json diff --git a/.dev/features/core-386-unpack-listed-paths-only/GRILL.md b/.dev/features/core-386-unpack-listed-paths-only/GRILL.md new file mode 100644 index 00000000..ee279029 --- /dev/null +++ b/.dev/features/core-386-unpack-listed-paths-only/GRILL.md @@ -0,0 +1,38 @@ +# GRILL — core-386-unpack-listed-paths-only + +Advisory (`/pharn-dev-grill` gates nothing). Spec hash: recomputed `bca940a5…3c4e`, equal to the plan's. + +```yaml +- type: FINDING + rule_id: P0 + severity: important + file: 'PLAN.md:Design step 2' + problem: 'Moving the layout-marker check from the tree to the manifest is only equivalent if nothing but listed files can create pharn/pharn-contracts.' + evidence: 'Pass 1 writes four root-level or .claude files only; pass 2 writes only listed paths. Say so in the code comment and keep the init test that pins the refusal.' +- type: FINDING + rule_id: P1 + severity: important + file: 'PLAN.md:Evals' + problem: 'Real gunzip chunks are 16 KiB, a multiple of 512, so a header never straddles a chunk in production and the carry path would go untested.' + evidence: 'Plan names odd-sized chunk tests via extractTar(readonly Buffer[]); make them byte-identical comparisons, and cover a payload split across chunks.' +- type: FINDING + rule_id: P2 + severity: minor + file: 'PLAN.md:Design (selection key)' + problem: 'The root segment of a selected entry is attacker bytes that reach a refusal message (second root, absolute).' + evidence: 'Keep assertDisplayablePath before any message that interpolates the full path, exactly as today.' +- type: FINDING + rule_id: P0 + severity: minor + file: 'PLAN.md:Caps' + problem: "A scanned-bytes cap is not in the ticket's list; justify it so it is not read as reintroducing the repo-size failure." + evidence: "1 GiB is 24x today's real archive (43 MB) and only bounds a compression bomb's CPU; name it in the CHANGELOG/SECURITY text." +- type: FINDING + rule_id: P7 + severity: minor + file: 'PLAN.md:Files (repo.ts)' + problem: 'extractPharnArchive is exported for a command that does not exist yet (CORE-387).' + evidence: 'Acceptable: the ticket asks for that shape; it is also what fetchAt calls, so it is not dead code.' +``` + +Verdict: proceed (advisory). All five folded into the build. diff --git a/.dev/features/core-386-unpack-listed-paths-only/PLAN.md b/.dev/features/core-386-unpack-listed-paths-only/PLAN.md new file mode 100644 index 00000000..89985deb --- /dev/null +++ b/.dev/features/core-386-unpack-listed-paths-only/PLAN.md @@ -0,0 +1,169 @@ +# PLAN — core-386-unpack-listed-paths-only (Linear CORE-386, epic CORE-380) + +- spec_content_hash: bca940a5ad247c120e6d8a3acba119d0d8df51dca275964d0e54c48d729d3c4e # fix #4 +- increment: the extractor writes ONLY the paths `pharn-install.json` lists plus the four files the CLI reads + itself; every other archive entry is skipped unwritten, whatever its type or name. Listed paths keep today's rules, + and `verifyUpstreamManifest`'s hash check still fails a listed file that is missing or altered. +- base: origin/main @ 51a96d29. Branch `feat/core-386-unpack-listed-paths-only`, built in the worktree + `/Users/pgalarowicz/Projects/pharn-cli-core-386`. +- layer(s): CLI source (`src/lib/tar-extract.ts`, `src/lib/repo.ts`, `src/lib/upstream-manifest.ts`), tests, docs + (`CLAUDE.md`, `docs/architecture.md`, `docs/contributing.md`, `SECURITY.md`, `CHANGELOG.md`), trusted doc + `THREAT-MODEL.md` (hook-protected → patch script for the human). +- constitution_refs: [P0, P1, P2, P4, P5, P7] + +## Why (live state, measured 2026-11-25) + +pharn-oss v7.25.5's codeload archive: 4,939 entries (4,149 files, 783 dirs, 7 symlinks under `.claude/skills/`), +43.0 MB decompressed, 11.5 MB compressed. Its manifest lists 616 files. Today's extractor applies its strict rules to +EVERY entry, so the 7 unlisted symlinks refuse every install on every channel. The CLI reads, beyond the manifest's +list, exactly: `pharn-install.json`, `SKILLS_VERSION` and `MIN_CLI` (both unlisted in v7.25.5), and +`.claude/settings.json` (listed `if-absent` in v7.25.5, but `hook-wiring` reads it whether or not it is listed). + +## Design + +Two passes over the in-memory `.tar.gz` (already capped at 32 MB by `fetchCapped`), each streamed through +`zlib.createGunzip()`, so the decompressed tar is never held whole (today `gunzipSync` holds it, which is why the +128 MB cap had to bound the whole repo). + +1. **Pass 1** writes only `CLONE_READ_FILES` = `pharn-install.json`, `SKILLS_VERSION`, `MIN_CLI`, + `.claude/settings.json` (each only if the archive has it). +2. The release check (`SKILLS_VERSION` = tag) runs, then `readUpstreamManifest(dir)` validates the manifest exactly + as today (the one parser). +3. **Pass 2** writes only the manifest's `files[].path` not already written by pass 1. +4. `verifyUpstreamManifest(dir, manifest)` as today. + +The extractor's walk, per header (every header, any type): checksum, `ustar` magic, octal `size`, the header cap, the +scanned-bytes cap, the end-of-archive marker and zero tail. These are framing: without them the walk cannot find the +next header, so they stay refusals for any entry. Nothing else is judged on an unselected entry. + +Selection key: the raw `prefix`/`name` bytes (latin1, lossless), with everything up to the first `/` stripped. Every +selected path is ASCII (manifest paths pass `MANIFEST_PATH_RE`; the four constants are ASCII), so an exact +membership test on the raw bytes is exact. A header whose key is selected gets TODAY's rules: strict UTF-8 decode, +the control/format-character refusal, regular file only (`0`/NUL), absolute / `..` / `\` / `:` / empty-or-`.` +segment refused, one root (shared by both passes), strip-1, `safeJoin`. A selected path appearing twice is refused. + +Pax `x` and GNU `L`/`K` (the headers that modify the NEXT entry's path/size): skipped, and the entry they modify is +skipped as unlisted. If that modified entry's ustar name is a selected path → refused ("pax data on a listed path"; +pharn does not honour pax records). If an `x`/`L`/`K`/`g` header's OWN name is a selected path → refused (not a +regular file). If the pax record renamed a listed file away from its ustar name, that file is missing and the hash +check fails. + +Caps (`repo.ts`): download 32 MB (unchanged), headers scanned 200,000 (any type, both passes), decompressed bytes +scanned 1 GiB (bounds a compression bomb's CPU now that memory is no longer the bound), bytes WRITTEN 128 MB +(checked at each selected header, before its payload is collected). Files written are bounded by the selection +(manifest ≤ 20,000 files + 4). + +API shaped for CORE-387 (`pharn verify-archive `): `extractTarGz(archive: Buffer, destDir, +{ select, limits, root? })` takes a buffer, never a URL; `repo.ts` exports `extractPharnArchive(archive, dir, +checkTree?)` (passes 1-2, manifest validation, hash check), which `fetchAt` calls after the download and a local-file +mode can call with no network. `TarExtractError` keeps its name and export; every refusal still names the entry path +and the rule. + +## Files + +- `src/lib/tar-extract.ts` — rewritten walker — layer CLI lib (fetch boundary): + - an incremental `TarWalker` (push chunks / finish) shared by `extractTar(tar: Buffer | readonly Buffer[], …)` + (sync, for tests and chunk-boundary tests) and `async extractTarGz(archive, …)` (streams `createGunzip`); + - `ExtractOptions { select: ReadonlySet; limits: TarLimits; root?: string }`, + `TarLimits { maxHeaders; maxScannedBytes; maxWrittenBytes }`, result `{ written: Set; bytes: number; +root: string | null }`; + - the selection, modifier (`x`/`L`/`K`) and duplicate rules above; `resolveEntryPath`, `readPathField`, + `assertDisplayablePath`, `readOctal`, `checksumOk`, `describeBytes`, `describeTypeflag` kept; + - module header rewritten: what is judged on every header (framing) vs only on a selected one, and why skipping is + strictly safer (nothing unselected touches disk). +- `src/lib/repo.ts` — `CLONE_READ_FILES`; `extractPharnArchive` (exported); `fetchAt` calls it; limits + `MAX_HEADERS`, `MAX_SCANNED_BYTES`, `MAX_WRITTEN_BYTES` replace `MAX_ENTRIES`/`MAX_EXTRACTED_BYTES`; the clone + invariant comment on `FetchedRepo` restated (files + dirs only, and only the listed + CLI-read files). +- `src/lib/upstream-manifest.ts` — `checkLayout`'s tree probe (`isPharnLayout(repoDir)`) also accepts the manifest's + own `files` listing a path under `pharn/pharn-contracts/` (amended at build: tree OR listing, so on-disk fixtures + that hold the marker dir keep passing), run after `checkFiles`, so the manifest can be fully + validated between the passes, before the tree holds anything it lists. Equivalent after extraction: the tree now + holds the marker iff a listed file is under it (and the hash check proves every listed file is there). + `MAX_MANIFEST_FILES` comment updated. Header comment: the tree holds only the listed files plus the CLI-read ones. +- `tests/tar-extract.test.ts` — rewritten to the new API. Kept (on a selected path): every framing refusal, every + path rule, UTF-8/format-character refusals, prefix reassembly, the base-256 cases, non-ASCII names. Inverted: + "rejects %s entry outright, rather than skipping it" becomes two blocks — OUTSIDE the selection (symlink, hard + link, char/block device, fifo, pax `x`, GNU `L`/`K`, unknown type, long pax-renamed name, `:` / `\` name, invalid + UTF-8, control characters, absolute, `..`, second root, no root) → extraction succeeds and writes nothing for that + entry; AT a selected path → refused. The comment records why the decision was narrowed (degit's silent skip lost + LISTED files; the manifest hash check now catches a missing or altered listed file). NEW: pax `x` before a selected + path → refused; pax `x` before an unselected path → both skipped; duplicate selected path → refused; header cap, + scanned-bytes cap, written-bytes cap; chunk boundaries (odd-sized chunks give identical output); the + only-files-and-dirs property over the result. +- `tests/repo.test.ts` — NEW: a tree whose archive carries an unlisted symlink, hard link, pax `x` + long-named + entry, and `:` name installs and none of them is written; the same entry AT a listed path refuses (symlink at a + listed path, pax `x` before a listed path) or fails the hash check (a pax-renamed listed file → "does not ship as a + file"); an unlisted file is not in the returned tree; `extractPharnArchive` over a local buffer (no fetch). +- `tests/upstream-manifest.test.ts` — the marker case (manifest lists nothing under `pharn/pharn-contracts`), if a + unit case exists; else covered by `tests/commands/init.test.ts`. +- `tests/project-lock.test.ts` — (added at build) the signal children's `signalHandled` helper holds the event loop + open with a ref'd timer until the handlers ran. The SIGINT-after-fetch child exited 13 (unsettled top-level await) + once `fetchRepo` became streamed: Node's signal handles are unref'd, and the base run had only passed because a + tsx IPC `ConnectWrap` happened to still be pending. Test harness only; no assertion changes. +- `tests/commands/init.test.ts` — the marker test's expected message → "lists no file under pharn/pharn-contracts". +- `CLAUDE.md` — "The clone is data" bullet: the extractor writes only the manifest's listed paths plus the CLI-read + files, as regular files and directories; every other entry is skipped unwritten. +- `docs/architecture.md` — step 3 (Source): the two passes and what the tree holds. +- `docs/contributing.md` — the fetch-boundary section and the "Security-sensitive files" bounds bullet (caps), the + `tar-extract.test.ts` row; the "symlinked sources" claim at line 147 is stale since CORE-173 and is fixed in passing. +- `SECURITY.md` — the "Archive parsing" paragraph (selected vs skipped, the new caps, pax rule) and line 61. +- `CHANGELOG.md` — `## [Unreleased]` `### Fixed` bullet (installs and updates no longer fail on a symlink, hard link, + pax header, long or `:` name, or repo size outside the listed paths) and `### Security` note (nothing unlisted is + written). No version bump. +- `THREAT-MODEL.md` — PROTECTED: `$SP/patches/CORE-386.py` for the human (§1 item 1 and 3, §2 "Extraction rejects + rather than skips" → "selects, then rejects", the caps sentence, the clone invariant, §3 table rows "oversized / + slow repo tarball" and "malformed / hostile archive entry", §4b caps line). NEEDS USER PATCH. + +Not touched: `src/commands/init.ts`, `src/commands/update.ts`, `src/lib/report-error.ts` (CORE-388's files); +`LIMITS.md` (its one extractor mention, "extracting it itself", stays true); `ARCHITECTURE.md`. + +## Contracts satisfied + +- `CLAUDE.md` invariants "The clone is data", "Containment", "Allowlists for untrusted names", "Network bounds", + "One unsafe-character set" — each kept on every written path; the new skip never writes. +- `CLAUDE.md` § Testing: update the test first (the new tar/repo cases are written before the code and run RED). + +## Evals to write (P1) — tests first; NEW ones must FAIL before the code change + +- unlisted symlink / hard link / pax `x` + entry / `:` name / long name → install OK, nothing written for it (FAILS + today: refused). +- symlink AT a listed path → refused; pax `x` before a listed path → refused; pax-renamed listed file → hash check + "does not ship as a file" (passes or fails today depending on the case; pinned). +- archive whose unlisted bytes exceed `maxWrittenBytes` → installs (FAILS today: decompressed cap). +- header cap / scanned-bytes cap / written-bytes cap refusals (new limits). +- duplicate selected path → refused (FAILS today: last wins). +- odd chunk boundaries → identical tree (new walker). +- e2e (manual, reported in the PR): built CLI `init` against real pharn-oss on the default `latest` channel + (v7.25.5, contains the symlinks) and on `--ref main`, plus `update`. + +## Guarantee audit (P0) + +- "No unselected entry is written" → floor: the only writes are `mkdirSync`/`writeFileSync` behind a `select.has(key)` + membership test; pinned by tests asserting the tree's exact contents. +- "A selected path is held to today's rules" → floor: the same functions as today on that branch; pinned by the + at-a-listed-path refusal tests. +- "A listed file that is missing or altered fails loudly" → floor: `verifyUpstreamManifest` (raw sha256), unchanged. +- "pax records are never honoured" → floor: no pax payload is read; a modified entry at a selected path is refused. +- "The tree holds only regular files and directories" → floor: unchanged (selected entries must be typeflag `0`/NUL). +- "Bounds" → floor: download cap (fetchCapped), header count, scanned bytes, written bytes — each a counter compare, + each tested. +- "Validating the layout marker on the manifest is equivalent to probing the tree" → advisory DERIVATION (stated in + the code): only listed files are written, and every one is proved present by the hash check. + +## Trust audit (P2) + +The archive and manifest stay untrusted. Strictly fewer bytes reach disk; unselected names are never decoded, so +they never reach a message. Selected names reach messages only after the control/format-character check, as today. + +## Determinism audit (P5) + +Every branch is a membership test: key ∈ select; typeflag ∈ {`0`, NUL} (accept), {`x`, `L`, `K`} (modifier), `g` +(skip); counters vs caps. No fallback guesses. + +## Open questions (HALT) + +- none. + +GATE 1 approved by lead (delegated by the user), 2026-11-25. Checked against the ticket: Scope bullets 1-6 → Design + +- Files; Done-when tests → Evals; e2e smoke → Evals (manual); no version bump; pharn-oss doc follow-up out of scope. diff --git a/.dev/features/core-386-unpack-listed-paths-only/REGRESSION.md b/.dev/features/core-386-unpack-listed-paths-only/REGRESSION.md new file mode 100644 index 00000000..eccf77db --- /dev/null +++ b/.dev/features/core-386-unpack-listed-paths-only/REGRESSION.md @@ -0,0 +1,19 @@ +# REGRESSION — core-386-unpack-listed-paths-only + +- Base: `51a96d2932` (origin/main, the branch's fork point), checked out in a detached worktree. +- Inside: the three source files, five test files, the docs (`CLAUDE.md`, `SECURITY.md`, `THREAT-MODEL.md`, + `docs/architecture.md`, `docs/contributing.md`), `CHANGELOG.md` and this feature's dev artifacts. None escapes the + plan's declared files (`check-regress.mjs scope`: `escaped` empty). +- Outside gates: the 53 stdlib `*.test.mjs`/`*.test.cjs` files (`node --test`), `node .dev/floor/validate.mjs .`, and + the full vitest suite (through heavy.sh, `--maxWorkers=2`; at HEAD with `--coverage`). + +| Gate | base | head | +| -------- | ---- | ---- | +| tests | 1 | 1 | +| validate | 0 | 0 | +| vitest | 0 | 0 | + +`regressions[]`: none. `pre_existing[]`: `tests` (red at base too: the gitignored `test-*/` fixtures, unrelated). + +REGRESSIONS: none, meaning no breakage outside the feature that these gates can detect (verdict `no-regressions`, +from `check-regress.mjs`). This certifies only the base→head comparison of these gates. diff --git a/.dev/features/core-386-unpack-listed-paths-only/REVIEW.md b/.dev/features/core-386-unpack-listed-paths-only/REVIEW.md new file mode 100644 index 00000000..ac670d9b --- /dev/null +++ b/.dev/features/core-386-unpack-listed-paths-only/REVIEW.md @@ -0,0 +1,33 @@ +# REVIEW — core-386-unpack-listed-paths-only + +Floor first: `node .dev/floor/validate.mjs .` GREEN. Everything below is advisory. + +```yaml +- type: FINDING + rule_id: P0 + severity: minor + file: 'src/lib/upstream-manifest.ts:checkLayoutMarker' + problem: 'The layout-marker check now passes when the manifest lists a file under pharn/pharn-contracts even if the tree lacks it.' + evidence: 'Safe because fetchRepo runs verifyUpstreamManifest before returning, and every later caller reads a fully extracted tree; pinned by the new upstream-manifest test (accepted by the parser, refused by the hash check).' +- type: FINDING + rule_id: P2 + severity: minor + file: 'src/lib/tar-extract.ts:TarWalker.push' + problem: "A selected file's payload is kept as subarrays of the gunzip output chunks until it is complete." + evidence: 'zlib allocates a fresh output buffer once one fills and never rewrites an emitted region; the e2e run verified 616 sha256s on the real archive, and the chunk-boundary tests compare byte-identical trees.' +- type: FINDING + rule_id: P7 + severity: minor + file: 'tests/project-lock.test.ts:SIGNAL_HANDLED' + problem: 'A test-harness change outside the extractor.' + evidence: "The SIGINT child relied on a pending tsx IPC handle to keep its loop alive; the streamed extraction removed that accident. A ref'd timer in the helper makes all signal children deterministic; no assertion changed." +- type: FINDING + rule_id: P3 + severity: minor + file: 'src/lib/repo.ts:extractPharnArchive' + problem: 'Exported ahead of its second caller (CORE-387 verify-archive).' + evidence: 'fetchAt uses it; the ticket asks for this shape. The clone-producer lint rule still confines mkdtemp to repo.ts.' +``` + +Verdict: 0 floor-gate findings, 4 advisory (minor). `TarExtractError` keeps its name and export; every refusal names +the entry path and the rule (CORE-388 compatibility). diff --git a/.dev/features/core-386-unpack-listed-paths-only/SHIP.md b/.dev/features/core-386-unpack-listed-paths-only/SHIP.md new file mode 100644 index 00000000..3e0b2e7f --- /dev/null +++ b/.dev/features/core-386-unpack-listed-paths-only/SHIP.md @@ -0,0 +1,16 @@ +# SHIP — core-386-unpack-listed-paths-only + +| Stage | Verdict (structural) | +| ------- | ------------------------------------------------------------------- | +| plan | GATE 1 approved by lead (delegated by the user) | +| grill | advisory: 5 concerns (0 blocking), folded into the build | +| build | floor GREEN (format:check, lint, lint:md, typecheck, vitest, build) | +| regress | `no-regressions` (regression-report.json; `tests` pre-existing red) | +| verify | `PASS` (verify-report.json) | +| review | 0 floor-gate findings, 4 advisory (minor) — see REVIEW.md | + +GATE 2 delegated to the lead: open the PR, drive CI green, do not merge. THREAT-MODEL.md was patched by the user with +the script this run wrote (`$SP/patches/CORE-386.py`, since deleted). + +Chain ran; the named floor verdicts are as shown — this is NOT a judgment that the increment is good or wise; that is +the human's call at the post-review gate. diff --git a/.dev/features/core-386-unpack-listed-paths-only/VERIFY.md b/.dev/features/core-386-unpack-listed-paths-only/VERIFY.md new file mode 100644 index 00000000..6903b93c --- /dev/null +++ b/.dev/features/core-386-unpack-listed-paths-only/VERIFY.md @@ -0,0 +1,22 @@ +# VERIFY — core-386-unpack-listed-paths-only + +| Gate | exit | +| ------------ | ---- | +| test | 0 | +| validate | 0 | +| lint | 0 | +| format:check | 0 | +| lint:md | 0 | +| typecheck | 0 | +| build | 0 | + +Verdict `PASS` (`check-verify.mjs`): 106 files, 3,662 tests, coverage 98.59 / 95.75 / 99.08 / 99.08 (floors +90/85/90/90). No verifier capabilities exist, so no advisory layer ran. + +End to end (manual, not a gate): the built `dist/index.js` ran `init --yes`, `status` and `update --yes` in throwaway +projects against the real pharn-oss archive on the default channel (release v7.25.5, commit `1755d6b8`) and on +`--ref main` (commit `a2cacaef`); both archives hold 7 symlinks under `.claude/skills/`. All exit 0, 592 files, "No +drift", "Up to date", no symlink in the project. The 0.21.5 build refuses the same archive with +`tar entry has an unsupported type '2': …/.claude/skills/pharn-ci-cover`. + +The named gates passed; this is not a claim that the feature is correct beyond what they check. diff --git a/.dev/features/core-386-unpack-listed-paths-only/regression-report.json b/.dev/features/core-386-unpack-listed-paths-only/regression-report.json new file mode 100644 index 00000000..1ff11c08 --- /dev/null +++ b/.dev/features/core-386-unpack-listed-paths-only/regression-report.json @@ -0,0 +1,44 @@ +{ + "base": "51a96d2932", + "inside": [ + ".dev/features/core-386-unpack-listed-paths-only/GRILL.md", + ".dev/features/core-386-unpack-listed-paths-only/PLAN.md", + ".dev/features/core-386-unpack-listed-paths-only/REGRESSION.md", + ".dev/features/core-386-unpack-listed-paths-only/REVIEW.md", + ".dev/features/core-386-unpack-listed-paths-only/SHIP.md", + ".dev/features/core-386-unpack-listed-paths-only/VERIFY.md", + ".dev/features/core-386-unpack-listed-paths-only/regression-report.json", + ".dev/features/core-386-unpack-listed-paths-only/verify-report.json", + "CHANGELOG.md", + "CLAUDE.md", + "SECURITY.md", + "THREAT-MODEL.md", + "docs/architecture.md", + "docs/contributing.md", + "src/lib/repo.ts", + "src/lib/tar-extract.ts", + "src/lib/upstream-manifest.ts", + "tests/commands/init.test.ts", + "tests/project-lock.test.ts", + "tests/repo.test.ts", + "tests/tar-extract.test.ts", + "tests/upstream-manifest.test.ts" + ], + "outside_gates": { + "tests": { + "base": 1, + "head": 1 + }, + "validate": { + "base": 0, + "head": 0 + }, + "vitest": { + "base": 0, + "head": 0 + } + }, + "regressions": [], + "pre_existing": ["tests"], + "verdict": "no-regressions" +} diff --git a/.dev/features/core-386-unpack-listed-paths-only/verify-report.json b/.dev/features/core-386-unpack-listed-paths-only/verify-report.json new file mode 100644 index 00000000..a610791f --- /dev/null +++ b/.dev/features/core-386-unpack-listed-paths-only/verify-report.json @@ -0,0 +1,14 @@ +{ + "feature": "core-386-unpack-listed-paths-only", + "gates": { + "build": 0, + "format:check": 0, + "lint": 0, + "lint:md": 0, + "test": 0, + "typecheck": 0, + "validate": 0 + }, + "verdict": "PASS", + "failing_gates": [] +} diff --git a/CHANGELOG.md b/CHANGELOG.md index 0a726c62..68d0681b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,14 @@ Releases 0.4.0 and older are in [CHANGELOG-ARCHIVE.md](CHANGELOG-ARCHIVE.md). ## [Unreleased] +### Fixed + +- **`pharn init`, `add`, `update` and `status` work again against pharn-oss v7.25.3 and later.** Those releases commit seven symlinks under `.claude/skills/`, and `pharn` refused any symlink anywhere in the downloaded archive, so every install and update failed on every channel. `pharn` now unpacks only the files pharn-oss's `pharn-install.json` lists, plus the four it reads itself (`pharn-install.json`, `SKILLS_VERSION`, `MIN_CLI`, `.claude/settings.json`); every other archive entry is skipped and never written. A symlink, hard link, pax header, long or `:` name elsewhere in pharn-oss, or pharn-oss growing past 20,000 entries or 128 MB, no longer stops an install. The archive is decompressed as a stream, so the 128 MB cap now applies to the bytes `pharn` writes, not to the whole repository. What is installed is unchanged. + +### Security + +- **Nothing outside pharn-oss's install list reaches your disk, even in the temporary download directory.** A listed file keeps every rule it had: it must be a regular file with a safe UTF-8 path (no `\`, `:` or `..`, one root), it may appear only once, and a symlink or any other entry type at a listed path is refused. A listed file preceded by a pax extended or GNU long-name header is refused, because `pharn` does not honour those records; a listed file such a header renamed is missing, and the sha256 check of every listed file still refuses the release. New bounds replace the entry and decompressed-size caps: 200,000 archive headers and 1 GiB of decompressed stream (a compression-bomb bound), beside the 32 MB download cap. + ## [0.21.5] — 2026-11-24 ### Changed diff --git a/CLAUDE.md b/CLAUDE.md index ed913417..f5c75475 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -80,10 +80,11 @@ PHARN_DEBUG=1 npm run dev -- init # full error output for fetch/install failur path that crosses a symlinked component, because `safeJoin` is lexical and copies/`rmSync` follow links. - **Hard-link-safe writes.** Writes replace the file (`lib/atomic-write.ts`: exclusive temp, then `rename`), one by one via `applyWrites`; a new `settings.json` uses `COPYFILE_EXCL`. A hard link's other name is never written through. -- **The clone is data.** `lib/tar-extract.ts` admits only regular files and directories, and `lib/repo.ts` is the only - producer of a clone. It requires the tree's `pharn-install.json` (a tree without one is refused) and verifies its raw - sha256s before returning the tree; every manifest `dest` must pass `isPharnOwnedPath`, never the manifest's own - `installRoots`. Nothing downloaded is ever executed: pharn-oss's `models` rules exist here as a pinned copy +- **The clone is data.** `lib/repo.ts` is the only producer of a clone. `lib/tar-extract.ts` writes only the paths + `pharn-install.json` lists plus `CLONE_READ_FILES`, each a regular file under today's path rules; every other archive + entry is skipped and never written, whatever its type. It requires the tree's `pharn-install.json` (a tree without + one is refused) and verifies its raw sha256s before returning the tree, so a listed file that is missing or altered + fails; every manifest `dest` must pass `isPharnOwnedPath`, never the manifest's own `installRoots`. Nothing downloaded is ever executed: pharn-oss's `models` rules exist here as a pinned copy (`lib/model-config.ts`), held to the vendored sha256-pinned checker by a differential test. - **Allowlists for untrusted names.** Untrusted names, versions, tags and manifest fields are checked against `CAPABILITY_NAME_RE`, `VERSION_RE`, `COPY_FILENAME_RE`, `COMMIT_RE`, `RELEASE_TAG_RE` and the role/applies enums. @@ -100,7 +101,7 @@ PHARN_DEBUG=1 npm run dev -- init # full error output for fetch/install failur - **Fail closed on release resolution.** `lib/release.ts` refuses (naming `--ref main`) when the latest release cannot be resolved or is malformed. It never floats to the tip of `main`. - **Network bounds.** `redirect: 'error'`, a per-request deadline and a body cap on every fetch. The tarball has its - own archive, extracted-size and entry caps. + own archive, headers-scanned, decompressed-bytes-scanned and bytes-written caps. - **The project lock.** `init`/`add`/`update`/`remove`/`uninstall` take `pharn/.lock` before reading the config, hold it across every prompt and plan once; edits made meanwhile are caught at write time (hash, fingerprint, walk). Dry runs and readers (`list`, `status`) never take it. diff --git a/SECURITY.md b/SECURITY.md index 826a2ad7..7c0cfc6a 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -54,11 +54,11 @@ Scope follows the surface described above: everything that touches remote input ### In scope - **Remote-input validation** bypasses in `src/lib/validate.ts` or `src/lib/upstream-manifest.ts` — the regex/enum allowlists active in the archetype flow (`CAPABILITY_NAME_RE`, `COPY_FILENAME_RE`, `VERSION_RE`, `COMMIT_RE`, `RELEASE_TAG_RE`, the `role`/`applies` enums via `assertRole`/`assertAppliesToken`), the `..` checks, control-character rejection (`assertSafeString`), or the network guards on the lightweight fetches. Every fetch goes through one bounded GET (`fetchCapped` in `src/lib/fetch-capped.ts`): `redirect: 'error'`, a hard deadline over the request **and** the body read (`withDeadline` in `src/lib/deadline.ts`, which settles at the deadline even if the body never ends), and a byte cap counted as the body streams. The lightweight fetches are sized at an 8 s deadline each: the release resolve in `src/lib/release.ts` (1 MiB for the release object, 1 KiB for the tag's commit), `fetchCommitSha` in `src/lib/repo.ts` (1 KiB) and `fetchRemoteSkillsVersion` in `src/lib/skills-version.ts` (256 KB). The repo download itself (`fetchRepo` in `src/lib/repo.ts`) carries the **same three guards, separately sized**: a 60 s deadline (`CLONE_TIMEOUT_MS`, sized to cover a streamed multi-megabyte body rather than a one-line response) and a body cap (`MAX_ARCHIVE_BYTES`, 32 MB), counted over the stream because codeload sends no `content-length`. Report ways around any of them (see `THREAT-MODEL.md §2` for the boundary, `§4b` for what it does and does not bound). -- **Archive parsing** in `src/lib/tar-extract.ts` — the hand-written ustar reader `pharn` uses instead of a tar dependency, and the highest-value target here, because it parses attacker-controlled header bytes. In scope: anything that gets an entry written outside the destination, gets a non-regular entry created, or gets past a bound. Its floor is the typeflag allowlist (ACCEPT regular files and directories; REJECT pax extended headers, symlinks, hard links, devices, FIFOs, GNU `L`/`K` long-name headers, and any unknown type), `prefix` + `name` reassembly **before** any path rule runs, rejection of absolute paths, `..` segments and any `\` or `:` in a name, a single-leading-component strip, a same-root check across every entry, `safeJoin` containment at each write, header-checksum verification, and octal-only numeric fields (a GNU base-256 field fails the octal test; only ASCII space is trimmed). That allowlist is what makes **the clone invariant** true — the tree `fetchRepo` returns holds only regular files and directories, in a private temp dir — and the clone-side readers rely on it rather than re-checking for links, so an entry type that slips past the allowlist is in scope. **`pax` records are never honoured: pharn reads only the ustar fields.** A per-file extended header (typeflag `x`) is refused on the **typeflag byte alone**, its payload never read — its records would override the ustar header that follows (`path=` replaces `prefix`+`name`, and a writer emits one exactly when the real path will not fit ustar, truncating it into the 100-byte `name` field where it would satisfy every containment rule above; `size=` replaces how many bytes the entry occupies). A **global** header (typeflag `g`) cannot be refused, because every codeload tarball opens with one; it is skipped, payload unread, and still counts toward the entry cap. Its defaults are never consulted, so the entries that follow land at their own ustar paths under every rule above, and the walk is framed by the ustar `size` alone. Reports that get a `pax` record honoured, or the `x` refusal suppressed, are in scope. Two bounds are passed in by `fetchRepo`: `MAX_ENTRIES` (20 000 entries, counted by the extractor) and `MAX_EXTRACTED_BYTES` (128 MB, `gunzipSync`'s `maxOutputLength` over the decompressed stream, which holds every byte an entry writes). That decompressed cap is what bounds a compression bomb, which neither a response header nor the archive's own size would. Extraction is deliberately **strict: every unexpected entry throws** rather than being silently skipped. +- **Archive parsing** in `src/lib/tar-extract.ts` — the hand-written ustar reader `pharn` uses instead of a tar dependency, and the highest-value target here, because it parses attacker-controlled header bytes. In scope: anything that gets an entry written outside the destination, gets a non-regular entry created, gets an entry written that pharn did not select, or gets past a bound. **It selects, then judges.** `src/lib/repo.ts` passes the paths to write: the ones `pharn-install.json` lists, plus the four files the CLI reads itself (`CLONE_READ_FILES`: the manifest, `SKILLS_VERSION`, `MIN_CLI`, `.claude/settings.json`), in two streamed passes (the CLI-read files, then — once the manifest has validated — the listed paths). Every other entry is skipped and **never written**, whatever its type or name: a symlink, hard link, device, pax header, long or `:` name elsewhere in pharn-oss no longer refuses the install, because nothing unselected touches disk. Every header is still framing-checked, because the walk cannot find the next one without it: header-checksum verification, the `ustar` magic, octal-only numeric fields (a GNU base-256 field fails the octal test; only ASCII space is trimmed), and an end-of-archive marker followed only by zeros. An entry at a selected path gets the full floor: a regular file only (typeflag `0`/NUL; a symlink, hard link, device, directory or any other type there is refused), strict UTF-8 with no control or format character, `prefix` + `name` reassembly **before** any path rule runs, rejection of absolute paths, `..` segments, empty or `.` segments and any `\` or `:`, a single-leading-component strip, a same-root check across every selected entry and both passes, a refusal when the path appears twice, and `safeJoin` containment at each write. That is what makes **the clone invariant** true — the tree `fetchRepo` returns holds only regular files and directories, and only the listed and CLI-read files, in a private temp dir — and the clone-side readers rely on it rather than re-checking for links. A listed file the archive does not ship as a regular file at its path is missing from the tree, and the manifest's raw sha256 check (`verifyUpstreamManifest`) refuses the tree. **`pax` records are never honoured: pharn reads only the ustar fields.** A per-file extended header (typeflag `x`, and GNU `L`/`K`) rewrites the next entry's path or size, so it is skipped together with the entry it modifies; when that entry's ustar name is a selected path, it is **refused**, and when the record renamed a listed file away from its ustar name, that file is missing and the sha256 check refuses. A **global** header (typeflag `g`; every codeload tarball opens with one) is skipped, payload unread; its defaults are never consulted, and the walk is framed by the ustar `size` alone. Reports that get a `pax` record honoured, or an unselected entry written, are in scope. Bounds, passed in by `fetchRepo`: `MAX_HEADERS` (200 000 headers of any type), `MAX_SCANNED_BYTES` (1 GiB of decompressed stream — the compression-bomb bound; the tar is streamed through `zlib.createGunzip`, never held whole) and `MAX_WRITTEN_BYTES` (128 MB, the sum of the selected files' sizes, checked at each header before its payload is read), on top of the 32 MB download cap. - **Path traversal** or unintended file-system writes from `src/lib/install-capabilities.ts` / `src/lib/install-manifest.ts` / `src/lib/diff.ts` / `src/commands/remove.ts` (copying resolved capability dirs and fixed product surfaces, `pharn.config.json` write) or from any capability / product-filename that escapes its intended target (`safeJoin` in `src/lib/validate.ts`, plus destination symlink walks in `install-capabilities.ts`). - **Server-side request forgery (SSRF)** or redirect abuse in the release, commit-metadata or `SKILLS_VERSION` fetches (the `fetch()` calls above use `redirect: 'error'`; report ways around it). - **Supply-chain** issues in how pharn-oss is fetched — the default verified-release resolve (`--ref latest`, the default of `pharn init` since 0.15.0; `src/lib/release.ts`: the latest release's tag, the tag's commit through the full tag ref, and the check that the fetched tree's `SKILLS_VERSION` equals the tag; it fails closed and never floats), the SHA-pinned `codeload.github.com` tarball download it feeds (`src/lib/repo.ts`), the opt-in `main` channel (`--ref main`, or an install that records no `ref`) with its one commit-SHA resolve **and its degraded mode** — when the SHA cannot be resolved the fetch floats `refs/heads/main` instead and records `commit` as absent (`LIMITS.md` §3b) — or the resolution of the repo coordinates (`src/lib/constants.ts`). Note the standing residual rather than re-reporting it: provenance is by-SHA, **not cryptographic** (`LIMITS.md §1b`), so a compromised upstream serving a valid-**shaped** tree at the resolved SHA passes every check above. -- **Untrusted-content injection** — a poisoned pharn-oss tree (a malicious `pharn-install.json` entry, symlink-planted paths, or unexpected directory entries) that leads the CLI to write outside the project or copy unintended content. +- **Untrusted-content injection** — a poisoned pharn-oss tree (a malicious `pharn-install.json` entry, a symlink or other non-file entry at a listed path, or unexpected directory entries) that leads the CLI to write outside the project or copy unintended content. - Logic in the archetype install pipeline (`src/commands/init.ts`, `src/steps/archetype-summary.ts`, `src/steps/overwrite-check.ts`, `src/steps/install-archetype.ts`, and the other commands) that could be abused to skip a consent prompt or overwrite files without confirmation. - **The forward-compatibility gate** in `src/lib/min-cli-gate.ts` and `readMinCli` (`src/lib/skills-version.ts`) — an optional `MIN_CLI` file read out of the **untrusted clone** and version-parsed to decide whether to refuse execution. It fails open by design (absent or malformed means "no constraint"); report ways to make a well-formed newer value fail to refuse, or a malformed one to crash rather than warn. - **Local-but-user-editable sidecar parsing** — `src/lib/pharn-config.ts` (every `capabilities[]` entry's `name` is validated against `CAPABILITY_NAME_RE` and its `role` against the role enum at ingest, because `pharn remove` path-joins that name into a recursive delete — which additionally accepts only a strict child of the role subtree via `safeChildJoin`), `src/lib/install-records.ts` (whose own header declares the store untrusted input: a defensive parser, a key-segment rule, and the invariant that a record key never drives a write; only orphan detection, a read, and `pharn uninstall`, a delete of a file still at its recorded hash, turn a key into a path, each behind `safeJoin`, a symlink walk and a regular-file check) and `src/lib/project-lock.ts` (which parses a JSON payload written by another process and feeds its `pid` to `process.kill`). Report ways to get a crafted store or lock file to write or delete outside the project, signal an unintended process, or get an overwrite or delete past the check that the file still has its recorded hash. diff --git a/THREAT-MODEL.md b/THREAT-MODEL.md index 503e2e8a..38eb93a9 100644 --- a/THREAT-MODEL.md +++ b/THREAT-MODEL.md @@ -47,13 +47,16 @@ surface: 1. **Malicious capability / product path** — a poisoned capability name, manifest `path`/`dest`, or product command/hook filename containing `..`, an absolute path, or control chars → a write **outside the intended subtree** (arbitrary file overwrite in the user's repo). Symlinks - planted in the archive are a variant — refused by the extractor's typeflag allowlist, so the - clone never holds one (the clone invariant, §2). The highest-value target. + planted in the archive are a variant — the extractor writes only the paths the install manifest + lists (plus the few files the CLI reads), each as a regular file, so the clone never holds one + (the clone invariant, §2): a symlink at a listed path is refused, one elsewhere is skipped + unwritten. The highest-value target. 2. **Malformed capability declarations** — broken `role`/`applies` values in `pharn-install.json`, or a capability `dir` in the wrong subtree, to crash the install or mis-drive selection into an unintended capability set. 3. **Oversized / slow response** — a huge clone or a hanging fetch → DoS the install. Every pharn fetch now carries a timeout and a body cap, the clone included: a streamed-byte cap on the - download and a second cap on the decompressed size (see the fetch boundary below). + download, and caps on the headers and decompressed bytes the extractor walks and on the bytes it + writes (see the fetch boundary below). 4. **Redirect to an attacker host** — a 3xx from any `fetch()` endpoint (`SKILLS_VERSION`, commit and release metadata, the tarball) to an off-repo sink. All of them pass `redirect: 'error'`. 5. **The copied methodology itself (Surface A)** — validated for **placement**, not for semantic @@ -95,40 +98,49 @@ a test. deadline even when the runtime never forwards the abort into a body that stops arriving. The clone's deadline is separately sized (60 s, not 8 s) because it must cover a ~2.5 MB streamed body rather than a one-line response. codeload sends **no - `content-length`**, so the cap is enforced by counting bytes as they stream, and a **second** cap - bounds the _decompressed_ size — a compression bomb is bounded by neither the header nor the - archive size. -- **Extraction rejects rather than skips.** This is the deliberate difference from what it replaces. - The bundled node-tar was called with **neither `strict` nor `onwarn`**, so a `TAR_ENTRY_INVALID` - (checksum / path / linkpath) was _recoverable_: the entry was silently dropped and extraction still - resolved successfully. `tar-extract.ts` throws on every one of those. It sorts each header into - three buckets: - - **ACCEPT** typeflag `0`/NUL (regular file) and `5` (directory) — the only content types the - archive holds. - - **SKIP** typeflag `g` (pax global header), advancing past the padded payload **unread**, with - **no** path rules applied; it still counts toward the entry cap. Every codeload tarball opens with - a `pax_global_header` whose single-segment name has no leading component to strip, so an - extractor that runs the path rules over it rejects every real archive on its first block. pharn - reads only the ustar fields, so a `g` default (`path`, `size`) is never honoured: the entries - after it land at their own ustar paths under every rule below. - - **REJECT** `x` (pax extended header — refused on the typeflag alone, payload unread, because its - records would override the next entry's path and size), `1`/`2` (hard/symlink), `3`/`4` - (devices), `6` (fifo), `7`, and any unknown byte. The archive contains none today, so a rejection - is a real signal rather than noise. + `content-length`**, so the cap is enforced by counting bytes as they stream, and the extractor + caps the _decompressed_ bytes it walks — a compression bomb is bounded by neither the header nor + the archive size. +- **Extraction selects, then rejects.** The bundled node-tar it replaces was called with **neither + `strict` nor `onwarn`**, so a `TAR_ENTRY_INVALID` (checksum / path / linkpath) was _recoverable_: + the entry was silently dropped and extraction still resolved — and a dropped entry could be a file + pharn installs. `tar-extract.ts` writes only the paths it is given: `fetchRepo` makes two streamed + passes, the first writing the files the CLI reads itself (`CLONE_READ_FILES`: `pharn-install.json`, + `SKILLS_VERSION`, `MIN_CLI`, `.claude/settings.json`), the second — once the manifest has + validated — the paths `pharn-install.json` lists. Each header falls in one of three cases: + - **EVERY header** is framing-checked (checksum, `ustar` magic, octal `size`, the header and + scanned-byte caps, an end-of-archive marker followed only by zeros), because the walk cannot + find the next header without it. + - **UNSELECTED** — every entry at a path pharn does not write, whatever its type or name (a + symlink, hard link, device, fifo, directory, pax header, long, `:` or invalid name): skipped, its + payload unread, **nothing written**. Skipping is strictly safer than judging, since nothing + unselected touches disk; refusing them made seven symlinks under pharn-oss's `.claude/skills/` + (v7.25.3–v7.25.5), outside the install list, break every install. The silent loss node-tar + allowed cannot recur: a listed file a skipped entry stood in for is missing from the tree, and + the manifest's raw sha256 check (`verifyUpstreamManifest`) refuses the tree loudly. + - **SELECTED** — an entry at a path pharn writes: it must be a regular file (typeflag `0`/NUL; + any other type there is refused), its path strict UTF-8 with no control or format character, + held to every path rule below, and present once. pharn reads only the ustar fields, never a pax + payload: a pax `x` (or GNU `L`/`K`) header, which rewrites the next entry's path and size, is + skipped together with that entry, and **refused** when that entry's ustar name is a selected + path. A `g` (global) header — every codeload tarball opens with one — modifies nothing and is + skipped; its defaults are never honoured. - **Paths are reassembled before they are judged.** The full path is `prefix + '/' + name` — ustar splits anything over 100 characters across those two header fields, and a large fraction of the live archive's entries use it. Reading `name` alone yields a bare leaf, which the strip-1 rule then rejects for having no leading component: a third of the tree silently lost, not merely misplaced. After reassembly: absolute paths, `..` segments and any `\` or `:` in a name are rejected (POSIX would write `a\..\..\evil` as one literal name; win32 would read it as a path), exactly one - leading component is stripped, every entry must share the **same** root component, and every write resolves through - `safeJoin` (`src/lib/validate.ts`). The entry count is capped by the extractor and the total - extracted bytes by gunzip's decompressed-size cap (the decompressed tar holds every byte an entry - writes). Header checksums are verified, and numeric fields are octal only, so the GNU base-256 - encoding is rejected rather than misparsed. + leading component is stripped, every selected entry must share the **same** root component, and every write resolves through + `safeJoin` (`src/lib/validate.ts`). The tar is decompressed as a stream (`zlib.createGunzip`), + never held whole; the extractor caps the headers it walks (200 000), the decompressed bytes it + walks (1 GiB, the compression-bomb bound) and the bytes it writes (128 MB, checked at each + selected header before its payload is read). Header checksums are verified, and numeric fields + are octal only, so the GNU base-256 encoding is rejected rather than misparsed. - **The clone invariant.** The tree `fetchRepo` returns contains only regular files and - directories, created by this process in a private `mkdtemp` dir (0700) that nothing else writes: - the typeflag allowlist above admits nothing else, the extractor's only writes are `mkdirSync` and + directories — only the listed and CLI-read files and the directories above them — created by this + process in a private `mkdtemp` dir (0700) that nothing else writes: a selected entry must be a + regular file, nothing unselected is written, the extractor's only writes are `mkdirSync` and `writeFileSync` through `safeJoin`, and a test pins that `src/lib/repo.ts` is the only producer of a clone. Clone-side readers rely on it and carry no symlink, FIFO or device checks of their own; they keep type checks where a directory (or a file where a directory belongs) can be produced. @@ -173,13 +185,13 @@ Every answer reduces to the floor (P0) or is labeled a limit (`LIMITS.md`). | Surface | Structural answer | Floor primitive (current file/function) | | --- | --- | --- | -| malicious capability / product path | `CAPABILITY_NAME_RE` / `COPY_FILENAME_RE` + `..`/unsafe-character rejection (`assertSafeString` in `src/lib/validate.ts`, through `hasUnsafeChars`; its messages escaped with `escapeUnsafe`, since the label quotes the name); `safeJoin` guards **every** read/write in `readUpstreamManifest`, `installCapabilityDirs`, `collectExpectedInstallPaths`, `diffInstalledCapabilities`, and `remove`; the clone holds no symlinks (the clone invariant, §2 — `extractTar`'s typeflag allowlist) and every destination path is walked for symlinked components before any write (`prepareInstall` in `src/lib/install-capabilities.ts`); pre-flight every capability source before any write (`installCapabilityDirs`) | regex + path containment + typeflag allowlist + destination symlink walk | +| malicious capability / product path | `CAPABILITY_NAME_RE` / `COPY_FILENAME_RE` + `..`/unsafe-character rejection (`assertSafeString` in `src/lib/validate.ts`, through `hasUnsafeChars`; its messages escaped with `escapeUnsafe`, since the label quotes the name); `safeJoin` guards **every** read/write in `readUpstreamManifest`, `installCapabilityDirs`, `collectExpectedInstallPaths`, `diffInstalledCapabilities`, and `remove`; the clone holds no symlinks (the clone invariant, §2 — `extractTar` writes only selected paths, each a regular file) and every destination path is walked for symlinked components before any write (`prepareInstall` in `src/lib/install-capabilities.ts`); pre-flight every capability source before any write (`installCapabilityDirs`) | regex + path containment + typeflag allowlist + destination symlink walk | | malformed capability declarations | `readUpstreamManifest` refuses the whole manifest, naming the entry, on a name outside `CAPABILITY_NAME_RE`, an unknown `role` (`assertRole`), a `dir` outside its role's subtree, a duplicate name or a capability with no files; an unknown `applies` token (`assertAppliesToken`) makes that one capability `unknown` in `manifestCapabilityIndex` — named, never installed, never a silent skip | enum + regex shape check | | oversized / slow `SKILLS_VERSION` fetch | 256 KB body cap + 8s timeout + `redirect: 'error'` | `fetchRemoteSkillsVersion` (`src/lib/skills-version.ts`) | | oversized / slow release or commit-SHA resolve | 8s deadline + `redirect: 'error'` + a 1 MiB cap on the release object and `MAX_SHA_BYTES` (1 KiB) on a commit id | `resolveSource` (`src/lib/release.ts`), `fetchCommitSha` (`src/lib/repo.ts`) | -| oversized / slow repo tarball | 60s timeout + a streamed-byte cap on the download + a separate cap on the **decompressed** size + `redirect: 'error'`; an entry-count cap in the extractor. A trip **throws** — there is no fallback transport to degrade to | `downloadArchive` (`src/lib/repo.ts`), `extractTarGz` (`src/lib/tar-extract.ts`) | +| oversized / slow repo tarball | 60s timeout + a streamed-byte cap on the download + `redirect: 'error'`; in the extractor, caps on the headers and **decompressed** bytes walked (streamed, never held whole) and on the bytes written. A trip **throws** — there is no fallback transport to degrade to | `downloadArchive` (`src/lib/repo.ts`), `extractTarGz` (`src/lib/tar-extract.ts`) | | redirect to attacker host | `redirect: 'error'` on every pharn `fetch()` call, the tarball included | `fetchCapped` (`src/lib/fetch-capped.ts`), the one GET behind `resolveSource`, `fetchRemoteSkillsVersion`, `fetchCommitSha` and `downloadArchive` | -| malformed / hostile archive entry | typeflag allowlist (files + dirs only; symlinks, hardlinks, devices and fifos **rejected**), `prefix`+`name` reassembly, `..`/absolute/`\`/`:` rejection, single-root check, `safeJoin` on every write, header-checksum verification | `extractTar` (`src/lib/tar-extract.ts`) | +| malformed / hostile archive entry | selection (only the manifest's listed paths and the CLI-read files are written; every other entry is **skipped unwritten**); at a selected path: regular file only (symlinks, hardlinks, devices, fifos and pax-modified entries **rejected**), `prefix`+`name` reassembly, `..`/absolute/`\`/`:` rejection, single-root check, no duplicate, `safeJoin` on every write; header-checksum verification on every header; the manifest's sha256 check catches a listed file that is missing or altered | `extractTar` (`src/lib/tar-extract.ts`) | | hostile / malformed `pharn-install.json` | data, never executed: one parser, a bounded (4 MiB) non-blocking read; `schemaVersion` exact-match (`1`, else refuse, naming the upgrade); every `path`/`dest` through a safe-segment regex + `safeJoin`; unique `dest`s; names, roles and versions against `CAPABILITY_NAME_RE` / `assertRole` / `VERSION_RE` (an unknown `applies` token makes that capability `unknown`, never installed); every `dest` inside the CLI-owned outer bound — below `pharn/` or `.claude//` inside a `pharn-*` entry or a fixed pharn root, `.claude/settings.json` only as copy-if-absent — never the manifest's own `installRoots`; each declared file's **raw** sha256 verified in `fetchRepo` before the tree is returned, so a mismatch refuses and nothing is written; `models.defaults` passes `checkModelsBlock` before any config write; `models.rules` drives nothing. Provenance only (§4a): whoever can change the tarball can change the manifest with it | `readUpstreamManifest` / `verifyUpstreamManifest` (`src/lib/upstream-manifest.ts`), `isPharnOwnedPath` (`src/lib/install-surfaces.ts`), `matchesRawSha256` (`src/lib/hash.ts`) | | poisoned tarball cache | **not applicable — pharn keeps no cache.** Every fetch downloads into a fresh temp dir | `fetchRepo` (`src/lib/repo.ts`) | | malformed / hostile upstream `models` block | bounded (1 MiB), non-blocking read; checked against pharn-oss's rules through the pinned copy; an unserializable block is refused; a failing block is **not written** and each reason is printed through `terminalSafe`; never executed | `readUpstreamModels` (`src/lib/upstream-models.ts`), `checkModelsBlock` (`src/lib/model-config.ts`) | @@ -236,8 +248,9 @@ not a "the source repo is ours" assumption (P0). `fetchRepo` now owns the whole download-and-extract path, so the residual is much smaller than it was — and what is left is worth stating precisely rather than implying it is closed: - **What is now floor, not delegation.** Timeout, streamed-byte cap, decompressed-size cap, - `redirect: 'error'`, typeflag allowlist, path reassembly + containment, single-root check, - entry/byte caps, header checksums. Each is pharn's own code with its own test, so a dependency + `redirect: 'error'`, selection of listed paths with a regular-file rule at each, path + reassembly + containment, single-root check, header/scanned-byte/written-byte caps, header + checksums. Each is pharn's own code with its own test, so a dependency bump cannot move any of them. The previous residual — "pharn bounds none of it" — is closed. - **What is closed by removal.** The shared cross-project tarball cache is gone, and with it both the poisoned-bytes surface (reuse keyed by **filename**, never a verified digest) and the worse diff --git a/docs/architecture.md b/docs/architecture.md index 4ddb5869..c00dbac1 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -71,7 +71,11 @@ directory gets its actionable error), under the lock, and before any network cal - Detection returns one piece of evidence per archetype (a dependency or the first triggering path). It is display-only, passed through `terminalSafe`. 3. **Source** (`lib/release.ts`, `lib/repo.ts`). `resolveSource` decides which commit, and `fetchRepo(source)` downloads - and extracts the codeload tarball into a temp dir that is removed in a `finally`. No command exits mid-run: a + the codeload tarball and extracts it into a temp dir that is removed in a `finally`. `extractPharnArchive` makes two + streamed passes over the archive: the first writes only the files the CLI reads itself (`CLONE_READ_FILES`: + `pharn-install.json`, `SKILLS_VERSION`, `MIN_CLI`, `.claude/settings.json`), the manifest is validated, and the + second writes only the paths the manifest lists. Every other entry (a symlink, a hard link, a pax header, a long or + `:` name anywhere else in pharn-oss) is skipped and never written. No command exits mid-run: a refusal, a failure or a cancel is thrown as a `CliError` (`lib/cli-error.ts`), so that `finally` (and the project lock's) runs first, and `runCli` in `src/index.ts` prints it once and sets `process.exitCode`. `fetchRepo` requires the tree's `pharn-install.json` (pharn-oss 7.21.0 and later), validates it and checks every declared file's raw @@ -144,7 +148,7 @@ is pharn-oss's [`docs/install-manifest.md`](https://github.com/pharn-dev/pharn-o - **Read and validate.** A bounded read (4 MiB, regular file, non-blocking), then a strict check: `schemaVersion` must be `1` (anything else refuses and says to upgrade pharn); `skillsVersion` must equal `SKILLS_VERSION`; the layout - must be the `pharn` layout this CLI knows; every capability `name`, `role` and `dir`, and every file `path`, `dest`, + must be the `pharn` layout this CLI knows, whose marker `pharn/pharn-contracts/` the tree holds or the manifest lists a file under; every capability `name`, `role` and `dir`, and every file `path`, `dest`, `sha256`, `policy` and `surface`, is held to an allowlist and to `safeJoin`; `dest`s are unique. Unknown keys are ignored (the schema is additive within version 1). - **The outer bound.** Every `dest` must lie inside `isPharnOwnedPath` (`lib/install-surfaces.ts`): below `pharn/` @@ -155,7 +159,8 @@ is pharn-oss's [`docs/install-manifest.md`](https://github.com/pharn-dev/pharn-o `uninstall` and `.prettierignore`) accepts the same paths, so a file installed into a surface this CLI does not name is updated, orphaned and uninstalled like any other, still gated by its record's hash. - **Verify.** `fetchRepo` checks each declared file's raw-byte sha256 (`matchesRawSha256` in `lib/hash.ts`; the - records' `contentHash` stays CRLF-folded) before it returns the tree. A mismatch refuses, and nothing is written. + records' `contentHash` stays CRLF-folded) before it returns the tree. A mismatch, or a listed file the archive does + not ship as a regular file at its path, refuses, and nothing is written. - **Use.** The install set (`collectExpectedInstallPaths`), `add`'s file list (`capabilityCloneFiles`), the capability index, the settings copy and the `models` defaults come from it. An `applies` token outside this CLI's enum makes that capability `unknown` (seen and named, never installed). `models.defaults` passes the same diff --git a/docs/contributing.md b/docs/contributing.md index ad691bef..39616774 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -144,10 +144,10 @@ See [Architecture](architecture.md) for the architecture in depth (the archetype `lib/validate.ts` and `lib/install-capabilities.ts` handle the untrusted remote input that reaches the filesystem (capability names, install paths). They are not the whole boundary: `lib/tar-extract.ts` parses attacker-controlled archive headers, `lib/upstream-manifest.ts` parses the untrusted `pharn-install.json`, `lib/unknown-capabilities.ts` strips control characters from upstream text before display, and `lib/install-records.ts` and `lib/project-lock.ts` parse local-but-user-editable sidecars. Preserve their invariants when editing: - Strict regex/enum allowlists (`CAPABILITY_NAME_RE`, `VERSION_RE`, `COPY_FILENAME_RE`, `COMMIT_RE`, the `role`/`applies` enums), `..` rejection, and control-char rejection. -- `safeJoin` (in `lib/validate.ts`) guards every read/copy so nothing escapes its base directory; `install-capabilities.ts` adds a symlink-aware backstop at the write sites and rejects symlinked sources. +- `safeJoin` (in `lib/validate.ts`) guards every read/copy so nothing escapes its base directory; `install-capabilities.ts` adds a symlink-aware backstop at the write sites. The clone itself holds no links: the extractor writes only the manifest's listed paths (plus the files the CLI reads) as regular files and skips every other entry. - Remote fetches (`lib/skills-version.ts`, `lib/release.ts`) use `redirect: 'error'`, an 8s timeout, and a body cap (256KB for `SKILLS_VERSION`, 1MiB for a release object). - A new install (`pharn init`) defaults to the newest verified pharn-oss release (`DEFAULT_INIT_REF`, `lib/release.ts`); `update`/`add`/`status` follow the channel the config records, and an absent `ref` means the tip of `main`. The release resolve fails closed: a release that cannot be resolved refuses the command and never falls back to the tip of `main`. -- The repo download (`lib/repo.ts`) has its own, larger bounds: a 60s timeout, a 32MB archive cap, a 128MB extracted cap, and a 20,000-entry cap — enforced twice, including at `gunzipSync`. +- The repo download (`lib/repo.ts`) has its own, larger bounds: a 60s timeout, a 32MB archive cap, and, over the streamed decompression, a 200,000-header cap, a 1 GiB decompressed-bytes cap (a compression-bomb bound, not a repo-size limit) and a 128MB cap on the bytes written. ### pharn-oss's `models` rules — a pinned copy @@ -184,16 +184,18 @@ properties of a dependency_, which a version bump could move without any pharn t If you change either file, the guarantees they carry are the ones `THREAT-MODEL.md` §2/§4b and `LIMITS.md` §3a state — timeout, streamed-byte cap, decompressed-size cap, `redirect: 'error'`, -typeflag allowlist, `prefix`+`name` path reassembly, `..`/absolute rejection, single-root check, -`safeJoin` on every write, entry/byte caps, header checksums. Each has a test in +selection (only listed paths are written; every other entry is skipped), the regular-file-only rule at a listed path, +`prefix`+`name` path reassembly, `..`/absolute/`\`/`:` rejection, single-root check, `safeJoin` on every write, +header/scanned-byte/written-byte caps, header checksums. Each has a test in `tests/tar-extract.test.ts` or `tests/repo.test.ts`; keep them in step with the prose. Two rules that are easy to get wrong: -- **Skip pax headers, do not judge them.** Every codeload tarball opens with a `pax_global_header` - (typeflag `g`) whose single-segment name has no leading component to strip. Running the path rules - over it fails the first block of every real archive — a bug no hand-made fixture would catch, which - is why `tests/tar-extract.test.ts` builds its fixtures with one. +- **Judge only what is written.** Every codeload tarball opens with a `pax_global_header` (typeflag `g`) + whose single-segment name has no leading component to strip, and pharn-oss holds symlinks and long names + outside the install list. Running the entry rules over an entry pharn does not write fails every real + archive — a bug no hand-made fixture would catch, which is why `tests/tar-extract.test.ts` builds its + fixtures with one and pins the skip for every entry type. - **Reassemble the path before judging it.** ustar splits anything over 100 characters across the `prefix` and `name` header fields. Reading `name` alone yields a bare leaf that strip-1 then rejects, losing a large fraction of the tree rather than misplacing it. @@ -227,7 +229,7 @@ Two rules that are easy to get wrong: | `model-config.test.ts` / `model-config-parity.test.ts` | pharn-oss's `models` rules as copied; the copy pinned to pharn-oss's own checker | | `models-update.test.ts` / `upstream-models.test.ts` | `update`'s rows for the `models` block; reading pharn-oss's block | | `confirm.test.ts` / `repo.test.ts` / `banner.test.ts` / `format.test.ts` | helpers; the codeload fetch boundary; banner; format | -| `tar-extract.test.ts` | The ustar reader: strip-1, pax skip, prefix reassembly, and every rejection | +| `tar-extract.test.ts` | The ustar reader: selection (unlisted entries skipped), strip-1, prefix reassembly, every rejection at a listed path | | `index.test.ts` | argv dispatch: the per-command option allowlist, the arity gate, and their exit codes | | `project-lock.test.ts` + `-break` / `commands/lock.test.ts` | The single-writer lock: acquire/release, stale-break single-winner, and which commands take it | | `min-cli-gate.test.ts` / `semver.test.ts` | The `MIN_CLI` forward-compat gate and its version comparison | diff --git a/src/lib/repo.ts b/src/lib/repo.ts index a7004d44..61f6f122 100644 --- a/src/lib/repo.ts +++ b/src/lib/repo.ts @@ -1,7 +1,13 @@ import { mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { REPO, REPO_BRANCH, SKILLS_VERSION_FILE } from './constants.js'; +import { + CLAUDE_SETTINGS_FILE, + MIN_CLI_FILE, + REPO, + REPO_BRANCH, + SKILLS_VERSION_FILE, +} from './constants.js'; import { onFatalSignal } from './fatal-signal.js'; import { fetchCapped } from './fetch-capped.js'; import type { CappedResponse, FetchCappedError } from './fetch-capped.js'; @@ -10,9 +16,11 @@ import type { InstallSource } from './release.js'; import { readSkillsVersion } from './skills-version.js'; import { extractTarGz } from './tar-extract.js'; import { + MANIFEST_FILE, readUpstreamManifest, verifyUpstreamManifest, } from './upstream-manifest.js'; +import type { UpstreamManifest } from './upstream-manifest.js'; import { assertSafeString, COMMIT_RE, @@ -25,12 +33,34 @@ const FETCH_TIMEOUT_MS = 8000; // The clone timeout has to cover a ~2.5 MB streamed body, not just the response // headers, so it is deliberately not the 8 s the two metadata fetches use. const CLONE_TIMEOUT_MS = 60_000; -// Caps on both sides of the gunzip: the compressed cap is counted as bytes -// stream (codeload sends no content-length); the decompressed cap bounds a zip -// bomb. +// The compressed cap is counted as bytes stream (codeload sends no +// content-length). The extractor streams the decompressed tar, so the repo's +// own size bounds nothing: headers walked and decompressed bytes walked bound a +// compression bomb's work (both far above pharn-oss v7.25.5's 4,939 entries and +// 43 MB), and the written-byte cap bounds what reaches disk. const MAX_ARCHIVE_BYTES = 32 * 1024 * 1024; -const MAX_EXTRACTED_BYTES = 128 * 1024 * 1024; -const MAX_ENTRIES = 20_000; +const MAX_HEADERS = 200_000; +const MAX_SCANNED_BYTES = 1024 * 1024 * 1024; +const MAX_WRITTEN_BYTES = 128 * 1024 * 1024; +const LIMITS = { + maxHeaders: MAX_HEADERS, + maxScannedBytes: MAX_SCANNED_BYTES, + maxWrittenBytes: MAX_WRITTEN_BYTES, +}; + +/** + * The tree files the CLI reads itself, written whether or not the manifest + * lists them: the manifest, `SKILLS_VERSION` (the release check, the manifest's + * `skillsVersion` check), the optional `MIN_CLI` handshake, and + * `.claude/settings.json` (hook-wiring reads it even when it is not listed). + * Nothing else unlisted is ever written. + */ +export const CLONE_READ_FILES: readonly string[] = [ + MANIFEST_FILE, + SKILLS_VERSION_FILE, + MIN_CLI_FILE, + CLAUDE_SETTINGS_FILE, +]; // --------------------------------------------------------------------------- // Temp-clone lifecycle backstop — a net under each caller's `finally`, never a @@ -72,10 +102,12 @@ function installCleanupHandlers(): void { export interface FetchedRepo { // THE CLONE INVARIANT: the tree holds only regular files and directories, - // created by this process in a private `mkdtemp` dir (tar-extract.ts's - // typeflag allowlist; this module is the only producer, enforced by the - // clone-producer rule in eslint.config.mjs). Clone-side readers skip symlink/FIFO - // checks but keep type checks. Every DESTINATION guard is separate and stays. + // created by this process in a private `mkdtemp` dir, and only the files the + // manifest lists plus CLONE_READ_FILES (tar-extract.ts selects, then admits a + // regular file only; this module is the only producer, enforced by the + // clone-producer rule in eslint.config.mjs). Clone-side readers skip + // symlink/FIFO checks but keep type checks. Every DESTINATION guard is + // separate and stays. dir: string; // The commit recorded as `commit`: the COMMIT_RE-validated SHA the tarball // was fetched at, or `null` when it could not be resolved and the fetch @@ -101,7 +133,8 @@ export interface FetchedRepo { * (`sha` null). Provenance is by-SHA, NOT cryptographic (LIMITS.md §1b). * * Network floor: `redirect: 'error'`, deadlines and body caps; path floor: - * lib/tar-extract.ts. No `git` binary, no tarball cache. + * lib/tar-extract.ts, through extractPharnArchive. No `git` binary, no tarball + * cache. */ export async function fetchRepo(source: InstallSource): Promise { if (source.kind === 'release') return fetchAt(source, source.sha); @@ -124,25 +157,18 @@ async function fetchAt( liveClones.add(dir); try { const archive = await downloadArchive(ref); - extractTarGz(archive, dir, { - maxEntries: MAX_ENTRIES, - maxTotalBytes: MAX_EXTRACTED_BYTES, - }); - // A release's tree must BE the version its tag names, or `update`'s - // version compare would lie. Refused inside this try, so the tree is removed. - if (source.kind === 'release') { - const found = readSkillsVersion(dir); + await extractPharnArchive(archive, dir, (tree) => { + // A release's tree must BE the version its tag names, or `update`'s + // version compare would lie. Refused inside this try, so the tree is + // removed. + if (source.kind !== 'release') return; + const found = readSkillsVersion(tree); if (found !== source.version) { throw new ManifestValidationError( `Release ${source.tag} (${source.sha}) ships ${SKILLS_VERSION_FILE} ${found}, not ${source.version}; refusing to install a release whose content does not match its tag.`, ); } - } - // The install manifest is required (a tree without one is older than - // pharn-oss 7.21.0 and refused), validated by the one parser, and every - // file it declares is held to its raw sha256 HERE, before the tree is - // returned: no command can read a tree that fails. - verifyUpstreamManifest(dir, readUpstreamManifest(dir)); + }); } catch (err) { // Extraction is not transactional, so a partially-written tree must never // be returned. Callers treat a fetchRepo throw as fatal. @@ -163,6 +189,43 @@ async function fetchAt( }; } +/** + * Unpack a pharn-oss `.tar.gz` into `dir` (an empty directory this module + * created) and return its validated manifest. Two passes over the same bytes: + * + * 1. write only CLONE_READ_FILES; run `checkTree` (the release check); + * validate pharn-install.json through the one parser (a tree without one + * is older than pharn-oss 7.21.0 and refused); + * 2. write only the paths the manifest lists, then hold every listed file to + * its raw sha256, so a listed file that is missing (a pax record renamed + * it) or altered refuses the tree before any command can read it. + * + * Every other archive entry is skipped unwritten. Takes the archive's bytes, + * never a URL, so a local file can be checked with no network. Throws on any + * refusal; extraction is not transactional, so the caller removes `dir`. + */ +export async function extractPharnArchive( + archive: Buffer, + dir: string, + checkTree?: (dir: string) => void, +): Promise { + const first = await extractTarGz(archive, dir, { + select: new Set(CLONE_READ_FILES), + limits: LIMITS, + }); + checkTree?.(dir); + const manifest = readUpstreamManifest(dir); + await extractTarGz(archive, dir, { + select: new Set( + manifest.files.map((f) => f.path).filter((p) => !first.written.has(p)), + ), + limits: { ...LIMITS, maxWrittenBytes: MAX_WRITTEN_BYTES - first.bytes }, + root: first.root, + }); + verifyUpstreamManifest(dir, manifest); + return manifest; +} + /** * Download the repo tarball at `ref` into memory, bounded on both time and * size (`fetchCapped`; the decompressed size is bounded by the extract). diff --git a/src/lib/tar-extract.ts b/src/lib/tar-extract.ts index c7ce8662..386dda88 100644 --- a/src/lib/tar-extract.ts +++ b/src/lib/tar-extract.ts @@ -1,4 +1,4 @@ -import { gunzipSync } from 'node:zlib'; +import { createGunzip } from 'node:zlib'; import { mkdirSync, writeFileSync } from 'node:fs'; import { dirname } from 'node:path'; import { escapeUnsafe, hasUnsafeChars } from './terminal-safe.js'; @@ -8,32 +8,45 @@ import { safeJoin } from './validate.js'; * The tar half of pharn's fetch boundary — a minimal, strict ustar reader for * the ONE archive shape pharn consumes: GitHub's `codeload.../tar.gz/`. * In-repo rather than a dependency because these guarantees ARE the fetch - * boundary, unit-tested against hand-built adversarial archives; every - * unexpected entry is a THROW, never a silent drop. + * boundary, unit-tested against hand-built adversarial archives. * - * WHAT THE TREE CAN HOLD (the invariant `fetchRepo` states, lib/repo.ts): only - * regular files and directories, under `destDir` — the only writes are - * `mkdirSync` and `writeFileSync`, each through `safeJoin`. Clone-side readers - * rely on this instead of re-checking for links. + * SELECT, THEN JUDGE. The caller names the root-relative paths to write + * (`select`: the paths pharn-install.json lists, plus the few files the CLI + * reads itself, lib/repo.ts). Every other entry is skipped and never written, + * whatever its type or name: nothing unselected touches disk, so skipping is + * strictly safer than judging. A symlink, hard link, device, pax header, long + * or `:` name anywhere else in the repo no longer refuses the install. + * + * EVERY header is framing-checked, because the walk cannot find the next one + * without it: checksum, `ustar` magic, an octal `size`, the header and + * scanned-byte caps, and the end-of-archive marker with a zero tail. + * A SELECTED header gets the full rules: strict UTF-8, no control or format + * character, a regular file (typeflag '0' / NUL) only, its path rebuilt from + * `prefix` + `name`, refused when absolute or holding `..`, `\`, `:` or an + * empty or `.` segment, one root shared by every selected entry, one leading + * component stripped, `safeJoin`-contained, written once, within the + * written-byte cap. Contents are written verbatim, never executed. * - * ACCEPT typeflag '0' / NUL (regular file) and '5' (directory). - * SKIP typeflag 'g' (pax global header), payload UNREAD — every codeload - * tarball opens with one. It still counts toward `maxEntries`. - * REJECT everything else: 'x' (pax extended header), '1'/'2' (hard/symlink), - * '3'/'4' (devices), '6' (fifo), '7', GNU 'L'/'K', any unknown byte. + * WHAT THE TREE CAN HOLD (the invariant `fetchRepo` states, lib/repo.ts): only + * regular files and the directories above them, under `destDir`, at selected + * paths — the only writes are `mkdirSync` and `writeFileSync`, each through + * `safeJoin`. Clone-side readers rely on this instead of re-checking for links. * * PAX IS NEVER HONOURED: only the ustar `name`, `prefix`, `size` and - * `typeflag` are read. A pax record would be a second untrusted path/size - * source, and a writer emits 'x' exactly when the real path does not fit ustar - * (truncating it into `name`, where it would pass every rule), so 'x' is - * refused on its typeflag. Ignoring 'g' is safe: its defaults are never - * consulted, and the walk is framed by the ustar `size` alone (a disagreeing - * stream fails the next header's checksum or magic). Cost: a `g` meaning "put - * everything at X" is extracted at its ustar paths, contained. + * `typeflag` are read, never a pax payload. A pax 'x' header (and GNU 'L'/'K') + * rewrites the NEXT entry's path or size, so it is skipped together with the + * entry it modifies, as unselected. When that entry's ustar name is a selected + * path, it is refused: pharn will not install a listed file whose real path or + * size it ignores. When the pax record renamed a listed file away from its + * ustar name, that file is simply missing, and the manifest's sha256 check + * (`verifyUpstreamManifest`) refuses the tree. A 'g' (global) header — every + * codeload tarball opens with one — is skipped and modifies nothing: its + * defaults are never consulted, and the walk is framed by the ustar `size` + * alone (a disagreeing stream fails the next header's checksum or magic). * - * Every accepted path is rebuilt from `prefix` + `name`, refused when absolute - * or holding `..`, `\` or `:`, stripped of one leading component, and resolved - * through `safeJoin`. Contents are written verbatim, never executed. + * The decompressed tar is streamed, never held whole, so a repo larger than the + * written-byte cap still installs; the scanned-byte cap only bounds the work a + * compression bomb can cause. */ /** A ustar header block is exactly 512 bytes; payloads are padded to that. */ const BLOCK = 512; @@ -50,15 +63,33 @@ const OFF_MAGIC = 257; const OFF_PREFIX = 345; const LEN_PREFIX = 155; +/** Headers that rewrite the NEXT entry's path, size or link name. */ +const MODIFIERS = new Set(['x', 'L', 'K']); + export interface TarLimits { - /** Maximum number of ACCEPTed entries. */ - maxEntries: number; - /** - * The largest DECOMPRESSED tar `extractTarGz` accepts (gunzip's - * `maxOutputLength`). The tar holds every byte an entry writes, so this is - * also the bound on bytes written; `extractTar` itself does not re-count. - */ - maxTotalBytes: number; + /** Headers walked, of any type, selected or not. */ + maxHeaders: number; + /** Decompressed bytes walked: bounds a compression bomb's work, not the repo. */ + maxScannedBytes: number; + /** Bytes written: the sum of the selected files' sizes. */ + maxWrittenBytes: number; +} + +export interface ExtractOptions { + /** Root-relative paths to write; every other entry is skipped unwritten. */ + select: ReadonlySet; + limits: TarLimits; + /** The archive's root component, when an earlier pass already learned it. */ + root?: string | null; +} + +export interface ExtractResult { + /** The root-relative paths written. */ + written: ReadonlySet; + /** Their total size in bytes. */ + bytes: number; + /** The root component every selected entry shared (`null`: none selected). */ + root: string | null; } /** Every refusal this module makes, so callers can tell it from an fs error. */ @@ -114,6 +145,21 @@ function readPathField(block: Buffer, offset: number, length: number): string { } } +/** + * The selection key of a header: its raw `prefix`/`name` bytes (latin1, so + * byte for byte) with everything up to the first `/` — the archive root — + * stripped; `null` when there is no `/`. Every selected path is ASCII, so an + * exact membership test on these bytes is exact, and an unselected name is + * never decoded, judged or printed. + */ +function selectionKey(block: Buffer): string | null { + const name = readString(block, OFF_NAME, LEN_NAME); + const prefix = readString(block, OFF_PREFIX, LEN_PREFIX); + const raw = prefix === '' ? name : `${prefix}/${name}`; + const slash = raw.indexOf('/'); + return slash === -1 ? null : raw.slice(slash + 1); +} + /** * A ustar numeric field: octal digits, space- or NUL-terminated. GNU base-256 * (high bit on the first byte) fails the octal test. Only ASCII space is @@ -161,17 +207,6 @@ function describeTypeflag(typeflag: string): string { : `'${typeflag}'`; } -/** Refuse any non-zero byte from `from` to the end (after the end marker). */ -function assertZeroTail(tar: Buffer, from: number): void { - for (let i = from; i < tar.length; i += 1) { - if (tar[i] !== 0) { - throw new TarExtractError( - 'tar archive has data after its end-of-archive marker.', - ); - } - } -} - /** True when the block is 512 NUL bytes — the end-of-archive marker. */ function isZeroBlock(block: Buffer): boolean { for (const byte of block) if (byte !== 0) return false; @@ -197,8 +232,8 @@ function checksumOk(block: Buffer): boolean { } /** - * Apply the path rules to an ACCEPTed entry and return its destination-relative - * path, or `null` for the archive's own root directory. + * Apply the path rules to a selected file entry and return its + * destination-relative path and root component. * * The full path is reconstructed from `prefix` + `name` BEFORE any rule runs: * ustar splits a path over 100 characters across the two, and `name` alone @@ -206,32 +241,26 @@ function checksumOk(block: Buffer): boolean { */ function resolveEntryPath( fullPath: string, - isDirectory: boolean, expectedRoot: string | null, -): { rel: string | null; root: string } { - if (fullPath === '') { - throw new TarExtractError('tar entry has an empty path.'); - } +): { rel: string; root: string } { if (fullPath.startsWith('/')) { throw new TarExtractError(`tar entry has an absolute path: ${fullPath}`); } // POSIX writes `a\..\..\evil` as ONE literal name; win32 reads the same - // bytes as a path (and `C:` as a drive). pharn-oss ships neither character. + // bytes as a path (and `C:` as a drive). pharn-oss lists neither character. if (/[\\:]/.test(fullPath)) { throw new TarExtractError( `tar entry path contains a backslash or colon, which pharn does not accept: ${fullPath}`, ); } - const segments = fullPath.replace(/\/+$/, '').split('/'); - for (const segment of segments) { - if (segment === '..') { - throw new TarExtractError( - `tar entry escapes the archive root: ${fullPath}`, - ); - } + const segments = fullPath.split('/'); + if (segments.includes('..')) { + throw new TarExtractError( + `tar entry escapes the archive root: ${fullPath}`, + ); } const root = segments[0]!; - if (root === '' || root === '.') { + if (root === '.') { throw new TarExtractError( `tar entry has no leading component: ${fullPath}`, ); @@ -251,132 +280,245 @@ function resolveEntryPath( `tar entry has an empty or "." path segment: ${fullPath}`, ); } - if (rest.length === 0) { - // The root directory entry itself: nothing to write, not a failure. - if (isDirectory) return { rel: null, root }; - throw new TarExtractError( - `tar entry has no path below the archive root: ${fullPath}`, - ); - } return { rel: rest.join('/'), root }; } +/** The selected file whose payload is being collected. */ +interface Pending { + target: string; + chunks: Buffer[]; +} + /** - * Extract a gzipped tar into `destDir`, stripping the single leading path - * component. Throws `TarExtractError` on any refusal — a caller that sees one - * must treat the destination as unusable and remove it, since extraction is not - * transactional. + * The walk itself, incremental so the decompressed tar can be streamed: `push` + * takes chunks of any size (a header or payload may straddle two), `finish` + * refuses an archive that ended early. A selected file is written only once + * its whole payload has arrived, so a truncated archive writes no partial file. */ -export function extractTarGz( - archive: Buffer, - destDir: string, - limits: TarLimits, -): void { - let tar: Buffer; - try { - tar = gunzipSync(archive, { maxOutputLength: limits.maxTotalBytes }); - } catch (err) { - throw new TarExtractError( - `could not decompress the fetched archive: ${(err as Error).message}`, - ); +class TarWalker { + private readonly written = new Set(); + private bytes = 0; + private headers = 0; + private scanned = 0; + private root: string | null; + // Header bytes received so far (a header can straddle two chunks). + private carry: Buffer[] = []; + private carryLength = 0; + // Payload and padding bytes of the current entry still to come. + private dataLeft = 0; + private padLeft = 0; + private pending: Pending | null = null; + // The previous header was a modifier ('x', 'L', 'K'), so this one's ustar + // path and size may not be the real ones. + private modified = false; + private ended = false; + + constructor( + private readonly destDir: string, + private readonly options: ExtractOptions, + ) { + this.root = options.root ?? null; } - extractTar(tar, destDir, limits); -} -/** The uncompressed half, split out so tests can build tar bytes directly. */ -export function extractTar( - tar: Buffer, - destDir: string, - limits: TarLimits, -): void { - let offset = 0; - let entries = 0; - let expectedRoot: string | null = null; + push(chunk: Buffer): void { + this.scanned += chunk.length; + if (this.scanned > this.options.limits.maxScannedBytes) { + throw new TarExtractError( + `tar archive decompresses to more than ${this.options.limits.maxScannedBytes} bytes.`, + ); + } + let at = 0; + while (at < chunk.length) { + if (this.ended) { + // After the end-of-archive marker everything must be zero padding, so + // a zero block cannot end the walk early and drop the rest in silence. + if (!isZeroBlock(chunk.subarray(at))) { + throw new TarExtractError( + 'tar archive has data after its end-of-archive marker.', + ); + } + return; + } + if (this.dataLeft > 0) { + const n = Math.min(this.dataLeft, chunk.length - at); + this.pending?.chunks.push(chunk.subarray(at, at + n)); + this.dataLeft -= n; + at += n; + if (this.dataLeft === 0) this.writePending(); + continue; + } + if (this.padLeft > 0) { + const n = Math.min(this.padLeft, chunk.length - at); + this.padLeft -= n; + at += n; + continue; + } + const n = Math.min(BLOCK - this.carryLength, chunk.length - at); + this.carry.push(chunk.subarray(at, at + n)); + this.carryLength += n; + at += n; + if (this.carryLength === BLOCK) { + const block = + this.carry.length === 1 ? this.carry[0]! : Buffer.concat(this.carry); + this.carry = []; + this.carryLength = 0; + this.header(block); + } + } + } + + finish(): ExtractResult { + if (this.dataLeft > 0) { + throw new TarExtractError( + 'tar entry runs past the end of the archive — truncated.', + ); + } + // The walk ran out of bytes without meeting a zero block: the archive was + // cut short (every real tar ends with at least one). + if (!this.ended) { + throw new TarExtractError( + 'tar archive has no end-of-archive marker — truncated.', + ); + } + return { written: this.written, bytes: this.bytes, root: this.root }; + } - while (offset + BLOCK <= tar.length) { - const header = tar.subarray(offset, offset + BLOCK); - // The end-of-archive marker; everything after it must be zero padding, so - // a zero block cannot end the walk early and drop the rest in silence. - if (isZeroBlock(header)) { - assertZeroTail(tar, offset + BLOCK); + private header(block: Buffer): void { + if (isZeroBlock(block)) { + this.ended = true; return; } - if (!checksumOk(header)) { + if (!checksumOk(block)) { throw new TarExtractError( 'tar header failed its checksum — the archive is corrupt or truncated.', ); } // Every header git archive writes is ustar (`ustar\0`); old GNU writes // `ustar ` — the 5-byte prefix admits both and nothing else. - if (header.toString('latin1', OFF_MAGIC, OFF_MAGIC + 5) !== 'ustar') { + if (block.toString('latin1', OFF_MAGIC, OFF_MAGIC + 5) !== 'ustar') { throw new TarExtractError( 'tar header is not a ustar header (missing "ustar" magic).', ); } - - const size = readOctal(header, OFF_SIZE, LEN_SIZE); - const dataStart = offset + BLOCK; - const dataEnd = dataStart + size; - if (dataEnd > tar.length) { + const size = readOctal(block, OFF_SIZE, LEN_SIZE); + this.headers += 1; + if (this.headers > this.options.limits.maxHeaders) { throw new TarExtractError( - 'tar entry runs past the end of the archive — truncated.', + `tar archive has more than ${this.options.limits.maxHeaders} headers.`, ); } - const next = dataStart + Math.ceil(size / BLOCK) * BLOCK; - const typeflag = String.fromCharCode(header[OFF_TYPEFLAG]!); + const typeflag = String.fromCharCode(block[OFF_TYPEFLAG]!); + const modified = this.modified; + // A 'g' modifies nothing, so it neither sets nor consumes the flag. + if (MODIFIERS.has(typeflag)) this.modified = true; + else if (typeflag !== 'g') this.modified = false; - // SKIP — a pax GLOBAL header, payload unread; it counts toward the cap. - if (typeflag === 'g') { - entries += 1; - if (entries > limits.maxEntries) { - throw new TarExtractError( - `tar archive has more than ${limits.maxEntries} entries.`, - ); - } - offset = next; - continue; + const key = selectionKey(block); + if (key !== null && this.options.select.has(key)) { + this.accept(block, typeflag, modified, size); } + this.dataLeft = size; + this.padLeft = Math.ceil(size / BLOCK) * BLOCK - size; + if (size === 0) this.writePending(); + } - // The FULL path is judged before any other entry rule, so no later message + /** The full rules, for a header at a selected path; arms `pending`. */ + private accept( + block: Buffer, + typeflag: string, + modified: boolean, + size: number, + ): void { + // The FULL path is judged before any other rule, so no later message // interpolates a control character from it. - const name = readPathField(header, OFF_NAME, LEN_NAME); - const prefix = readPathField(header, OFF_PREFIX, LEN_PREFIX); + const name = readPathField(block, OFF_NAME, LEN_NAME); + const prefix = readPathField(block, OFF_PREFIX, LEN_PREFIX); const fullPath = prefix === '' ? name : `${prefix}/${name}`; assertDisplayablePath(fullPath); - - const isFile = typeflag === '0' || typeflag === '\0'; - const isDirectory = typeflag === '5'; - if (!isFile && !isDirectory) { + if (typeflag !== '0' && typeflag !== '\0') { + throw new TarExtractError( + `tar entry has an unsupported type ${describeTypeflag(typeflag)} at a path pharn installs (only a regular file is accepted there): ${fullPath}`, + ); + } + if (modified) { + throw new TarExtractError( + `tar entry follows a pax extended or GNU long-name header, whose records pharn does not honour, at a path pharn installs: ${fullPath}`, + ); + } + const { rel, root } = resolveEntryPath(fullPath, this.root); + this.root = root; + if (this.written.has(rel)) { throw new TarExtractError( - `tar entry has an unsupported type ${describeTypeflag(typeflag)}: ${fullPath}`, + `tar archive holds this path twice: ${fullPath}`, ); } + this.written.add(rel); + this.bytes += size; + if (this.bytes > this.options.limits.maxWrittenBytes) { + throw new TarExtractError( + `the files pharn installs from this archive exceed ${this.options.limits.maxWrittenBytes} bytes.`, + ); + } + // safeJoin is the lexical containment backstop behind the segment rules. + this.pending = { target: safeJoin(this.destDir, rel), chunks: [] }; + } - const { rel, root } = resolveEntryPath(fullPath, isDirectory, expectedRoot); - expectedRoot = root; + private writePending(): void { + if (this.pending === null) return; + const { target, chunks } = this.pending; + this.pending = null; + mkdirSync(dirname(target), { recursive: true }); + writeFileSync(target, Buffer.concat(chunks)); + } +} - if (rel !== null) { - entries += 1; - if (entries > limits.maxEntries) { - throw new TarExtractError( - `tar archive has more than ${limits.maxEntries} entries.`, - ); - } - // safeJoin is the lexical containment backstop behind the segment rules. - const target = safeJoin(destDir, rel); - if (isDirectory) { - mkdirSync(target, { recursive: true }); - } else { - mkdirSync(dirname(target), { recursive: true }); - writeFileSync(target, tar.subarray(dataStart, dataEnd)); +/** + * Extract the selected files of an uncompressed tar into `destDir`, stripping + * the single leading path component. `tar` may come in chunks of any size. + * Throws `TarExtractError` on any refusal — a caller that sees one must treat + * the destination as unusable and remove it, since extraction is not + * transactional. + */ +export function extractTar( + tar: Buffer | readonly Buffer[], + destDir: string, + options: ExtractOptions, +): ExtractResult { + const walker = new TarWalker(destDir, options); + for (const chunk of Buffer.isBuffer(tar) ? [tar] : tar) walker.push(chunk); + return walker.finish(); +} + +/** + * `extractTar` over a gzipped archive, decompressed as a stream so the whole + * tar is never held in memory. Takes the archive's bytes, never a URL, so a + * local file goes through the same walk as a download. + */ +export async function extractTarGz( + archive: Buffer, + destDir: string, + options: ExtractOptions, +): Promise { + const walker = new TarWalker(destDir, options); + const gunzip = createGunzip(); + gunzip.end(archive); + // A refusal from the walk is rethrown as itself; only a gunzip failure is + // reported as a decompression error. + let refusal: unknown = null; + try { + for await (const chunk of gunzip) { + try { + walker.push(chunk as Buffer); + } catch (err) { + refusal = err; + break; } } - - offset = next; + } catch (err) { + throw new TarExtractError( + `could not decompress the fetched archive: ${(err as Error).message}`, + ); } - // The walk ran out of bytes without meeting a zero block: the archive was cut - // short (every real tar ends with at least one). - throw new TarExtractError( - 'tar archive has no end-of-archive marker — truncated.', - ); + if (refusal !== null) throw refusal; + return walker.finish(); } diff --git a/src/lib/upstream-manifest.ts b/src/lib/upstream-manifest.ts index 92e57a4d..d2dbe91e 100644 --- a/src/lib/upstream-manifest.ts +++ b/src/lib/upstream-manifest.ts @@ -42,7 +42,11 @@ import type { // safeJoin-contained, every `dest` must lie inside the CLI-owned outer bound // (isPharnOwnedPath — never the manifest's own `installRoots`), and fetchRepo // verifies each file's RAW sha256 right after extraction, before any command -// can read the tree, so a mismatch refuses with nothing written. +// can read the tree, so a mismatch refuses with nothing written. The extractor +// writes only the paths listed here plus the few files the CLI reads itself +// (CLONE_READ_FILES, lib/repo.ts), so this file is validated between its two +// passes, before the tree holds anything it lists: no check here may probe the +// tree for a listed file. // // ONE parser: readUpstreamManifest is the only reader. verifyUpstreamManifest // takes its result, and every branch point re-reads through it, so there is no @@ -55,7 +59,7 @@ export const MANIFEST_FILE = 'pharn-install.json'; export const MANIFEST_SCHEMA_VERSION = 1; // pharn-oss 7.21.0's file is about 180 KB. export const MAX_MANIFEST_BYTES = 4 * 1024 * 1024; -// The extractor's own entry cap: a tree cannot hold more files than this. +// The most files a manifest may list, and so the most the extractor writes. export const MAX_MANIFEST_FILES = 20_000; const POLICIES = ['managed', 'if-absent'] as const; @@ -158,9 +162,10 @@ export function readUpstreamManifest(repoDir: string): UpstreamManifest { ); } const skillsVersion = checkSkillsVersion(repoDir, raw.skillsVersion); - checkLayout(repoDir, raw.layout); + checkLayout(raw.layout); const capabilities = checkCapabilities(raw.capabilities); const files = checkFiles(repoDir, raw.files, capabilities); + checkLayoutMarker(repoDir, files); const modelsDefaults = checkModels(raw.models); checkInstallRoots(raw.installRoots); return { skillsVersion, capabilities, files, modelsDefaults }; @@ -180,8 +185,8 @@ function checkSkillsVersion(repoDir: string, value: unknown): string { } // The only layout a manifest may declare is the one this CLI knows as `pharn`, -// with its own marker and capability subtrees, and the tree must be it. -function checkLayout(repoDir: string, layout: unknown): void { +// with its own marker and capability subtrees. +function checkLayout(layout: unknown): void { const pharn = layoutPaths('pharn'); const subtrees = isPlainObject(layout) ? layout.capabilitySubtrees : null; const known = @@ -197,9 +202,23 @@ function checkLayout(repoDir: string, layout: unknown): void { `pharn-oss's ${MANIFEST_FILE} declares a layout this pharn does not know (${escapeUnsafe(show(layout))}). Upgrade pharn (\`npm install -g @pharn-dev/pharn@latest\`) and re-run. Nothing was written.`, ); } - if (!isPharnLayout(repoDir)) { +} + +// The layout's marker must be in the tree. The extractor writes only listed +// files (each proved present by verifyUpstreamManifest) plus a few root and +// .claude files, so once extracted the tree has the marker exactly when a +// listed file lies under it. Accepting a listed file lets this run between the +// extractor's passes, before the listed files are written. +function checkLayoutMarker( + repoDir: string, + files: readonly ManifestFile[], +): void { + const listed = files.some((f) => + f.path.startsWith(`${PHARN_CONTRACTS_DIR}/`), + ); + if (!listed && !isPharnLayout(repoDir)) { throw refuse( - `declares the pharn layout, but the tree has no ${PHARN_CONTRACTS_DIR}`, + `declares the pharn layout, but the tree has no ${PHARN_CONTRACTS_DIR} and it lists no file there`, ); } } diff --git a/tests/commands/init.test.ts b/tests/commands/init.test.ts index ced7c9a7..84c0d4da 100644 --- a/tests/commands/init.test.ts +++ b/tests/commands/init.test.ts @@ -971,13 +971,14 @@ describe('a fresh install', () => { }); // pharn/pharn-contracts is the pharn layout's marker: a manifest that - // declares that layout over a tree without it is refused, never installed. - it('a clone with no pharn-contracts is refused: its manifest declares a layout the tree lacks', async () => { + // declares that layout but lists nothing under it is refused, never + // installed (only listed files are extracted, so the tree would lack it). + it('a clone with no pharn-contracts is refused: its manifest declares a layout it does not list', async () => { delete upstream.tree['pharn/pharn-contracts/finding-shape.md']; const before = snapshot(); expect(await run(() => runInit({ yes: true }))).toBe(1); expect(errors()).toContain( - 'declares the pharn layout, but the tree has no pharn/pharn-contracts', + 'declares the pharn layout, but the tree has no pharn/pharn-contracts and it lists no file there', ); expect(snapshot()).toEqual(before); }); diff --git a/tests/project-lock.test.ts b/tests/project-lock.test.ts index 21b05ef5..99fd1e03 100644 --- a/tests/project-lock.test.ts +++ b/tests/project-lock.test.ts @@ -804,11 +804,23 @@ describe('withProjectLock — a fatal signal while held', () => { // re-raise land. A handler that re-raises kills the process before that // listener runs; one that swallows the signal lets the body print the marker // in milliseconds. + // The signal is processed on a later loop turn. Node's signal handles are + // unref'd, so with nothing else ref'd the child would exit (code 13, an + // unsettled top-level await) before it: a ref'd timer holds the loop open + // until the handlers have run, instead of whatever handle happens to be live. const SIGNAL_HANDLED = ` const signalHandled = (s) => - new Promise((resolve) => - process.once(s, () => setImmediate(() => setImmediate(resolve))), - ); + new Promise((resolve) => { + const alive = setInterval(() => {}, 1000); + process.once(s, () => + setImmediate(() => + setImmediate(() => { + clearInterval(alive); + resolve(); + }), + ), + ); + }); `; /** Killed by `sig` — as a signal, or as the shell's 128 + n. */ diff --git a/tests/repo.test.ts b/tests/repo.test.ts index aaae00c2..975e76c2 100644 --- a/tests/repo.test.ts +++ b/tests/repo.test.ts @@ -1,5 +1,6 @@ import { existsSync, + lstatSync, mkdtempSync, readdirSync, readFileSync, @@ -12,6 +13,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { REPO, REPO_BRANCH } from '../src/lib/constants.js'; import { ManifestValidationError } from '../src/lib/validate.js'; import { UpstreamManifestError } from '../src/lib/upstream-manifest.js'; +import { TarExtractError } from '../src/lib/tar-extract.js'; import { codeloadArchive } from './support/tar-fixture.js'; import { MANIFEST, @@ -21,7 +23,8 @@ import { withManifest, } from './support/harness.js'; -const { fetchRepo, fetchCommitSha } = await import('../src/lib/repo.js'); +const { CLONE_READ_FILES, extractPharnArchive, fetchRepo, fetchCommitSha } = + await import('../src/lib/repo.js'); // A real 40-char lowercase-hex commit SHA (the SHA-1 of the empty blob) — the // form fetchRepo validates against COMMIT_RE before it fetches or records it. @@ -658,3 +661,196 @@ describe('fetchRepo — a tree that declares pharn-install.json (CORE-194)', () expect(leftoverTempDirs()).toEqual([]); }); }); + +// CORE-386: only the paths pharn-install.json lists (plus the files the CLI +// reads itself) are unpacked. pharn-oss v7.25.3–v7.25.5 committed symlinks +// under .claude/skills/, outside the manifest, and every install failed. +describe('fetchRepo — only the listed paths are unpacked (CORE-386)', () => { + const release = { + kind: 'release' as const, + tag: 'v7.20.0', + version: '7.20.0', + sha: VALID_SHA, + }; + const ROOT = `pharn-oss-${VALID_SHA.slice(0, 7)}`; + + beforeEach(() => { + sandbox = mkdtempSync(join(tmpdir(), 'pharn-repo-sandbox-')); + process.env.TMPDIR = sandbox; + process.env.TEMP = sandbox; + process.env.TMP = sandbox; + }); + + afterEach(() => { + for (const [key, value] of Object.entries(realTmp)) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + rmSync(sandbox, { recursive: true, force: true }); + vi.unstubAllGlobals(); + }); + + /** A pax extended-header record, ` =\n` (self-counting). */ + function paxRecord(keyword: string, value: string): string { + const body = ` ${keyword}=${value}\n`; + let len = body.length + 1; + while (String(len).length + body.length !== len) + len = String(len).length + body.length; + return `${len}${body}`; + } + + /** + * The codeload shape around `tree`, with `odd` entries spliced in right after + * the root directory and `replace` swapping a tree file's own entry for raw + * entries (a symlink at a listed path, a pax-renamed file). + */ + function archiveWith( + tree: Record, + odd: Buffer[], + replace: Record = {}, + ): Buffer { + const parts = [ + entry('pax_global_header', 'g', `52 comment=${VALID_SHA}\n`), + entry(`${ROOT}/`, '5'), + ...odd, + ]; + for (const rel of Object.keys(tree).sort()) { + parts.push( + ...(replace[rel] ?? [entry(`${ROOT}/${rel}`, '0', tree[rel])]), + ); + } + parts.push(Buffer.alloc(BLOCK * 2)); + return gzipSync(Buffer.concat(parts)); + } + + const serve = (bytes: Buffer): void => { + vi.stubGlobal( + 'fetch', + vi.fn(async () => tarResponse(bytes, 4096)), + ); + }; + + /** Every regular file under `dir`, relative and sorted. */ + function filesUnder(dir: string): string[] { + return (readdirSync(dir, { recursive: true }) as string[]) + .filter((rel) => lstatSync(join(dir, rel)).isFile()) + .sort(); + } + + // Each entry v7.25.5 (or a future pharn-oss) could carry outside the list. + const UNLISTED: Buffer[] = [ + entry(`${ROOT}/.claude/skills/pharn-cli`, '2'), // a symlink + entry(`${ROOT}/.dev/hard`, '1'), // a hard link + entry( + `${ROOT}/PaxHeaders/long`, + 'x', + paxRecord('path', `${ROOT}/.dev/${'s'.repeat(120)}.md`), + ), + entry(`${ROOT}/0123456789abcdef.data`, '0', 'long-named\n'), + entry(`${ROOT}/.dev/a:b.md`, '0', 'colon\n'), + entry(`${ROOT}/.dev/notes.md`, '0', 'an unlisted regular file\n'), + ]; + + it('installs past a symlink, hard link, pax header, long and colon name outside the list, writing none of them', async () => { + const tree = manifestTree('7.20.0'); + serve(archiveWith(tree, UNLISTED)); + const repo = await fetchRepo(release); + try { + const listed = ( + JSON.parse(tree[MANIFEST]!) as { files: { path: string }[] } + ).files.map((f) => f.path); + const expected = new Set([ + ...listed, + ...CLONE_READ_FILES.filter((f) => f in tree), + ]); + expect(filesUnder(repo.dir)).toEqual([...expected].sort()); + expect(existsSync(join(repo.dir, '.dev'))).toBe(false); + expect(existsSync(join(repo.dir, '.claude/skills/pharn-cli'))).toBe( + false, + ); + expect(existsSync(join(repo.dir, 'PaxHeaders'))).toBe(false); + } finally { + repo.cleanup(); + } + }); + + it('refuses a symlink AT a listed path, and removes the tree', async () => { + serve( + archiveWith(manifestTree('7.20.0'), [], { + [SECURITY]: [entry(`${ROOT}/${SECURITY}`, '2')], + }), + ); + const err = await fetchRepo(release).catch((e: unknown) => e); + expect(err).toBeInstanceOf(TarExtractError); + expect((err as Error).message).toMatch(/unsupported type '2'/); + expect((err as Error).message).toContain(SECURITY); + expect(leftoverTempDirs()).toEqual([]); + }); + + it('refuses a listed file that follows a pax extended header, and removes the tree', async () => { + const tree = manifestTree('7.20.0'); + serve( + archiveWith(tree, [], { + [SECURITY]: [ + entry(`${ROOT}/PaxHeaders/security.md`, 'x', paxRecord('mtime', '1')), + entry(`${ROOT}/${SECURITY}`, '0', tree[SECURITY]), + ], + }), + ); + const err = await fetchRepo(release).catch((e: unknown) => e); + expect(err).toBeInstanceOf(TarExtractError); + expect((err as Error).message).toMatch(/pax extended or GNU long-name/); + expect(leftoverTempDirs()).toEqual([]); + }); + + it('fails the hash check when a pax record renamed a listed file away from its ustar name', async () => { + const tree = manifestTree('7.20.0'); + serve( + archiveWith(tree, [], { + [SECURITY]: [ + entry( + `${ROOT}/PaxHeaders/security.md`, + 'x', + paxRecord('path', `${ROOT}/${SECURITY}`), + ), + entry(`${ROOT}/0123456789abcdef.data`, '0', tree[SECURITY]), + ], + }), + ); + const err = await fetchRepo(release).catch((e: unknown) => e); + expect(err).toBeInstanceOf(UpstreamManifestError); + expect((err as Error).message).toContain( + `declares ${SECURITY}, which the tree does not ship as a file`, + ); + expect(leftoverTempDirs()).toEqual([]); + }); + + it('extracts a local archive with no network: the CLI-read files first, then the listed ones', async () => { + vi.stubGlobal( + 'fetch', + vi.fn(async () => { + throw new Error('no network in this test'); + }), + ); + const tree = manifestTree('7.20.0'); + const dir = mkdtempSync(join(sandbox, 'local-')); + const seen: boolean[] = []; + const manifest = await extractPharnArchive( + archiveWith(tree, UNLISTED), + dir, + (d) => { + seen.push(existsSync(join(d, MANIFEST)), existsSync(join(d, SECURITY))); + }, + ); + // Between the passes the manifest is on disk and no listed file is yet. + expect(seen).toEqual([true, false]); + expect(manifest.files.map((f) => f.path)).toContain(SECURITY); + expect(readFileSync(join(dir, SECURITY), 'utf8')).toBe(tree[SECURITY]); + expect(existsSync(join(dir, '.dev'))).toBe(false); + // The tree check is optional (a local file has no tag to hold it to). + const again = mkdtempSync(join(sandbox, 'local-')); + await expect( + extractPharnArchive(archiveWith(tree, UNLISTED), again), + ).resolves.toMatchObject({ skillsVersion: '7.20.0' }); + }); +}); diff --git a/tests/tar-extract.test.ts b/tests/tar-extract.test.ts index 4bc09752..9a6caa86 100644 --- a/tests/tar-extract.test.ts +++ b/tests/tar-extract.test.ts @@ -1,4 +1,4 @@ -import { existsSync, lstatSync, readFileSync, readdirSync } from 'node:fs'; +import { lstatSync, mkdtempSync, readFileSync, readdirSync } from 'node:fs'; import { join } from 'node:path'; import { gzipSync } from 'node:zlib'; import { describe, expect, it } from 'vitest'; @@ -8,6 +8,7 @@ import { extractTarGz, TarExtractError, } from '../src/lib/tar-extract.js'; +import type { ExtractOptions, TarLimits } from '../src/lib/tar-extract.js'; import { hasUnsafeChars } from '../src/lib/terminal-safe.js'; import { codeloadArchive } from './support/tar-fixture.js'; @@ -16,11 +17,22 @@ import { codeloadArchive } from './support/tar-fixture.js'; // refuses to write — an absolute path, a `..` segment, a device node, a header // whose checksum does not match. A fixture generator that can only produce // well-formed archives cannot exercise a single rejection. +// +// CORE-386: the extractor writes only the SELECTED paths (pharn-install.json's +// list plus the files the CLI reads). Every block below states which side of +// the selection its entry sits on: outside it, any entry is skipped and nothing +// is written for it; at a selected path, every rule applies. const BLOCK = 512; -const LIMITS = { maxEntries: 1000, maxTotalBytes: 1024 * 1024 }; +const LIMITS: TarLimits = { + maxHeaders: 1000, + maxScannedBytes: 8 * 1024 * 1024, + maxWrittenBytes: 1024 * 1024, +}; /** An escape byte, written as a code point so no raw control char sits in this source. */ const ESC = '\u001b'; +const ROOT = 'pharn-oss-abc1234'; +const at = (rel: string): string => `${ROOT}/${rel}`; interface EntryInit { name: string; @@ -86,8 +98,7 @@ function tar(entries: EntryInit[]): Buffer { /** * One pax record, ` =\n`, where `` counts the whole * record INCLUDING its own digits — so the width is self-referential and has to - * be solved for, which is exactly the arithmetic a hand-written literal gets - * wrong (and which the reader now rejects rather than tolerates). + * be solved for. */ function paxRecord(keyword: string, value: string): string { const body = ` ${keyword}=${value}\n`; @@ -108,94 +119,116 @@ const GLOBAL_HEADER: EntryInit = { /** The shape every real codeload archive has, minus the entries under test. */ function githubArchive(entries: EntryInit[]): Buffer { - return tar([ - // GitHub's first entry, always. Single-segment name, no leading component. - GLOBAL_HEADER, - { name: 'pharn-oss-abc1234/', type: '5' }, - ...entries, - ]); + return tar([GLOBAL_HEADER, { name: `${ROOT}/`, type: '5' }, ...entries]); } -describe('extractTar', () => { - const tmp = useTmpDir(); +/** One selected file every archive below carries, so "nothing else" is visible. */ +const KEEP: EntryInit = { name: at('SKILLS_VERSION'), data: '1.0.0\n' }; - it('strips one component and writes the tree', () => { - const dest = tmp.path(); - extractTar( +function opts( + select: Iterable = ['SKILLS_VERSION'], + limits: TarLimits = LIMITS, +): ExtractOptions { + return { select: new Set(select), limits }; +} + +/** Every path under `dir`, files and directories, relative and sorted. */ +function treeOf(dir: string): string[] { + return (readdirSync(dir, { recursive: true }) as string[]) + .map((p) => p.split('\\').join('/')) + .sort(); +} + +/** Every path under `dir` that lstat says is neither a file nor a directory. */ +function nonFileOrDir(dir: string): string[] { + return treeOf(dir).filter((rel) => { + const st = lstatSync(join(dir, rel)); + return !st.isFile() && !st.isDirectory(); + }); +} + +// One temp dir per test; `fresh()` hands out an empty directory inside it. +const tmp = useTmpDir(); +const fresh = (): string => mkdtempSync(join(tmp.path(), 'dest-')); + +/** The refusal message, or 'accepted'. */ +function refusal(archive: Buffer, options = opts(), dest = fresh()): string { + try { + extractTar(archive, dest, options); + } catch (err) { + expect(err).toBeInstanceOf(TarExtractError); + return (err as Error).message; + } + return 'accepted'; +} + +const utf8AsLatin1 = (s: string): string => + Buffer.from(s, 'utf8').toString('latin1'); + +describe('extractTar — what is written', () => { + it('writes exactly the selected files, stripping one component', () => { + const dest = fresh(); + const result = extractTar( githubArchive([ - { name: 'pharn-oss-abc1234/SKILLS_VERSION', data: '1.0.0\n' }, - { name: 'pharn-oss-abc1234/pharn-review/', type: '5' }, - { name: 'pharn-oss-abc1234/pharn-review/a11y.md', data: '# a11y\n' }, + KEEP, + { name: at('pharn-review/'), type: '5' }, + { name: at('pharn-review/a11y.md'), data: '# a11y\n' }, + { name: at('pharn-review/unlisted.md'), data: 'not listed\n' }, + { name: at('README.md'), data: 'not listed\n' }, ]), dest, - LIMITS, + opts(['SKILLS_VERSION', 'pharn-review/a11y.md']), ); + expect(treeOf(dest)).toEqual([ + 'SKILLS_VERSION', + 'pharn-review', + 'pharn-review/a11y.md', + ]); expect(readFileSync(join(dest, 'SKILLS_VERSION'), 'utf8')).toBe('1.0.0\n'); expect(readFileSync(join(dest, 'pharn-review/a11y.md'), 'utf8')).toBe( '# a11y\n', ); - // The archive root itself is not written as a directory named after the sha. - expect(existsSync(join(dest, 'pharn-oss-abc1234'))).toBe(false); + expect([...result.written].sort()).toEqual([ + 'SKILLS_VERSION', + 'pharn-review/a11y.md', + ]); + expect(result.bytes).toBe(6 + 7); + expect(result.root).toBe(ROOT); }); - it('skips the leading pax_global_header instead of rejecting it', () => { - // The regression this test exists for: a `g` entry's name is a single - // segment with nothing to strip, so running the path rules over it fails - // the FIRST block of every real archive — init/add/update/status would fail - // 100% of the time against the live remote while every hand-made fixture - // passed. - const dest = tmp.path(); - expect(() => - extractTar( - githubArchive([{ name: 'pharn-oss-abc1234/ok.txt', data: 'ok' }]), - dest, - LIMITS, - ), - ).not.toThrow(); - expect(readFileSync(join(dest, 'ok.txt'), 'utf8')).toBe('ok'); - expect(existsSync(join(dest, 'pax_global_header'))).toBe(false); + it('writes nothing, and reports no root, when nothing is selected', () => { + const dest = fresh(); + const result = extractTar(githubArchive([KEEP]), dest, opts([])); + expect(treeOf(dest)).toEqual([]); + expect(result).toEqual({ written: new Set(), bytes: 0, root: null }); }); - // --- pax extended headers (typeflag 'x') ------------------------------------ - // - // An `x` header's records OVERRIDE the ustar header that follows it (`path=`, - // `size=`), so it is refused on the TYPEFLAG alone. Its payload is never read, - // so no payload, well-formed or not, can change the answer. - - it.each([ - ['path=', paxRecord('path', 'pharn-oss-abc1234/deep/elsewhere.txt')], - ['size=', paxRecord('size', '8589934592')], - ['only benign metadata', paxRecord('mtime', '1700000000.0')], - ['an unparseable payload', '7 comment=xyz\n'], - ['an empty payload', ''], - ])( - 'refuses a pax extended header carrying %s, on its typeflag alone', - (_label, data) => { - expect(() => - extractTar( - githubArchive([ - { name: 'pharn-oss-abc1234/PaxHeaders/f.txt', type: 'x', data }, - { name: 'pharn-oss-abc1234/f.txt', data: 'x' }, - ]), - tmp.path(), - LIMITS, - ), - ).toThrow(/unsupported type 'x'.*pax extended header/); - }, - ); + it('writes a selected empty file', () => { + const dest = fresh(); + extractTar( + githubArchive([{ name: at('MIN_CLI'), data: '' }]), + dest, + opts(['MIN_CLI']), + ); + expect(readFileSync(join(dest, 'MIN_CLI'), 'utf8')).toBe(''); + }); - // --- pax GLOBAL headers (typeflag 'g') -------------------------------------- - // - // Every codeload archive opens with one, so 'g' is SKIPPED, payload unread. - // pharn reads only the ustar fields, so a `g` default for `path`/`size` is - // never honoured: the entries that follow land at their own ustar paths, and - // a size the default would imply cannot re-frame pharn's walk. + it('skips the leading pax_global_header instead of rejecting it', () => { + // The anti-regression for the 100%-failure bug: `pax_global_header` is a + // single segment with nothing to strip, so judging it fails the FIRST + // block of every real archive while every hand-made fixture passes. + const dest = fresh(); + extractTar(githubArchive([KEEP]), dest, opts()); + expect(treeOf(dest)).toEqual(['SKILLS_VERSION']); + }); + // A `g` default is never honoured: pharn reads only the ustar fields, so the + // entries after it land at their own ustar paths. it.each([['path'], ['linkpath'], ['size']])( 'skips a pax global header setting a default %s=, never honouring it', (keyword) => { - const dest = tmp.path(); + const dest = fresh(); extractTar( tar([ { @@ -203,389 +236,354 @@ describe('extractTar', () => { type: 'g', data: paxRecord(keyword, 'elsewhere'), }, - { name: 'pharn-oss-abc1234/', type: '5' }, - { name: 'pharn-oss-abc1234/f.txt', data: 'x' }, + { name: `${ROOT}/`, type: '5' }, + { name: at('f.txt'), data: 'x' }, ]), dest, - LIMITS, + opts(['f.txt']), ); - expect(readdirSync(dest)).toEqual(['f.txt']); + expect(treeOf(dest)).toEqual(['f.txt']); expect(readFileSync(join(dest, 'f.txt'), 'utf8')).toBe('x'); }, ); - it('skips a pax global header whose payload does not parse, unread', () => { - const dest = tmp.path(); + it.each([ + ['an unparseable payload', '7 comment=xyz\n'], + [ + 'metadata and vendor records', + paxRecord('mtime', '1700000000.0') + + paxRecord('SCHILY.xattr.user.thing', 'value'), + ], + ['a payload over two blocks', paxRecord('comment', 'q'.repeat(1200))], + ])('skips a pax global header carrying %s, unread', (_label, data) => { + const dest = fresh(); extractTar( tar([ - { name: 'pax_global_header', type: 'g', data: '7 comment=xyz\n' }, - { name: 'pharn-oss-abc1234/', type: '5' }, - { name: 'pharn-oss-abc1234/f.txt', data: 'x' }, + { name: 'pax_global_header', type: 'g', data }, + { name: `${ROOT}/`, type: '5' }, + KEEP, ]), dest, - LIMITS, - ); - expect(readdirSync(dest)).toEqual(['f.txt']); - }); - - it('still skips the global header GitHub actually sends', () => { - // The anti-regression for the 100%-failure bug: `pax_global_header` is a - // single segment with nothing to strip, so running the path rules over it — - // or throwing on `g` outright — fails the FIRST block of every real archive - // while every hand-made fixture passes. - const dest = tmp.path(); - extractTar( - githubArchive([{ name: 'pharn-oss-abc1234/ok.txt', data: 'ok' }]), - dest, - LIMITS, + opts(), ); - expect(readFileSync(join(dest, 'ok.txt'), 'utf8')).toBe('ok'); - expect(existsSync(join(dest, 'pax_global_header'))).toBe(false); + expect(treeOf(dest)).toEqual(['SKILLS_VERSION']); }); - it('skips a global header carrying metadata and vendor records', () => { - const dest = tmp.path(); + it('reassembles a selected path split across prefix and name', () => { + // ustar splits any path over 100 chars: the tail goes in `name`, the head + // in `prefix`. Reading `name` alone would miss the file entirely. + const deep = 'a'.repeat(40); + const rel = `${deep}/${deep}/regression-report.json`; + const dest = fresh(); extractTar( - tar([ + githubArchive([ { - name: 'pax_global_header', - type: 'g', - data: - paxRecord('mtime', '1700000000.0') + - paxRecord('uname', 'root') + - paxRecord('SCHILY.xattr.user.thing', 'value'), + prefix: `${ROOT}/${deep}/${deep}`, + name: 'regression-report.json', + data: '{}', }, - { name: 'pharn-oss-abc1234/', type: '5' }, - { name: 'pharn-oss-abc1234/ok.txt', data: 'ok' }, ]), dest, - LIMITS, + opts([rel]), ); - expect(readFileSync(join(dest, 'ok.txt'), 'utf8')).toBe('ok'); + expect(readFileSync(join(dest, rel), 'utf8')).toBe('{}'); }); - it('skips a global header whose payload spans more than one block', () => { - // The padded multi-block advance is newly load-bearing: the reader now - // consumes the payload it used to step over blind, so the framing has to be - // demonstrated rather than inherited. - const dest = tmp.path(); - const big = paxRecord('comment', 'q'.repeat(1200)); - expect(big.length).toBeGreaterThan(BLOCK * 2); + it('accepts a non-ASCII root and writes the selected file below it', () => { + const dest = fresh(); extractTar( tar([ - { name: 'pax_global_header', type: 'g', data: big }, - { name: 'pharn-oss-abc1234/', type: '5' }, - { name: 'pharn-oss-abc1234/ok.txt', data: 'ok' }, + GLOBAL_HEADER, + { name: utf8AsLatin1('pharn-oss-café/SKILLS_VERSION'), data: 'ok' }, ]), dest, - LIMITS, + opts(), ); - expect(readFileSync(join(dest, 'ok.txt'), 'utf8')).toBe('ok'); + expect(treeOf(dest)).toEqual(['SKILLS_VERSION']); }); - it('reassembles a path split across prefix and name', () => { - // ustar splits any path over 100 chars: the tail goes in `name`, the head in - // `prefix`. 619 of the live archive's ~1,470 entries use it. Reading `name` - // alone yields a bare leaf, which strip-1 then rejects for having no leading - // component — losing a third of the tree rather than misplacing it. - const deep = 'a'.repeat(40); - const dest = tmp.path(); - extractTar( - githubArchive([ - { - prefix: `pharn-oss-abc1234/${deep}/${deep}`, - name: 'regression-report.json', - data: '{}', - }, - ]), - dest, - LIMITS, + it('holds a later pass to the root an earlier pass learned', () => { + const archive = githubArchive([KEEP]); + expect(refusal(archive, { ...opts(), root: 'pharn-oss-other' })).toMatch( + /more than one root component: pharn-oss-other and/, ); - expect( - readFileSync(join(dest, deep, deep, 'regression-report.json'), 'utf8'), - ).toBe('{}'); - // ...and it did NOT land at the root as a bare leaf. - expect(existsSync(join(dest, 'regression-report.json'))).toBe(false); - }); - - it.each([ - ['a `..` segment', 'pharn-oss-abc1234/../escape.txt'], - ['a deeper `..` segment', 'pharn-oss-abc1234/nested/../../escape.txt'], - ])('rejects %s', (_label, name) => { - expect(() => - extractTar(githubArchive([{ name, data: 'x' }]), tmp.path(), LIMITS), - ).toThrow(TarExtractError); + expect(refusal(archive, { ...opts(), root: ROOT })).toBe('accepted'); }); +}); - it('rejects an absolute path', () => { - expect(() => - extractTar( - githubArchive([{ name: '/etc/passwd', data: 'x' }]), - tmp.path(), - LIMITS, - ), - ).toThrow(/absolute path/); +// The decision this file used to pin was "reject a symlink entry outright, +// rather than skipping it": degit dropped such entries silently, and a dropped +// entry could be a file pharn installs. It is NARROWED here, not reversed: an +// entry outside the selection is skipped and never written (nothing unlisted +// touches disk, so skipping is strictly safer than judging), while an entry at +// a selected path is still refused. A listed file that a skipped entry stood in +// for — a symlink, or a file a pax record renamed — is missing from the tree, +// and the manifest's sha256 check (verifyUpstreamManifest) refuses it loudly: +// the silent loss degit allowed cannot recur. +describe('extractTar — outside the selection: skipped, nothing written', () => { + it.each<[string, EntryInit[]]>([ + ['a symlink', [{ name: at('.claude/skills/x'), type: '2' }]], + ['a hard link', [{ name: at('link'), type: '1' }]], + ['a character device', [{ name: at('dev'), type: '3' }]], + ['a block device', [{ name: at('blk'), type: '4' }]], + ['a fifo', [{ name: at('fifo'), type: '6' }]], + ['an unknown type', [{ name: at('odd'), type: '9' }]], + ['a directory', [{ name: at('.dev/'), type: '5' }]], + [ + 'a pax extended header and the entry it renames', + [ + { + name: at('PaxHeaders/long'), + type: 'x', + data: paxRecord('path', at(`${'d'.repeat(120)}/f.md`)), + }, + { name: at('0123456789abcdef.data'), data: 'x' }, + ], + ], + [ + 'a GNU long name and the entry it renames', + [ + { name: '././@LongLink', type: 'L', data: at('x'.repeat(150)) }, + { name: at('xxxxxxxx'), data: 'x' }, + ], + ], + [ + 'a GNU long link name and its symlink', + [ + { name: '././@LongLink', type: 'K', data: 'y'.repeat(150) }, + { name: at('l'), type: '2' }, + ], + ], + ['a name with a colon', [{ name: at('a:b.md'), data: 'x' }]], + ['a name with a backslash', [{ name: at('a\\..\\..\\evil'), data: 'x' }]], + ['an invalid UTF-8 name', [{ name: at('bad-\x9b2J.md'), data: 'x' }]], + ['an escape sequence in a name', [{ name: at(`n${ESC}[2K`), data: 'x' }]], + [ + 'a right-to-left override', + [{ name: utf8AsLatin1(at('evil\u202egnp.md')), data: 'x' }], + ], + ['an absolute path', [{ name: '/etc/passwd', data: 'x' }]], + ['a `..` segment', [{ name: at('../escape.txt'), data: 'x' }]], + ['a second root', [{ name: 'somewhere-else/evil.txt', data: 'x' }]], + ['a file with no root', [{ name: 'loose.txt', data: 'x' }]], + ['an empty segment', [{ name: at('a//b.md'), data: 'x' }]], + ])('installs past %s and writes nothing for it', (_label, entries) => { + const dest = fresh(); + const result = extractTar(githubArchive([...entries, KEEP]), dest, opts()); + expect(treeOf(dest)).toEqual(['SKILLS_VERSION']); + expect([...result.written]).toEqual(['SKILLS_VERSION']); + expect(nonFileOrDir(dest)).toEqual([]); }); - it('rejects a file with no component to strip', () => { - // No preceding root entry, so this is the FIRST accepted path: the - // multi-root guard cannot fire and the strip-1 rule is what must reject it. - expect(() => - extractTar( - tar([GLOBAL_HEADER, { name: 'loose.txt', data: 'x' }]), - tmp.path(), - LIMITS, - ), - ).toThrow(/no path below the archive root/); + it('a pax header modifies only the next entry: the selected file after it is written', () => { + const dest = fresh(); + extractTar( + githubArchive([ + { name: at('PaxHeaders/x'), type: 'x', data: paxRecord('size', '1') }, + { name: at('unlisted.md'), data: 'x' }, + KEEP, + ]), + dest, + opts(), + ); + expect(treeOf(dest)).toEqual(['SKILLS_VERSION']); }); - it('rejects a second root component', () => { - expect(() => - extractTar( - githubArchive([ - { name: 'pharn-oss-abc1234/ok.txt', data: 'x' }, - { name: 'somewhere-else/evil.txt', data: 'x' }, - ]), - tmp.path(), - LIMITS, - ), - ).toThrow(/more than one root component/); + it('bounds only the bytes written: an unselected file over the cap is skipped', () => { + const dest = fresh(); + extractTar( + githubArchive([{ name: at('big.bin'), data: 'x'.repeat(4096) }, KEEP]), + dest, + opts(['SKILLS_VERSION'], { ...LIMITS, maxWrittenBytes: 100 }), + ); + expect(treeOf(dest)).toEqual(['SKILLS_VERSION']); }); +}); +describe('extractTar — at a selected path: refused', () => { it.each([ ['a symlink', '2'], - ['a hardlink', '1'], + ['a hard link', '1'], ['a character device', '3'], ['a block device', '4'], + ['a directory', '5'], ['a fifo', '6'], ['a pax extended header', 'x'], - // GNU's long-name typeflags are the other way a writer escapes ustar's - // 100-byte name field. They need no branch of their own — they are neither - // '0'/NUL nor '5', so they land in this reject — but they are pinned HERE - // so a future refactor of the bucket cannot start accepting them quietly. + ['a pax global header', 'g'], ['a GNU long name', 'L'], ['a GNU long link name', 'K'], ['an unknown type', '9'], - ])('rejects %s entry outright, rather than skipping it', (_label, type) => { - // degit passed neither `strict` nor `onwarn`, so an entry like this was - // dropped and the clone still resolved. The live archive contains none of - // these, so a rejection here is a real signal. - expect(() => - extractTar( - githubArchive([{ name: 'pharn-oss-abc1234/link', type }]), - tmp.path(), - LIMITS, + ])('refuses %s, naming the path and the rule', (_label, type) => { + const dest = fresh(); + const message = refusal( + githubArchive([{ name: at('SKILLS_VERSION'), type }]), + opts(), + dest, + ); + expect(message).toMatch(/unsupported type/); + expect(message).toContain(at('SKILLS_VERSION')); + expect(treeOf(dest)).toEqual([]); + }); + + it.each([ + ['a pax extended header', 'x'], + ['a GNU long name', 'L'], + ])( + 'refuses a selected file that follows %s, whose records pharn does not honour', + (_label, type) => { + const message = refusal( + githubArchive([ + { name: at('PaxHeaders/SKILLS_VERSION'), type, data: '' }, + KEEP, + ]), + ); + expect(message).toMatch(/pax extended or GNU long-name header/); + expect(message).toContain(at('SKILLS_VERSION')); + }, + ); + + it('a pax global header between the extended header and the file does not lift the refusal', () => { + expect( + refusal( + githubArchive([ + { name: at('PaxHeaders/x'), type: 'x', data: '' }, + { name: 'pax_global_header', type: 'g', data: '' }, + KEEP, + ]), ), - ).toThrow(/unsupported type/); + ).toMatch(/pax extended or GNU long-name header/); }); - // PHARN-17: a name a terminal would interpret is refused before any other - // entry rule, so it is neither installed (and later listed by status/update) - // nor echoed raw by a refusal message. Names are latin1 in the header, so a - // UTF-8 U+202E is written as its three bytes. - const utf8AsLatin1 = (s: string): string => - Buffer.from(s, 'utf8').toString('latin1'); + it.each([ + ['an absolute path', '/SKILLS_VERSION', /absolute path/], + ['a `..` root', '../SKILLS_VERSION', /escapes the archive root/], + ['a "." root', './SKILLS_VERSION', /no leading component/], + ['a drive-letter root', 'C:/SKILLS_VERSION', /backslash or colon/], + ['a backslash in the root', 'a\\b/SKILLS_VERSION', /backslash or colon/], + ])('refuses %s', (_label, name, rule) => { + const message = refusal(tar([GLOBAL_HEADER, { name, data: 'x' }])); + expect(message).toMatch(rule); + expect(message).toContain(name); + }); + + it('refuses a colon in the ustar prefix too', () => { + expect( + refusal(tar([{ prefix: 'x:y', name: 'SKILLS_VERSION', data: 'x' }])), + ).toMatch(/backslash or colon/); + }); + + it.each([['a//b.md'], ['a/./b.md']])( + 'refuses the empty or "." segment in a selected %s', + (rel) => { + expect( + refusal(githubArchive([{ name: at(rel), data: 'x' }]), opts([rel])), + ).toMatch(/empty or "\." path segment/); + }, + ); + + it('refuses a selected file under a second root', () => { + expect( + refusal( + githubArchive([KEEP, { name: 'elsewhere/MIN_CLI', data: '1.0.0' }]), + opts(['SKILLS_VERSION', 'MIN_CLI']), + ), + ).toMatch(/more than one root component/); + }); + + it('refuses a selected path the archive holds twice', () => { + const dest = fresh(); + const message = refusal(githubArchive([KEEP, KEEP]), opts(), dest); + expect(message).toMatch(/holds this path twice/); + expect(message).toContain(at('SKILLS_VERSION')); + }); + // PHARN-17: a name a terminal would interpret is refused before any other + // rule, so it is neither installed nor echoed raw by a refusal message. + // Names are latin1 in the header, so a UTF-8 U+202E is written as its bytes. it.each([ - [ - 'an ESC sequence in the name', - { name: `pharn-oss-abc1234/n${ESC}[2K\r${ESC}[32mOK` }, - ], + ['an ESC sequence in the root', { name: `d${ESC}[2K\r/SKILLS_VERSION` }], [ 'a right-to-left override', - { name: utf8AsLatin1('pharn-oss-abc1234/evil\u202egnp.md') }, + { name: utf8AsLatin1('evil\u202egnp/SKILLS_VERSION') }, ], [ 'a zero-width space', - { name: utf8AsLatin1('pharn-oss-abc1234/se\u200bcurity.md') }, + { name: utf8AsLatin1('se\u200bcurity/SKILLS_VERSION') }, ], [ 'a control byte in the ustar prefix', - { name: 'f.md', prefix: `pharn-oss-abc1234/d${ESC}x` }, + { name: 'SKILLS_VERSION', prefix: `d${ESC}x` }, ], - // CORE-170: the one unsafe set now holds the two line separators too. [ 'a line separator (U+2028)', - { name: utf8AsLatin1('pharn-oss-abc1234/a\u2028b.md') }, + { name: utf8AsLatin1('a\u2028b/SKILLS_VERSION') }, + ], + [ + 'a leading byte-order mark, never stripped', + { name: utf8AsLatin1('\ufeffroot/SKILLS_VERSION') }, ], ])('refuses %s, naming it without the raw character', (_label, entry) => { - let message = ''; - try { - extractTar(githubArchive([entry]), tmp.path(), LIMITS); - } catch (err) { - expect(err).toBeInstanceOf(TarExtractError); - message = (err as Error).message; - } + const dest = fresh(); + const message = refusal( + tar([GLOBAL_HEADER, { ...entry, data: 'x' }]), + opts(), + dest, + ); expect(message).toMatch(/control or format character/); expect(hasUnsafeChars(message)).toBe(false); + expect(treeOf(dest)).toEqual([]); }); - it('refuses an unsafe name even on an unsupported-type entry (path judged first)', () => { - expect(() => - extractTar( - githubArchive([{ name: `pharn-oss-abc1234/n${ESC}[32mOK`, type: '2' }]), - tmp.path(), - LIMITS, - ), - ).toThrow(/control or format character/); + it('judges the path before the type', () => { + expect( + refusal(tar([{ name: `n${ESC}[32mOK/SKILLS_VERSION`, type: '2' }])), + ).toMatch(/control or format character/); }); it('renders an unprintable typeflag as its code, not the raw byte', () => { - let message = ''; - try { - extractTar( - githubArchive([{ name: 'pharn-oss-abc1234/x', type: ESC }]), - tmp.path(), - LIMITS, - ); - } catch (err) { - message = (err as Error).message; - } + const message = refusal( + githubArchive([{ name: at('SKILLS_VERSION'), type: ESC }]), + ); expect(message).toContain('unsupported type 0x1b'); expect(message).not.toContain(ESC); }); - it('still extracts an ordinary non-ASCII name', () => { - extractTar( - githubArchive([ - { name: utf8AsLatin1('pharn-oss-abc1234/café.md'), data: 'ok' }, - ]), - tmp.path(), - LIMITS, - ); - }); - - // tar-entry-names. The check used to judge a DIFFERENT string than the one - // written — the UTF-8 decoding of latin1-read bytes, against the latin1 string - // itself — so a raw C1 byte passed as U+FFFD and landed on disk as U+009B, and - // every non-ASCII name landed garbled. Names are now decoded once, strictly, - // and the check, the path rules and the write share that one string. Asserted - // on the BYTES the filesystem returns, not on a decoded string. - const onDisk = (dir: string): Buffer[] => - readdirSync(dir, { encoding: 'buffer' }); - - it('writes a non-ASCII name as exactly the archive bytes', () => { - const dest = tmp.path(); - extractTar( - githubArchive([ - { name: utf8AsLatin1('pharn-oss-abc1234/a—b.md'), data: 'ok' }, - ]), - dest, - LIMITS, - ); - expect(onDisk(dest)).toEqual([Buffer.from('a—b.md', 'utf8')]); - }); - it.each([ - ['a raw C1 byte', 'pharn-oss-abc1234/evil-\x9b2J.md'], - ['a truncated UTF-8 sequence', 'pharn-oss-abc1234/bad-\xe2\x80.md'], - ['an overlong encoding of "/"', 'pharn-oss-abc1234/slash-\xc0\xaf.md'], + ['a raw C1 byte', 'pharn-oss-\x9b2J/SKILLS_VERSION'], + ['a truncated UTF-8 sequence', 'bad-\xe2\x80/SKILLS_VERSION'], + ['an overlong encoding', 'slash-\xc0\xaf/SKILLS_VERSION'], ])( - 'refuses a name holding %s — not valid UTF-8 — writing nothing', + 'refuses a root holding %s — not valid UTF-8 — writing nothing', (_label, name) => { - const dest = tmp.path(); - let message = ''; - try { - extractTar(githubArchive([{ name, data: 'x' }]), dest, LIMITS); - } catch (err) { - expect(err).toBeInstanceOf(TarExtractError); - message = (err as Error).message; - } + const dest = fresh(); + const message = refusal( + tar([GLOBAL_HEADER, { name, data: 'x' }]), + opts(), + dest, + ); expect(message).toMatch(/not valid UTF-8/); expect(hasUnsafeChars(message)).toBe(false); - expect(onDisk(dest)).toEqual([]); + expect(treeOf(dest)).toEqual([]); }, ); it('refuses invalid UTF-8 in the ustar prefix too', () => { - expect(() => - extractTar( - githubArchive([{ name: 'f.md', prefix: 'pharn-oss-abc1234/d\x9b' }]), - tmp.path(), - LIMITS, - ), - ).toThrow(/not valid UTF-8/); - }); - - // A decoder's DEFAULT drops a leading byte-order mark: the name would be - // written under a different name than the archive holds instead of refused. - it('refuses a name field that starts with a byte-order mark, never strips it', () => { - const dest = tmp.path(); - expect(() => - extractTar( - githubArchive([ - { - name: utf8AsLatin1('\ufeff' + 'f.md'), // BOM, then `f.md` - prefix: 'pharn-oss-abc1234', - data: 'x', - }, - ]), - dest, - LIMITS, - ), - ).toThrow(/control or format character/); - expect(onDisk(dest)).toEqual([]); - }); - - it('counts every pax global header toward the entry cap', () => { - const empty: EntryInit = { name: 'pax_global_header', type: 'g', data: '' }; - expect(() => - extractTar( - tar([ - empty, - empty, - empty, - empty, - { name: 'pharn-oss-abc1234/', type: '5' }, - ]), - tmp.path(), - { maxEntries: 3, maxTotalBytes: 1024 }, - ), - ).toThrow(/more than 3 entries/); - }); - - it('names a malformed numeric field escaped — no raw newline reaches the message', () => { - const bad = header({ name: 'pharn-oss-abc1234/f.txt' }); - bad.fill(0, 124, 136); // the size field - bad.write('1\n Done', 124, 12, 'latin1'); - bad.write(' ', 148, 8, 'latin1'); // re-checksum over the forged field - let sum = 0; - for (const byte of bad) sum += byte; - bad.write(sum.toString(8).padStart(6, '0') + '\0 ', 148, 8, 'latin1'); - - let message = ''; - try { - extractTar( - Buffer.concat([bad, Buffer.alloc(BLOCK * 2)]), - tmp.path(), - LIMITS, - ); - } catch (err) { - message = (err as Error).message; - } - expect(message).toMatch(/non-octal numeric field/); - expect(message).not.toContain('\n'); - expect(message).toContain('1\\x0a Done'); + expect( + refusal(tar([{ name: 'SKILLS_VERSION', prefix: 'd\x9b', data: 'x' }])), + ).toMatch(/not valid UTF-8/); }); +}); - // PHARN-18: strict framing. Each case was ACCEPTED by the base source. - const refusal = (archive: Buffer): string => { - try { - extractTar(archive, tmp.path(), LIMITS); - } catch (err) { - expect(err).toBeInstanceOf(TarExtractError); - return (err as Error).message; - } - return 'accepted'; - }; - +// Framing is checked on EVERY header: without it the walk cannot find the next +// header, so these stay refusals whatever the entry is. +describe('extractTar — framing, on every header', () => { it('refuses entries hidden after a zero block mid-archive', () => { const archive = Buffer.concat([ - tar([GLOBAL_HEADER, { name: 'pharn-oss-abc1234/', type: '5' }]).subarray( + tar([GLOBAL_HEADER, { name: `${ROOT}/`, type: '5' }]).subarray( 0, -BLOCK, // keep ONE zero block, then keep going ), - tar([{ name: 'pharn-oss-abc1234/hidden.md', data: 'x' }]), + tar([KEEP]), ]); expect(refusal(archive)).toMatch(/data after its end-of-archive marker/); }); @@ -596,88 +594,64 @@ describe('extractTar', () => { }); it('refuses an archive with no end-of-archive marker', () => { - const archive = githubArchive([ - { name: 'pharn-oss-abc1234/a.md', data: 'x' }, - ]).subarray(0, -2 * BLOCK); + const archive = githubArchive([KEEP]).subarray(0, -2 * BLOCK); expect(refusal(archive)).toMatch(/no end-of-archive marker/); }); - it('refuses a header without the ustar magic', () => { - const archive = githubArchive([ - { name: 'pharn-oss-abc1234/a.md', data: 'x' }, + it('refuses an archive cut inside a payload, writing no partial file', () => { + const dest = fresh(); + const full = githubArchive([ + { name: at('SKILLS_VERSION'), data: 'x'.repeat(600) }, ]); + // Header blocks 0-2, then 512 of the 600 payload bytes. + expect(refusal(full.subarray(0, BLOCK * 4), opts(), dest)).toMatch( + /runs past the end of the archive — truncated/, + ); + expect(treeOf(dest)).toEqual([]); + }); + + it('refuses an unselected header without the ustar magic', () => { + const archive = githubArchive([{ name: at('a.md'), data: 'x' }, KEEP]); // Blank the magic of the third header and re-seal its checksum, so the // magic check — not the checksum — is what refuses it. - const at = 2 * BLOCK; - archive.fill(0, at + 257, at + 263); - archive.write(' ', at + 148, 8, 'latin1'); + const off = 2 * BLOCK; + archive.fill(0, off + 257, off + 263); + archive.write(' ', off + 148, 8, 'latin1'); let sum = 0; - for (const byte of archive.subarray(at, at + BLOCK)) sum += byte; + for (const byte of archive.subarray(off, off + BLOCK)) sum += byte; archive.write( sum.toString(8).padStart(6, '0') + '\0 ', - at + 148, + off + 148, 8, 'latin1', ); expect(refusal(archive)).toMatch(/missing "ustar" magic/); }); - it.each([['pharn-oss-abc1234/a//b.md'], ['pharn-oss-abc1234/a/./b.md']])( - 'refuses the empty or "." segment in %s', - (name) => { - expect(refusal(githubArchive([{ name, data: 'x' }]))).toMatch( - /empty or "\." path segment/, - ); - }, - ); - - it('still extracts the codeload shape (one small global header, zero tail)', () => { + it('refuses an unselected header whose checksum does not match', () => { expect( refusal( githubArchive([ - { name: 'pharn-oss-abc1234/SKILLS_VERSION', data: '1\n' }, + { name: at('f.txt'), data: 'x', forgeChecksum: '000000\0 ' }, + KEEP, ]), ), - ).toBe('accepted'); - }); - - it('enforces the entry-count cap', () => { - const many = Array.from({ length: 5 }, (_, i) => ({ - name: `pharn-oss-abc1234/f${i}.txt`, - data: 'x', - })); - expect(() => - extractTar(githubArchive(many), tmp.path(), { - maxEntries: 3, - maxTotalBytes: 1024, - }), - ).toThrow(/more than 3 entries/); + ).toMatch(/checksum/); }); - it('rejects a truncated archive', () => { - const full = githubArchive([ - { name: 'pharn-oss-abc1234/f.txt', data: 'x'.repeat(600) }, - ]); - // Cut inside the file payload: the header promises more than is there. - expect(() => - extractTar(full.subarray(0, BLOCK * 4), tmp.path(), LIMITS), - ).toThrow(/truncated/); - }); + it('names a malformed numeric field escaped — no raw newline reaches the message', () => { + const bad = header({ name: at('f.txt') }); + bad.fill(0, 124, 136); // the size field + bad.write('1\n Done', 124, 12, 'latin1'); + bad.write(' ', 148, 8, 'latin1'); // re-checksum over the forged field + let sum = 0; + for (const byte of bad) sum += byte; + bad.write(sum.toString(8).padStart(6, '0') + '\0 ', 148, 8, 'latin1'); - it('rejects a header whose checksum does not match', () => { - expect(() => - extractTar( - githubArchive([ - { - name: 'pharn-oss-abc1234/f.txt', - data: 'x', - forgeChecksum: '000000\0 ', - }, - ]), - tmp.path(), - LIMITS, - ), - ).toThrow(/checksum/); + const message = refusal(Buffer.concat([bad, Buffer.alloc(BLOCK * 2)])); + expect(message).toMatch(/non-octal numeric field/); + expect(message).not.toContain('\n'); + expect(message).toContain('1\\x0a Done'); }); // A GNU base-256 field sets the high bit of its first byte. No such byte is @@ -692,124 +666,184 @@ describe('extractTar', () => { 'rejects a size field whose first byte is %s (GNU base-256), never misreading it', (_label, byte) => { const bytes = Buffer.concat([ - header({ name: 'pharn-oss-abc1234/', type: '5' }), - header({ - name: 'pharn-oss-abc1234/f.txt', - data: 'x', - forgeSizeByte: byte, - }), + header({ name: `${ROOT}/`, type: '5' }), + header({ name: at('f.txt'), data: 'x', forgeSizeByte: byte }), Buffer.alloc(BLOCK), Buffer.alloc(BLOCK * 2), ]); - expect(() => extractTar(bytes, tmp.path(), LIMITS)).toThrow( - /non-octal numeric field/, - ); + expect(refusal(bytes)).toMatch(/non-octal numeric field/); }, ); +}); - // CORE-173: `\` and `:` in an entry name. POSIX writes `a\..\..\evil` as - // ONE literal file name; win32 would read the same bytes as a path. pharn-oss - // ships neither character, so either is refused, naming the entry. - it.each([ - ['a backslash path', 'pharn-oss-abc1234/a\\..\\..\\evil'], - ['a drive letter', 'pharn-oss-abc1234/C:/x'], - ['a colon in a name', 'pharn-oss-abc1234/a:b.md'], - ['a backslash in a directory segment', 'pharn-oss-abc1234/d\\e/f.md'], - ])('refuses %s, writing nothing', (_label, name) => { - const dest = tmp.path(); - let message = ''; - try { - extractTar(githubArchive([{ name, data: 'x' }]), dest, LIMITS); - } catch (err) { - expect(err).toBeInstanceOf(TarExtractError); - message = (err as Error).message; - } - expect(message).toMatch(/backslash or colon/); - expect(message).toContain(name); - expect(readdirSync(dest)).toEqual([]); +describe('extractTar — caps', () => { + it('counts every header toward maxHeaders: global, unselected and selected', () => { + const empty: EntryInit = { name: 'pax_global_header', type: 'g', data: '' }; + const limits = { ...LIMITS, maxHeaders: 3 }; + expect( + refusal(tar([empty, empty, empty, empty]), opts([], limits)), + ).toMatch(/more than 3 headers/); + expect( + refusal( + githubArchive([{ name: at('a'), data: 'x' }, KEEP]), + opts(['SKILLS_VERSION'], limits), + ), + ).toMatch(/more than 3 headers/); + expect( + refusal(githubArchive([KEEP]), opts(['SKILLS_VERSION'], limits)), + ).toBe('accepted'); }); - it('refuses a backslash or colon in the ustar prefix too', () => { - expect(() => - extractTar( - githubArchive([{ name: 'f.md', prefix: 'pharn-oss-abc1234/x:y' }]), - tmp.path(), - LIMITS, + it('refuses selected files whose sizes exceed maxWrittenBytes', () => { + const dest = fresh(); + const message = refusal( + githubArchive([KEEP, { name: at('big.md'), data: 'x'.repeat(600) }]), + opts(['SKILLS_VERSION', 'big.md'], { ...LIMITS, maxWrittenBytes: 100 }), + dest, + ); + expect(message).toMatch(/exceed 100 bytes/); + // Refused at the header, before the payload is collected. + expect(treeOf(dest)).toEqual(['SKILLS_VERSION']); + }); + + it('refuses a stream over maxScannedBytes', () => { + expect( + refusal( + githubArchive([{ name: at('pad'), data: 'x'.repeat(4096) }, KEEP]), + opts(['SKILLS_VERSION'], { ...LIMITS, maxScannedBytes: 2048 }), ), - ).toThrow(/backslash or colon/); + ).toMatch(/decompresses to more than 2048 bytes/); }); }); -describe('extractTarGz', () => { - const tmp = useTmpDir(); +// Production chunks (gunzip's 16 KiB) are block-aligned, so a header or payload +// straddling two chunks never happens there; it is forced here. +describe('extractTar — chunk boundaries', () => { + const archive = githubArchive([ + { name: at('a.md'), data: 'a'.repeat(700) }, + KEEP, + { name: at('.claude/skills/x'), type: '2' }, + { name: at('d/b.md'), data: 'b'.repeat(1300) }, + { name: at('MIN_CLI'), data: '' }, + ]); + const select = ['a.md', 'SKILLS_VERSION', 'd/b.md', 'MIN_CLI']; + + function chunked(bytes: Buffer, size: number): Buffer[] { + const out: Buffer[] = []; + for (let i = 0; i < bytes.length; i += size) + out.push(bytes.subarray(i, i + size)); + return out; + } + + function snapshot(dir: string): Record { + const out: Record = {}; + for (const rel of treeOf(dir)) { + if (lstatSync(join(dir, rel)).isFile()) + out[rel] = readFileSync(join(dir, rel), 'utf8'); + } + return out; + } + + it.each([[1], [7], [511], [513], [1500]])( + 'gives the same tree in %i-byte chunks as in one buffer', + (size) => { + const whole = fresh(); + const parts = fresh(); + const a = extractTar(archive, whole, opts(select)); + const b = extractTar(chunked(archive, size), parts, opts(select)); + expect(snapshot(parts)).toEqual(snapshot(whole)); + expect(b).toEqual(a); + expect(Object.keys(snapshot(whole)).sort()).toEqual([...select].sort()); + }, + ); + + it('still refuses data after the end marker when it arrives in a later chunk', () => { + const tail = Buffer.concat([archive, Buffer.alloc(BLOCK)]); + tail[tail.length - 1] = 1; + expect(() => extractTar(chunked(tail, 300), fresh(), opts(select))).toThrow( + /data after its end-of-archive marker/, + ); + }); +}); - it('decompresses and extracts', () => { - const dest = tmp.path(); - extractTarGz( - gzipSync(githubArchive([{ name: 'pharn-oss-abc1234/v', data: '1.0.0' }])), +describe('extractTarGz', () => { + it('decompresses and extracts the selected files', async () => { + const dest = fresh(); + const result = await extractTarGz( + gzipSync(githubArchive([KEEP, { name: at('other'), data: 'x' }])), dest, - LIMITS, + opts(), ); - expect(readFileSync(join(dest, 'v'), 'utf8')).toBe('1.0.0'); + expect(treeOf(dest)).toEqual(['SKILLS_VERSION']); + expect(result.root).toBe(ROOT); }); - it('surfaces corrupt gzip as a TarExtractError', () => { - expect(() => - extractTarGz(Buffer.from('not a gzip stream'), tmp.path(), LIMITS), - ).toThrow(TarExtractError); + it('surfaces corrupt gzip as a TarExtractError', async () => { + await expect( + extractTarGz(Buffer.from('not a gzip stream'), fresh(), opts()), + ).rejects.toThrow(/could not decompress the fetched archive/); }); - it('bounds the bytes written by the decompressed size (maxTotalBytes)', () => { - // Moved from extractTar: the decompressed tar holds every byte an entry - // writes, so gunzip's maxOutputLength is the one total-bytes bound. - expect(() => - extractTarGz( - gzipSync( - githubArchive([ - { name: 'pharn-oss-abc1234/big.txt', data: 'x'.repeat(600) }, - ]), - ), - tmp.path(), - { maxEntries: 100, maxTotalBytes: 100 }, - ), - ).toThrow(/could not decompress/); + it('rethrows a refusal from the walk as itself, not as a gzip failure', async () => { + const err = await extractTarGz( + gzipSync(githubArchive([{ name: at('SKILLS_VERSION'), type: '2' }])), + fresh(), + opts(), + ).catch((e: unknown) => e); + expect(err).toBeInstanceOf(TarExtractError); + expect((err as Error).message).toMatch(/unsupported type '2'/); + }); + + it('refuses a truncated gzip stream', async () => { + const gz = gzipSync(githubArchive([KEEP])); + await expect( + extractTarGz(gz.subarray(0, gz.length - 20), fresh(), opts()), + ).rejects.toThrow(TarExtractError); }); - it('caps the DECOMPRESSED size, so a zip bomb is bounded', () => { - // Neither content-length nor the compressed size bounds this: 1 MB of zeros - // gzips to about a kilobyte. + it('bounds a compression bomb by maxScannedBytes', async () => { + // Neither content-length nor the compressed size bounds this: 4 MB of + // zeros gzips to a few kilobytes. const bomb = gzipSync( githubArchive([ - { name: 'pharn-oss-abc1234/bomb', data: '\0'.repeat(1024 * 1024) }, + { name: at('bomb'), data: '\0'.repeat(4 * 1024 * 1024) }, + KEEP, ]), ); expect(bomb.length).toBeLessThan(64 * 1024); - expect(() => - extractTarGz(bomb, tmp.path(), { maxEntries: 10, maxTotalBytes: 4096 }), - ).toThrow(TarExtractError); + await expect( + extractTarGz( + bomb, + fresh(), + opts(['SKILLS_VERSION'], { ...LIMITS, maxScannedBytes: 65536 }), + ), + ).rejects.toThrow(/decompresses to more than 65536 bytes/); + }); + + it('installs from a repo larger than maxWrittenBytes when the selected files fit', async () => { + const dest = fresh(); + await extractTarGz( + gzipSync( + githubArchive([ + { name: at('.dev/huge'), data: 'z'.repeat(1024 * 1024) }, + KEEP, + ]), + ), + dest, + opts(['SKILLS_VERSION'], { ...LIMITS, maxWrittenBytes: 4096 }), + ); + expect(treeOf(dest)).toEqual(['SKILLS_VERSION']); }); }); -// CORE-173: the invariant fetchRepo states and clone-side readers rely on — the -// extracted tree holds only regular files and directories. Asserted on what is -// ON DISK (lstat), over the real codeload shape and over the partial tree a -// refused archive leaves behind before fetchRepo removes it. +// The invariant fetchRepo states and clone-side readers rely on: the extracted +// tree holds only regular files and directories. Asserted on what is ON DISK +// (lstat), over the codeload shape with every kind of entry outside the +// selection. describe('the extracted tree holds only regular files and directories', () => { - const tmp = useTmpDir(); - - /** Every path under `dir` that lstat says is neither a file nor a directory. */ - function nonFileOrDir(dir: string): string[] { - const odd: string[] = []; - for (const rel of readdirSync(dir, { recursive: true }) as string[]) { - const st = lstatSync(join(dir, rel)); - if (!st.isFile() && !st.isDirectory()) odd.push(rel); - } - return odd; - } - - it('over the codeload shape', () => { - const dest = tmp.path(); - extractTarGz( + it('over the codeload shape', async () => { + const dest = fresh(); + await extractTarGz( codeloadArchive('0123456789abcdef0123456789abcdef01234567', { SKILLS_VERSION: '1.0.0\n', 'pharn-review/a11y/a11y.md': '# a11y\n', @@ -817,34 +851,31 @@ describe('the extracted tree holds only regular files and directories', () => { '.claude/settings.json': '{}\n', }), dest, - LIMITS, + opts([ + 'SKILLS_VERSION', + 'pharn-review/a11y/a11y.md', + '.claude/hooks/h.cjs', + '.claude/settings.json', + ]), ); - expect(readdirSync(dest, { recursive: true }).length).toBeGreaterThan(4); + expect(treeOf(dest).length).toBeGreaterThan(4); expect(nonFileOrDir(dest)).toEqual([]); }); - it.each([ - ['a symlink', '2'], - ['a hard link', '1'], - ['a fifo', '6'], - ['a pax extended header', 'x'], - ])( - 'in the partial tree left when %s entry is refused part-way', - (_label, type) => { - const dest = tmp.path(); - expect(() => - extractTar( - githubArchive([ - { name: 'pharn-oss-abc1234/d/', type: '5' }, - { name: 'pharn-oss-abc1234/d/before.md', data: 'x' }, - { name: 'pharn-oss-abc1234/d/odd', type }, - ]), - dest, - LIMITS, - ), - ).toThrow(TarExtractError); - expect(readFileSync(join(dest, 'd/before.md'), 'utf8')).toBe('x'); - expect(nonFileOrDir(dest)).toEqual([]); - }, - ); + it('in the partial tree a refusal leaves behind', () => { + const dest = fresh(); + expect(() => + extractTar( + githubArchive([ + { name: at('d/before.md'), data: 'x' }, + { name: at('d/skipped'), type: '2' }, + { name: at('d/odd'), type: '2' }, + ]), + dest, + opts(['d/before.md', 'd/odd']), + ), + ).toThrow(TarExtractError); + expect(readFileSync(join(dest, 'd/before.md'), 'utf8')).toBe('x'); + expect(nonFileOrDir(dest)).toEqual([]); + }); }); diff --git a/tests/upstream-manifest.test.ts b/tests/upstream-manifest.test.ts index 04e09490..bf564975 100644 --- a/tests/upstream-manifest.test.ts +++ b/tests/upstream-manifest.test.ts @@ -212,7 +212,26 @@ describe('readUpstreamManifest — the one parser', () => { expect(msg).toContain('Upgrade pharn'); }); - it('refuses the pharn layout when the tree lacks its marker', () => { + it('refuses the pharn layout when the tree lacks its marker and lists nothing there', () => { + const tree = upstreamTree('7.20.0'); + const dir = writeTree( + withManifest( + Object.fromEntries( + Object.entries(tree).filter( + ([p]) => !p.startsWith('pharn/pharn-contracts/'), + ), + ), + ), + ); + expect(() => readUpstreamManifest(dir)).toThrow( + /has no pharn\/pharn-contracts and it lists no file there/, + ); + }); + + // CORE-386: the extractor validates the manifest BETWEEN its passes, before + // any listed file is written, so a listed file under the marker stands in + // for it. A listed file the tree then lacks is the hash check's to refuse. + it('accepts a marker the manifest lists before the tree holds it; the hash check refuses it if it never arrives', () => { const tree = manifestTree('7.20.0'); const dir = writeTree( Object.fromEntries( @@ -221,8 +240,9 @@ describe('readUpstreamManifest — the one parser', () => { ), ), ); - expect(() => readUpstreamManifest(dir)).toThrow( - /has no pharn\/pharn-contracts/, + const manifest = readUpstreamManifest(dir); + expect(() => verifyUpstreamManifest(dir, manifest)).toThrow( + /declares pharn\/pharn-contracts\/.*which the tree does not ship as a file/, ); }); From 6c3d849c73ac62924aee8cf4e4c5643307d748af Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Przemys=C5=82aw=20Galarowicz?= Date: Wed, 25 Nov 2026 17:37:56 +0100 Subject: [PATCH 2/4] chore(release): 0.21.6; keep the base test names in tar-extract tests (CORE-386) Bump to 0.21.6 (epic-coordinated) and move the CORE-386 entry into the [0.21.6] CHANGELOG section; v0.21.5 joins KNOWN_TAGS. pharn-ci TI02 read the restructured tar-extract tests as removals. The tests keep their base names now (the same behaviour, re-expressed against the selection), with the old merged g-header and BOM cases split back out. The init test is back to its base text: the new marker message still contains it. Co-Authored-By: Claude Opus 5.5 --- .../core-386-unpack-listed-paths-only/SHIP.md | 4 +- CHANGELOG.md | 5 +- package-lock.json | 4 +- package.json | 2 +- tests/commands/init.test.ts | 7 +- tests/release-consistency.test.ts | 1 + tests/tar-extract.test.ts | 300 ++++++++++++++---- tests/upstream-manifest.test.ts | 2 +- 8 files changed, 252 insertions(+), 73 deletions(-) diff --git a/.dev/features/core-386-unpack-listed-paths-only/SHIP.md b/.dev/features/core-386-unpack-listed-paths-only/SHIP.md index 3e0b2e7f..d8d8125e 100644 --- a/.dev/features/core-386-unpack-listed-paths-only/SHIP.md +++ b/.dev/features/core-386-unpack-listed-paths-only/SHIP.md @@ -9,7 +9,9 @@ | verify | `PASS` (verify-report.json) | | review | 0 floor-gate findings, 4 advisory (minor) — see REVIEW.md | -GATE 2 delegated to the lead: open the PR, drive CI green, do not merge. THREAT-MODEL.md was patched by the user with +GATE 2 delegated to the lead: open the PR, drive CI green, do not merge. The lead later set the version: 0.21.6 +(epic-coordinated), so `package.json` is bumped and the CHANGELOG entry is the `[0.21.6]` section. pharn-ci's +TI02 on the first push (renamed tests in `tests/tar-extract.test.ts`) was answered by keeping the base test names. THREAT-MODEL.md was patched by the user with the script this run wrote (`$SP/patches/CORE-386.py`, since deleted). Chain ran; the named floor verdicts are as shown — this is NOT a judgment that the increment is good or wise; that is diff --git a/CHANGELOG.md b/CHANGELOG.md index 68d0681b..18811395 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,8 @@ Releases 0.4.0 and older are in [CHANGELOG-ARCHIVE.md](CHANGELOG-ARCHIVE.md). ## [Unreleased] +## [0.21.6] — 2026-11-25 + ### Fixed - **`pharn init`, `add`, `update` and `status` work again against pharn-oss v7.25.3 and later.** Those releases commit seven symlinks under `.claude/skills/`, and `pharn` refused any symlink anywhere in the downloaded archive, so every install and update failed on every channel. `pharn` now unpacks only the files pharn-oss's `pharn-install.json` lists, plus the four it reads itself (`pharn-install.json`, `SKILLS_VERSION`, `MIN_CLI`, `.claude/settings.json`); every other archive entry is skipped and never written. A symlink, hard link, pax header, long or `:` name elsewhere in pharn-oss, or pharn-oss growing past 20,000 entries or 128 MB, no longer stops an install. The archive is decompressed as a stream, so the 128 MB cap now applies to the bytes `pharn` writes, not to the whole repository. What is installed is unchanged. @@ -527,7 +529,8 @@ _Never released: 0.9.0 followed on the same day, so `0.8.0` was neither tagged n matcher that silently stopped matching, or a comparator read in the wrong direction, would otherwise leave every assertion green. -[Unreleased]: https://github.com/pharn-dev/pharn-cli/compare/v0.21.5...HEAD +[Unreleased]: https://github.com/pharn-dev/pharn-cli/compare/v0.21.6...HEAD +[0.21.6]: https://github.com/pharn-dev/pharn-cli/compare/v0.21.5...v0.21.6 [0.21.5]: https://github.com/pharn-dev/pharn-cli/compare/v0.21.4...v0.21.5 [0.21.4]: https://github.com/pharn-dev/pharn-cli/compare/v0.21.3...v0.21.4 [0.21.3]: https://github.com/pharn-dev/pharn-cli/compare/v0.21.2...v0.21.3 diff --git a/package-lock.json b/package-lock.json index c23d57c3..0af6d1c4 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@pharn-dev/pharn", - "version": "0.21.5", + "version": "0.21.6", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@pharn-dev/pharn", - "version": "0.21.5", + "version": "0.21.6", "license": "Apache-2.0", "dependencies": { "@clack/prompts": "^1.8.1", diff --git a/package.json b/package.json index fc5b550b..2b998f2b 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@pharn-dev/pharn", - "version": "0.21.5", + "version": "0.21.6", "description": "Install and update PHARN in any git project. PHARN gets features shipped right with Claude Code, with spec, plan and checks kept in Git.", "keywords": [ "claude-code", diff --git a/tests/commands/init.test.ts b/tests/commands/init.test.ts index 84c0d4da..ced7c9a7 100644 --- a/tests/commands/init.test.ts +++ b/tests/commands/init.test.ts @@ -971,14 +971,13 @@ describe('a fresh install', () => { }); // pharn/pharn-contracts is the pharn layout's marker: a manifest that - // declares that layout but lists nothing under it is refused, never - // installed (only listed files are extracted, so the tree would lack it). - it('a clone with no pharn-contracts is refused: its manifest declares a layout it does not list', async () => { + // declares that layout over a tree without it is refused, never installed. + it('a clone with no pharn-contracts is refused: its manifest declares a layout the tree lacks', async () => { delete upstream.tree['pharn/pharn-contracts/finding-shape.md']; const before = snapshot(); expect(await run(() => runInit({ yes: true }))).toBe(1); expect(errors()).toContain( - 'declares the pharn layout, but the tree has no pharn/pharn-contracts and it lists no file there', + 'declares the pharn layout, but the tree has no pharn/pharn-contracts', ); expect(snapshot()).toEqual(before); }); diff --git a/tests/release-consistency.test.ts b/tests/release-consistency.test.ts index 4f660114..4a8447b1 100644 --- a/tests/release-consistency.test.ts +++ b/tests/release-consistency.test.ts @@ -95,6 +95,7 @@ const KNOWN_TAGS: readonly string[] = [ 'v0.21.2', 'v0.21.3', 'v0.21.4', + 'v0.21.5', ]; // Sections with no tag at all, and so no link: 0.8.0 was bumped and superseded // by 0.9.0 on the same day, never tagged or published; 0.2.0 / 0.1.0 predate diff --git a/tests/tar-extract.test.ts b/tests/tar-extract.test.ts index 9a6caa86..6a44da9b 100644 --- a/tests/tar-extract.test.ts +++ b/tests/tar-extract.test.ts @@ -165,8 +165,9 @@ function refusal(archive: Buffer, options = opts(), dest = fresh()): string { const utf8AsLatin1 = (s: string): string => Buffer.from(s, 'utf8').toString('latin1'); -describe('extractTar — what is written', () => { - it('writes exactly the selected files, stripping one component', () => { +// What is written. +describe('extractTar', () => { + it('strips one component and writes the tree', () => { const dest = fresh(); const result = extractTar( githubArchive([ @@ -247,19 +248,11 @@ describe('extractTar — what is written', () => { }, ); - it.each([ - ['an unparseable payload', '7 comment=xyz\n'], - [ - 'metadata and vendor records', - paxRecord('mtime', '1700000000.0') + - paxRecord('SCHILY.xattr.user.thing', 'value'), - ], - ['a payload over two blocks', paxRecord('comment', 'q'.repeat(1200))], - ])('skips a pax global header carrying %s, unread', (_label, data) => { + it('skips a pax global header whose payload does not parse, unread', () => { const dest = fresh(); extractTar( tar([ - { name: 'pax_global_header', type: 'g', data }, + { name: 'pax_global_header', type: 'g', data: '7 comment=xyz\n' }, { name: `${ROOT}/`, type: '5' }, KEEP, ]), @@ -269,7 +262,86 @@ describe('extractTar — what is written', () => { expect(treeOf(dest)).toEqual(['SKILLS_VERSION']); }); - it('reassembles a selected path split across prefix and name', () => { + it('still skips the global header GitHub actually sends', () => { + const dest = fresh(); + extractTar(githubArchive([KEEP]), dest, opts()); + expect(readFileSync(join(dest, 'SKILLS_VERSION'), 'utf8')).toBe('1.0.0\n'); + expect(treeOf(dest)).toEqual(['SKILLS_VERSION']); + }); + + it('skips a global header carrying metadata and vendor records', () => { + const dest = fresh(); + extractTar( + tar([ + { + name: 'pax_global_header', + type: 'g', + data: + paxRecord('mtime', '1700000000.0') + + paxRecord('uname', 'root') + + paxRecord('SCHILY.xattr.user.thing', 'value'), + }, + { name: `${ROOT}/`, type: '5' }, + KEEP, + ]), + dest, + opts(), + ); + expect(treeOf(dest)).toEqual(['SKILLS_VERSION']); + }); + + it('skips a global header whose payload spans more than one block', () => { + const dest = fresh(); + const big = paxRecord('comment', 'q'.repeat(1200)); + expect(big.length).toBeGreaterThan(BLOCK * 2); + extractTar( + tar([ + { name: 'pax_global_header', type: 'g', data: big }, + { name: `${ROOT}/`, type: '5' }, + KEEP, + ]), + dest, + opts(), + ); + expect(treeOf(dest)).toEqual(['SKILLS_VERSION']); + }); + + it('still extracts the codeload shape (one small global header, zero tail)', () => { + expect(refusal(githubArchive([KEEP]))).toBe('accepted'); + }); + + it('skips a file with no component to strip, writing nothing for it', () => { + // Formerly refused. Its name has no `/`, so it can never be a selected + // path: it is skipped like any other entry pharn does not install. + const dest = fresh(); + extractTar( + tar([GLOBAL_HEADER, { name: 'SKILLS_VERSION', data: 'x' }]), + dest, + opts(), + ); + expect(treeOf(dest)).toEqual([]); + }); + + // tar-entry-names: a selected path is decoded once, strictly, and the check, + // the path rules and the write share that one string; asserted on the BYTES + // the filesystem returns. + it('writes a non-ASCII name as exactly the archive bytes', () => { + const dest = fresh(); + extractTar( + tar([ + GLOBAL_HEADER, + { name: utf8AsLatin1('pharn-oss-a—b/SKILLS_VERSION'), data: 'ok' }, + { name: utf8AsLatin1('pharn-oss-a—b/a—b.md'), data: 'unlisted' }, + ]), + dest, + opts(), + ); + expect(readdirSync(dest, { encoding: 'buffer' })).toEqual([ + Buffer.from('SKILLS_VERSION', 'utf8'), + ]); + }); + + it('reassembles a path split across prefix and name', () => { // ustar splits any path over 100 chars: the tail goes in `name`, the head // in `prefix`. Reading `name` alone would miss the file entirely. const deep = 'a'.repeat(40); @@ -289,7 +361,7 @@ describe('extractTar — what is written', () => { expect(readFileSync(join(dest, rel), 'utf8')).toBe('{}'); }); - it('accepts a non-ASCII root and writes the selected file below it', () => { + it('still extracts an ordinary non-ASCII name', () => { const dest = fresh(); extractTar( tar([ @@ -320,7 +392,8 @@ describe('extractTar — what is written', () => { // for — a symlink, or a file a pax record renamed — is missing from the tree, // and the manifest's sha256 check (verifyUpstreamManifest) refuses it loudly: // the silent loss degit allowed cannot recur. -describe('extractTar — outside the selection: skipped, nothing written', () => { +// Outside the selection: skipped, nothing written. +describe('extractTar', () => { it.each<[string, EntryInit[]]>([ ['a symlink', [{ name: at('.claude/skills/x'), type: '2' }]], ['a hard link', [{ name: at('link'), type: '1' }]], @@ -400,7 +473,8 @@ describe('extractTar — outside the selection: skipped, nothing written', () => }); }); -describe('extractTar — at a selected path: refused', () => { +// At a selected path: refused. +describe('extractTar', () => { it.each([ ['a symlink', '2'], ['a hard link', '1'], @@ -413,7 +487,7 @@ describe('extractTar — at a selected path: refused', () => { ['a GNU long name', 'L'], ['a GNU long link name', 'K'], ['an unknown type', '9'], - ])('refuses %s, naming the path and the rule', (_label, type) => { + ])('rejects %s entry outright, rather than skipping it', (_label, type) => { const dest = fresh(); const message = refusal( githubArchive([{ name: at('SKILLS_VERSION'), type }]), @@ -425,15 +499,20 @@ describe('extractTar — at a selected path: refused', () => { expect(treeOf(dest)).toEqual([]); }); + // An `x` header's records OVERRIDE the ustar header that follows it, so the + // listed file after one is refused whatever the payload: it is never read. it.each([ - ['a pax extended header', 'x'], - ['a GNU long name', 'L'], + ['path=', paxRecord('path', at('deep/elsewhere.txt'))], + ['size=', paxRecord('size', '8589934592')], + ['only benign metadata', paxRecord('mtime', '1700000000.0')], + ['an unparseable payload', '7 comment=xyz\n'], + ['an empty payload', ''], ])( - 'refuses a selected file that follows %s, whose records pharn does not honour', - (_label, type) => { + 'refuses a pax extended header carrying %s, on its typeflag alone', + (_label, data) => { const message = refusal( githubArchive([ - { name: at('PaxHeaders/SKILLS_VERSION'), type, data: '' }, + { name: at('PaxHeaders/SKILLS_VERSION'), type: 'x', data }, KEEP, ]), ); @@ -442,6 +521,14 @@ describe('extractTar — at a selected path: refused', () => { }, ); + it('refuses a selected file that follows a GNU long name, whose records pharn does not honour', () => { + expect( + refusal( + githubArchive([{ name: '././@LongLink', type: 'L', data: 'x' }, KEEP]), + ), + ).toMatch(/pax extended or GNU long-name header/); + }); + it('a pax global header between the extended header and the file does not lift the refusal', () => { expect( refusal( @@ -455,25 +542,58 @@ describe('extractTar — at a selected path: refused', () => { }); it.each([ - ['an absolute path', '/SKILLS_VERSION', /absolute path/], - ['a `..` root', '../SKILLS_VERSION', /escapes the archive root/], - ['a "." root', './SKILLS_VERSION', /no leading component/], - ['a drive-letter root', 'C:/SKILLS_VERSION', /backslash or colon/], - ['a backslash in the root', 'a\\b/SKILLS_VERSION', /backslash or colon/], - ])('refuses %s', (_label, name, rule) => { - const message = refusal(tar([GLOBAL_HEADER, { name, data: 'x' }])); - expect(message).toMatch(rule); + ['a `..` segment', '../SKILLS_VERSION', 'SKILLS_VERSION'], + [ + 'a deeper `..` segment', + `${ROOT}/nested/../../escape.txt`, + 'nested/../../escape.txt', + ], + ])('rejects %s', (_label, name, selected) => { + expect( + refusal(tar([GLOBAL_HEADER, { name, data: 'x' }]), opts([selected])), + ).toMatch(/escapes the archive root/); + }); + + it('rejects an absolute path', () => { + expect( + refusal(tar([GLOBAL_HEADER, { name: '/SKILLS_VERSION', data: 'x' }])), + ).toMatch(/absolute path/); + }); + + it('refuses a "." root', () => { + expect( + refusal(tar([GLOBAL_HEADER, { name: './SKILLS_VERSION', data: 'x' }])), + ).toMatch(/no leading component/); + }); + + // CORE-173: `\` and `:` in an entry name. POSIX writes `a\..\..\evil` as + // ONE literal file name; win32 would read the same bytes as a path. At a + // listed path either is refused, naming the entry. + it.each([ + ['a drive letter', 'C:/SKILLS_VERSION', 'SKILLS_VERSION'], + ['a backslash path', `${ROOT}/a\\..\\..\\evil`, 'a\\..\\..\\evil'], + ['a colon in a name', `${ROOT}/a:b.md`, 'a:b.md'], + ['a backslash in the root', 'a\\b/SKILLS_VERSION', 'SKILLS_VERSION'], + ])('refuses %s, writing nothing', (_label, name, selected) => { + const dest = fresh(); + const message = refusal( + tar([GLOBAL_HEADER, { name, data: 'x' }]), + opts([selected]), + dest, + ); + expect(message).toMatch(/backslash or colon/); expect(message).toContain(name); + expect(treeOf(dest)).toEqual([]); }); - it('refuses a colon in the ustar prefix too', () => { + it('refuses a backslash or colon in the ustar prefix too', () => { expect( refusal(tar([{ prefix: 'x:y', name: 'SKILLS_VERSION', data: 'x' }])), ).toMatch(/backslash or colon/); }); it.each([['a//b.md'], ['a/./b.md']])( - 'refuses the empty or "." segment in a selected %s', + 'refuses the empty or "." segment in %s', (rel) => { expect( refusal(githubArchive([{ name: at(rel), data: 'x' }]), opts([rel])), @@ -481,7 +601,7 @@ describe('extractTar — at a selected path: refused', () => { }, ); - it('refuses a selected file under a second root', () => { + it('rejects a second root component', () => { expect( refusal( githubArchive([KEEP, { name: 'elsewhere/MIN_CLI', data: '1.0.0' }]), @@ -518,10 +638,6 @@ describe('extractTar — at a selected path: refused', () => { 'a line separator (U+2028)', { name: utf8AsLatin1('a\u2028b/SKILLS_VERSION') }, ], - [ - 'a leading byte-order mark, never stripped', - { name: utf8AsLatin1('\ufeffroot/SKILLS_VERSION') }, - ], ])('refuses %s, naming it without the raw character', (_label, entry) => { const dest = fresh(); const message = refusal( @@ -534,7 +650,27 @@ describe('extractTar — at a selected path: refused', () => { expect(treeOf(dest)).toEqual([]); }); - it('judges the path before the type', () => { + // A decoder's DEFAULT drops a leading byte-order mark: the name would be + // written under a different name than the archive holds instead of refused. + it('refuses a name field that starts with a byte-order mark, never strips it', () => { + const dest = fresh(); + expect( + refusal( + tar([ + GLOBAL_HEADER, + { + name: utf8AsLatin1('\ufeff' + 'root/SKILLS_VERSION'), + data: 'x', + }, + ]), + opts(), + dest, + ), + ).toMatch(/control or format character/); + expect(treeOf(dest)).toEqual([]); + }); + + it('refuses an unsafe name even on an unsupported-type entry (path judged first)', () => { expect( refusal(tar([{ name: `n${ESC}[32mOK/SKILLS_VERSION`, type: '2' }])), ).toMatch(/control or format character/); @@ -553,7 +689,7 @@ describe('extractTar — at a selected path: refused', () => { ['a truncated UTF-8 sequence', 'bad-\xe2\x80/SKILLS_VERSION'], ['an overlong encoding', 'slash-\xc0\xaf/SKILLS_VERSION'], ])( - 'refuses a root holding %s — not valid UTF-8 — writing nothing', + 'refuses a name holding %s — not valid UTF-8 — writing nothing', (_label, name) => { const dest = fresh(); const message = refusal( @@ -576,7 +712,8 @@ describe('extractTar — at a selected path: refused', () => { // Framing is checked on EVERY header: without it the walk cannot find the next // header, so these stay refusals whatever the entry is. -describe('extractTar — framing, on every header', () => { +// Framing, on every header. +describe('extractTar', () => { it('refuses entries hidden after a zero block mid-archive', () => { const archive = Buffer.concat([ tar([GLOBAL_HEADER, { name: `${ROOT}/`, type: '5' }]).subarray( @@ -598,7 +735,7 @@ describe('extractTar — framing, on every header', () => { expect(refusal(archive)).toMatch(/no end-of-archive marker/); }); - it('refuses an archive cut inside a payload, writing no partial file', () => { + it('rejects a truncated archive', () => { const dest = fresh(); const full = githubArchive([ { name: at('SKILLS_VERSION'), data: 'x'.repeat(600) }, @@ -610,7 +747,7 @@ describe('extractTar — framing, on every header', () => { expect(treeOf(dest)).toEqual([]); }); - it('refuses an unselected header without the ustar magic', () => { + it('refuses a header without the ustar magic', () => { const archive = githubArchive([{ name: at('a.md'), data: 'x' }, KEEP]); // Blank the magic of the third header and re-seal its checksum, so the // magic check — not the checksum — is what refuses it. @@ -628,7 +765,7 @@ describe('extractTar — framing, on every header', () => { expect(refusal(archive)).toMatch(/missing "ustar" magic/); }); - it('refuses an unselected header whose checksum does not match', () => { + it('rejects a header whose checksum does not match', () => { expect( refusal( githubArchive([ @@ -676,8 +813,23 @@ describe('extractTar — framing, on every header', () => { ); }); -describe('extractTar — caps', () => { - it('counts every header toward maxHeaders: global, unselected and selected', () => { +// Caps. +describe('extractTar', () => { + it('enforces the entry-count cap', () => { + // Every header counts, selected or not: the cap bounds the walk itself. + const many = Array.from({ length: 5 }, (_, i) => ({ + name: at(`f${i}.txt`), + data: 'x', + })); + expect(() => + extractTar(githubArchive(many), fresh(), { + select: new Set(), + limits: { ...LIMITS, maxHeaders: 3 }, + }), + ).toThrow(/more than 3 headers/); + }); + + it('counts every pax global header toward the entry cap', () => { const empty: EntryInit = { name: 'pax_global_header', type: 'g', data: '' }; const limits = { ...LIMITS, maxHeaders: 3 }; expect( @@ -767,7 +919,7 @@ describe('extractTar — chunk boundaries', () => { }); describe('extractTarGz', () => { - it('decompresses and extracts the selected files', async () => { + it('decompresses and extracts', async () => { const dest = fresh(); const result = await extractTarGz( gzipSync(githubArchive([KEEP, { name: at('other'), data: 'x' }])), @@ -794,6 +946,20 @@ describe('extractTarGz', () => { expect((err as Error).message).toMatch(/unsupported type '2'/); }); + it('bounds the bytes written by the selected sizes (maxWrittenBytes)', async () => { + await expect( + extractTarGz( + gzipSync( + githubArchive([ + { name: at('SKILLS_VERSION'), data: 'x'.repeat(600) }, + ]), + ), + fresh(), + opts(['SKILLS_VERSION'], { ...LIMITS, maxWrittenBytes: 100 }), + ), + ).rejects.toThrow(/exceed 100 bytes/); + }); + it('refuses a truncated gzip stream', async () => { const gz = gzipSync(githubArchive([KEEP])); await expect( @@ -801,7 +967,7 @@ describe('extractTarGz', () => { ).rejects.toThrow(TarExtractError); }); - it('bounds a compression bomb by maxScannedBytes', async () => { + it('caps the DECOMPRESSED size, so a zip bomb is bounded', async () => { // Neither content-length nor the compressed size bounds this: 4 MB of // zeros gzips to a few kilobytes. const bomb = gzipSync( @@ -862,20 +1028,28 @@ describe('the extracted tree holds only regular files and directories', () => { expect(nonFileOrDir(dest)).toEqual([]); }); - it('in the partial tree a refusal leaves behind', () => { - const dest = fresh(); - expect(() => - extractTar( - githubArchive([ - { name: at('d/before.md'), data: 'x' }, - { name: at('d/skipped'), type: '2' }, - { name: at('d/odd'), type: '2' }, - ]), - dest, - opts(['d/before.md', 'd/odd']), - ), - ).toThrow(TarExtractError); - expect(readFileSync(join(dest, 'd/before.md'), 'utf8')).toBe('x'); - expect(nonFileOrDir(dest)).toEqual([]); - }); + it.each([ + ['a symlink', '2'], + ['a hard link', '1'], + ['a fifo', '6'], + ['a pax extended header', 'x'], + ])( + 'in the partial tree left when %s entry is refused part-way', + (_label, type) => { + const dest = fresh(); + expect(() => + extractTar( + githubArchive([ + { name: at('d/before.md'), data: 'x' }, + { name: at('d/skipped'), type }, + { name: at('d/odd'), type }, + ]), + dest, + opts(['d/before.md', 'd/odd']), + ), + ).toThrow(TarExtractError); + expect(readFileSync(join(dest, 'd/before.md'), 'utf8')).toBe('x'); + expect(nonFileOrDir(dest)).toEqual([]); + }, + ); }); diff --git a/tests/upstream-manifest.test.ts b/tests/upstream-manifest.test.ts index bf564975..dfd6b519 100644 --- a/tests/upstream-manifest.test.ts +++ b/tests/upstream-manifest.test.ts @@ -212,7 +212,7 @@ describe('readUpstreamManifest — the one parser', () => { expect(msg).toContain('Upgrade pharn'); }); - it('refuses the pharn layout when the tree lacks its marker and lists nothing there', () => { + it('refuses the pharn layout when the tree lacks its marker', () => { const tree = upstreamTree('7.20.0'); const dir = writeTree( withManifest( From 59b69fd27d364f457b91e8924cfc49d442deda9f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Przemys=C5=82aw=20Galarowicz?= Date: Wed, 25 Nov 2026 17:43:36 +0100 Subject: [PATCH 3/4] test(tar-extract): judge the base fixtures as selected paths (CORE-386) pharn-ci TI02 still read eight base tests as removed (computed it.each names match by body). They are back with their base bodies: a test-level LIMITS selects every path they use (latin1 keys), so each entry is judged by the full rules exactly as before. A rootless entry named like a selected path is now refused ("no path below the archive root") rather than skipped, which restores "rejects a file with no component to strip". CLAUDE.md no longer names pharn-install.json as a repo path (pharn-ci SETUP_STALE_SI02). Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 8 +- src/lib/tar-extract.ts | 18 +- tests/tar-extract.test.ts | 384 ++++++++++++++++++++++---------------- 3 files changed, 240 insertions(+), 170 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index f5c75475..52fc671d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -81,10 +81,10 @@ PHARN_DEBUG=1 npm run dev -- init # full error output for fetch/install failur - **Hard-link-safe writes.** Writes replace the file (`lib/atomic-write.ts`: exclusive temp, then `rename`), one by one via `applyWrites`; a new `settings.json` uses `COPYFILE_EXCL`. A hard link's other name is never written through. - **The clone is data.** `lib/repo.ts` is the only producer of a clone. `lib/tar-extract.ts` writes only the paths - `pharn-install.json` lists plus `CLONE_READ_FILES`, each a regular file under today's path rules; every other archive - entry is skipped and never written, whatever its type. It requires the tree's `pharn-install.json` (a tree without - one is refused) and verifies its raw sha256s before returning the tree, so a listed file that is missing or altered - fails; every manifest `dest` must pass `isPharnOwnedPath`, never the manifest's own `installRoots`. Nothing downloaded is ever executed: pharn-oss's `models` rules exist here as a pinned copy + the tree's install manifest (pharn-install.json) lists plus `CLONE_READ_FILES`, each a regular file under today's + path rules; every other archive entry is skipped and never written, whatever its type. A tree without that manifest + is refused, and its raw sha256s are verified before the tree is returned, so a listed file that is missing or + altered fails; every manifest `dest` must pass `isPharnOwnedPath`, never the manifest's own `installRoots`. Nothing downloaded is ever executed: pharn-oss's `models` rules exist here as a pinned copy (`lib/model-config.ts`), held to the vendored sha256-pinned checker by a differential test. - **Allowlists for untrusted names.** Untrusted names, versions, tags and manifest fields are checked against `CAPABILITY_NAME_RE`, `VERSION_RE`, `COPY_FILENAME_RE`, `COMMIT_RE`, `RELEASE_TAG_RE` and the role/applies enums. diff --git a/src/lib/tar-extract.ts b/src/lib/tar-extract.ts index 386dda88..4aeee3e1 100644 --- a/src/lib/tar-extract.ts +++ b/src/lib/tar-extract.ts @@ -146,18 +146,20 @@ function readPathField(block: Buffer, offset: number, length: number): string { } /** - * The selection key of a header: its raw `prefix`/`name` bytes (latin1, so + * Is this header at a selected path? Its raw `prefix`/`name` bytes (latin1, so * byte for byte) with everything up to the first `/` — the archive root — - * stripped; `null` when there is no `/`. Every selected path is ASCII, so an + * stripped are the key. A name with no `/` at all that IS a selected path is + * selected too, so a rootless copy of a listed file is refused (it has no + * component to strip) rather than skipped. Every selected path is ASCII, so an * exact membership test on these bytes is exact, and an unselected name is * never decoded, judged or printed. */ -function selectionKey(block: Buffer): string | null { +function isSelected(block: Buffer, select: ReadonlySet): boolean { const name = readString(block, OFF_NAME, LEN_NAME); const prefix = readString(block, OFF_PREFIX, LEN_PREFIX); const raw = prefix === '' ? name : `${prefix}/${name}`; const slash = raw.indexOf('/'); - return slash === -1 ? null : raw.slice(slash + 1); + return select.has(slash === -1 ? raw : raw.slice(slash + 1)); } /** @@ -265,6 +267,11 @@ function resolveEntryPath( `tar entry has no leading component: ${fullPath}`, ); } + if (segments.length === 1) { + throw new TarExtractError( + `tar entry has no path below the archive root: ${fullPath}`, + ); + } // One root, the same throughout: a second root would mean strip-1 flattens // two unrelated trees into one destination. if (expectedRoot !== null && root !== expectedRoot) { @@ -413,8 +420,7 @@ class TarWalker { if (MODIFIERS.has(typeflag)) this.modified = true; else if (typeflag !== 'g') this.modified = false; - const key = selectionKey(block); - if (key !== null && this.options.select.has(key)) { + if (isSelected(block, this.options.select)) { this.accept(block, typeflag, modified, size); } this.dataLeft = size; diff --git a/tests/tar-extract.test.ts b/tests/tar-extract.test.ts index 6a44da9b..23946806 100644 --- a/tests/tar-extract.test.ts +++ b/tests/tar-extract.test.ts @@ -24,7 +24,7 @@ import { codeloadArchive } from './support/tar-fixture.js'; // is written for it; at a selected path, every rule applies. const BLOCK = 512; -const LIMITS: TarLimits = { +const CAPS: TarLimits = { maxHeaders: 1000, maxScannedBytes: 8 * 1024 * 1024, maxWrittenBytes: 1024 * 1024, @@ -127,7 +127,7 @@ const KEEP: EntryInit = { name: at('SKILLS_VERSION'), data: '1.0.0\n' }; function opts( select: Iterable = ['SKILLS_VERSION'], - limits: TarLimits = LIMITS, + limits: TarLimits = CAPS, ): ExtractOptions { return { select: new Set(select), limits }; } @@ -165,6 +165,34 @@ function refusal(archive: Buffer, options = opts(), dest = fresh()): string { const utf8AsLatin1 = (s: string): string => Buffer.from(s, 'utf8').toString('latin1'); +/** + * The options the base-fixture cases extract with: every path they use is + * selected (keys are the raw header bytes as latin1, below the root), so each + * is judged by the full rules, as every entry was before CORE-386. + */ +const LIMITS: ExtractOptions = { + select: new Set([ + 'f.txt', + '../escape.txt', + 'nested/../../escape.txt', + 'loose.txt', + 'link', + `n${ESC}[2K\r${ESC}[32mOK`, + utf8AsLatin1('evil\u202egnp.md'), + utf8AsLatin1('se\u200bcurity.md'), + `d${ESC}x/f.md`, + utf8AsLatin1('a\u2028b.md'), + 'evil-\x9b2J.md', + 'bad-\xe2\x80.md', + 'slash-\xc0\xaf.md', + 'a\\..\\..\\evil', + 'C:/x', + 'a:b.md', + 'd\\e/f.md', + ]), + limits: CAPS, +}; + // What is written. describe('extractTar', () => { it('strips one component and writes the tree', () => { @@ -315,7 +343,7 @@ describe('extractTar', () => { // path: it is skipped like any other entry pharn does not install. const dest = fresh(); extractTar( - tar([GLOBAL_HEADER, { name: 'SKILLS_VERSION', data: 'x' }]), + tar([GLOBAL_HEADER, { name: 'loose.txt', data: 'x' }]), dest, opts(), ); @@ -467,7 +495,7 @@ describe('extractTar', () => { extractTar( githubArchive([{ name: at('big.bin'), data: 'x'.repeat(4096) }, KEEP]), dest, - opts(['SKILLS_VERSION'], { ...LIMITS, maxWrittenBytes: 100 }), + opts(['SKILLS_VERSION'], { ...CAPS, maxWrittenBytes: 100 }), ); expect(treeOf(dest)).toEqual(['SKILLS_VERSION']); }); @@ -475,52 +503,6 @@ describe('extractTar', () => { // At a selected path: refused. describe('extractTar', () => { - it.each([ - ['a symlink', '2'], - ['a hard link', '1'], - ['a character device', '3'], - ['a block device', '4'], - ['a directory', '5'], - ['a fifo', '6'], - ['a pax extended header', 'x'], - ['a pax global header', 'g'], - ['a GNU long name', 'L'], - ['a GNU long link name', 'K'], - ['an unknown type', '9'], - ])('rejects %s entry outright, rather than skipping it', (_label, type) => { - const dest = fresh(); - const message = refusal( - githubArchive([{ name: at('SKILLS_VERSION'), type }]), - opts(), - dest, - ); - expect(message).toMatch(/unsupported type/); - expect(message).toContain(at('SKILLS_VERSION')); - expect(treeOf(dest)).toEqual([]); - }); - - // An `x` header's records OVERRIDE the ustar header that follows it, so the - // listed file after one is refused whatever the payload: it is never read. - it.each([ - ['path=', paxRecord('path', at('deep/elsewhere.txt'))], - ['size=', paxRecord('size', '8589934592')], - ['only benign metadata', paxRecord('mtime', '1700000000.0')], - ['an unparseable payload', '7 comment=xyz\n'], - ['an empty payload', ''], - ])( - 'refuses a pax extended header carrying %s, on its typeflag alone', - (_label, data) => { - const message = refusal( - githubArchive([ - { name: at('PaxHeaders/SKILLS_VERSION'), type: 'x', data }, - KEEP, - ]), - ); - expect(message).toMatch(/pax extended or GNU long-name header/); - expect(message).toContain(at('SKILLS_VERSION')); - }, - ); - it('refuses a selected file that follows a GNU long name, whose records pharn does not honour', () => { expect( refusal( @@ -541,19 +523,6 @@ describe('extractTar', () => { ).toMatch(/pax extended or GNU long-name header/); }); - it.each([ - ['a `..` segment', '../SKILLS_VERSION', 'SKILLS_VERSION'], - [ - 'a deeper `..` segment', - `${ROOT}/nested/../../escape.txt`, - 'nested/../../escape.txt', - ], - ])('rejects %s', (_label, name, selected) => { - expect( - refusal(tar([GLOBAL_HEADER, { name, data: 'x' }]), opts([selected])), - ).toMatch(/escapes the archive root/); - }); - it('rejects an absolute path', () => { expect( refusal(tar([GLOBAL_HEADER, { name: '/SKILLS_VERSION', data: 'x' }])), @@ -566,26 +535,6 @@ describe('extractTar', () => { ).toMatch(/no leading component/); }); - // CORE-173: `\` and `:` in an entry name. POSIX writes `a\..\..\evil` as - // ONE literal file name; win32 would read the same bytes as a path. At a - // listed path either is refused, naming the entry. - it.each([ - ['a drive letter', 'C:/SKILLS_VERSION', 'SKILLS_VERSION'], - ['a backslash path', `${ROOT}/a\\..\\..\\evil`, 'a\\..\\..\\evil'], - ['a colon in a name', `${ROOT}/a:b.md`, 'a:b.md'], - ['a backslash in the root', 'a\\b/SKILLS_VERSION', 'SKILLS_VERSION'], - ])('refuses %s, writing nothing', (_label, name, selected) => { - const dest = fresh(); - const message = refusal( - tar([GLOBAL_HEADER, { name, data: 'x' }]), - opts([selected]), - dest, - ); - expect(message).toMatch(/backslash or colon/); - expect(message).toContain(name); - expect(treeOf(dest)).toEqual([]); - }); - it('refuses a backslash or colon in the ustar prefix too', () => { expect( refusal(tar([{ prefix: 'x:y', name: 'SKILLS_VERSION', data: 'x' }])), @@ -617,39 +566,6 @@ describe('extractTar', () => { expect(message).toContain(at('SKILLS_VERSION')); }); - // PHARN-17: a name a terminal would interpret is refused before any other - // rule, so it is neither installed nor echoed raw by a refusal message. - // Names are latin1 in the header, so a UTF-8 U+202E is written as its bytes. - it.each([ - ['an ESC sequence in the root', { name: `d${ESC}[2K\r/SKILLS_VERSION` }], - [ - 'a right-to-left override', - { name: utf8AsLatin1('evil\u202egnp/SKILLS_VERSION') }, - ], - [ - 'a zero-width space', - { name: utf8AsLatin1('se\u200bcurity/SKILLS_VERSION') }, - ], - [ - 'a control byte in the ustar prefix', - { name: 'SKILLS_VERSION', prefix: `d${ESC}x` }, - ], - [ - 'a line separator (U+2028)', - { name: utf8AsLatin1('a\u2028b/SKILLS_VERSION') }, - ], - ])('refuses %s, naming it without the raw character', (_label, entry) => { - const dest = fresh(); - const message = refusal( - tar([GLOBAL_HEADER, { ...entry, data: 'x' }]), - opts(), - dest, - ); - expect(message).toMatch(/control or format character/); - expect(hasUnsafeChars(message)).toBe(false); - expect(treeOf(dest)).toEqual([]); - }); - // A decoder's DEFAULT drops a leading byte-order mark: the name would be // written under a different name than the archive holds instead of refused. it('refuses a name field that starts with a byte-order mark, never strips it', () => { @@ -684,29 +600,193 @@ describe('extractTar', () => { expect(message).not.toContain(ESC); }); + it('refuses invalid UTF-8 in the ustar prefix too', () => { + expect( + refusal(tar([{ name: 'SKILLS_VERSION', prefix: 'd\x9b', data: 'x' }])), + ).toMatch(/not valid UTF-8/); + }); +}); + +// The rules a SELECTED entry is held to, over the base fixtures: `LIMITS` +// selects each path these cases use (as latin1 keys, byte for byte), so every +// entry below is judged exactly as before CORE-386. +describe('extractTar', () => { + const onDisk = (dir: string): Buffer[] => + readdirSync(dir, { encoding: 'buffer' }); + it.each([ - ['a raw C1 byte', 'pharn-oss-\x9b2J/SKILLS_VERSION'], - ['a truncated UTF-8 sequence', 'bad-\xe2\x80/SKILLS_VERSION'], - ['an overlong encoding', 'slash-\xc0\xaf/SKILLS_VERSION'], + ['path=', paxRecord('path', 'pharn-oss-abc1234/deep/elsewhere.txt')], + ['size=', paxRecord('size', '8589934592')], + ['only benign metadata', paxRecord('mtime', '1700000000.0')], + ['an unparseable payload', '7 comment=xyz\n'], + ['an empty payload', ''], + ])( + 'refuses a pax extended header carrying %s, on its typeflag alone', + (_label, data) => { + expect(() => + extractTar( + githubArchive([ + { name: 'pharn-oss-abc1234/PaxHeaders/f.txt', type: 'x', data }, + { name: 'pharn-oss-abc1234/f.txt', data: 'x' }, + ]), + tmp.path(), + LIMITS, + ), + ).toThrow(/pax extended or GNU long-name header/); + }, + ); + + it.each([ + ['a `..` segment', 'pharn-oss-abc1234/../escape.txt'], + ['a deeper `..` segment', 'pharn-oss-abc1234/nested/../../escape.txt'], + ])('rejects %s', (_label, name) => { + expect(() => + extractTar(githubArchive([{ name, data: 'x' }]), tmp.path(), LIMITS), + ).toThrow(TarExtractError); + }); + + it.each([ + ['a symlink', '2'], + ['a hardlink', '1'], + ['a character device', '3'], + ['a block device', '4'], + ['a fifo', '6'], + ['a pax extended header', 'x'], + // GNU's long-name typeflags are the other way a writer escapes ustar's + // 100-byte name field. They need no branch of their own — they are neither + // '0'/NUL nor '5', so they land in this reject — but they are pinned HERE + // so a future refactor of the bucket cannot start accepting them quietly. + ['a GNU long name', 'L'], + ['a GNU long link name', 'K'], + ['an unknown type', '9'], + ['a directory', '5'], + ['a pax global header', 'g'], + ])('rejects %s entry outright, rather than skipping it', (_label, type) => { + // At a selected path only (`link` is in LIMITS.select): outside the + // selection the same entry is skipped (see the block above). + expect(() => + extractTar( + githubArchive([{ name: 'pharn-oss-abc1234/link', type }]), + tmp.path(), + LIMITS, + ), + ).toThrow(/unsupported type/); + }); + + it.each([ + [ + 'an ESC sequence in the name', + { name: `pharn-oss-abc1234/n${ESC}[2K\r${ESC}[32mOK` }, + ], + [ + 'a right-to-left override', + { name: utf8AsLatin1('pharn-oss-abc1234/evil\u202egnp.md') }, + ], + [ + 'a zero-width space', + { name: utf8AsLatin1('pharn-oss-abc1234/se\u200bcurity.md') }, + ], + [ + 'a control byte in the ustar prefix', + { name: 'f.md', prefix: `pharn-oss-abc1234/d${ESC}x` }, + ], + // CORE-170: the one unsafe set now holds the two line separators too. + [ + 'a line separator (U+2028)', + { name: utf8AsLatin1('pharn-oss-abc1234/a\u2028b.md') }, + ], + ])('refuses %s, naming it without the raw character', (_label, entry) => { + let message = ''; + try { + extractTar(githubArchive([entry]), tmp.path(), LIMITS); + } catch (err) { + expect(err).toBeInstanceOf(TarExtractError); + message = (err as Error).message; + } + expect(message).toMatch(/control or format character/); + expect(hasUnsafeChars(message)).toBe(false); + }); + + it.each([ + ['a raw C1 byte', 'pharn-oss-abc1234/evil-\x9b2J.md'], + ['a truncated UTF-8 sequence', 'pharn-oss-abc1234/bad-\xe2\x80.md'], + ['an overlong encoding of "/"', 'pharn-oss-abc1234/slash-\xc0\xaf.md'], ])( 'refuses a name holding %s — not valid UTF-8 — writing nothing', (_label, name) => { - const dest = fresh(); - const message = refusal( - tar([GLOBAL_HEADER, { name, data: 'x' }]), - opts(), - dest, - ); + const dest = tmp.path(); + let message = ''; + try { + extractTar(githubArchive([{ name, data: 'x' }]), dest, LIMITS); + } catch (err) { + expect(err).toBeInstanceOf(TarExtractError); + message = (err as Error).message; + } expect(message).toMatch(/not valid UTF-8/); expect(hasUnsafeChars(message)).toBe(false); - expect(treeOf(dest)).toEqual([]); + expect(onDisk(dest)).toEqual([]); }, ); - it('refuses invalid UTF-8 in the ustar prefix too', () => { - expect( - refusal(tar([{ name: 'SKILLS_VERSION', prefix: 'd\x9b', data: 'x' }])), - ).toMatch(/not valid UTF-8/); + // A GNU base-256 field sets the high bit of its first byte. No such byte is + // an octal digit, so the non-octal check refuses it: 0x80 directly, and 0xA0 + // because only ASCII space is trimmed (String#trim would strip U+00A0 and + // then read the octal digits behind it as the size). + it.each([ + ['0x80', 0x80], + ['0xa0 (U+00A0 in latin1)', 0xa0], + ['0xff', 0xff], + ])( + 'rejects a size field whose first byte is %s (GNU base-256), never misreading it', + (_label, byte) => { + const bytes = Buffer.concat([ + header({ name: 'pharn-oss-abc1234/', type: '5' }), + header({ + name: 'pharn-oss-abc1234/f.txt', + data: 'x', + forgeSizeByte: byte, + }), + Buffer.alloc(BLOCK), + Buffer.alloc(BLOCK * 2), + ]); + expect(() => extractTar(bytes, tmp.path(), LIMITS)).toThrow( + /non-octal numeric field/, + ); + }, + ); + + // CORE-173: `\` and `:` in an entry name. POSIX writes `a\..\..\evil` as + // ONE literal file name; win32 would read the same bytes as a path. pharn-oss + // ships neither character, so either is refused, naming the entry. + it.each([ + ['a backslash path', 'pharn-oss-abc1234/a\\..\\..\\evil'], + ['a drive letter', 'pharn-oss-abc1234/C:/x'], + ['a colon in a name', 'pharn-oss-abc1234/a:b.md'], + ['a backslash in a directory segment', 'pharn-oss-abc1234/d\\e/f.md'], + ])('refuses %s, writing nothing', (_label, name) => { + const dest = tmp.path(); + let message = ''; + try { + extractTar(githubArchive([{ name, data: 'x' }]), dest, LIMITS); + } catch (err) { + expect(err).toBeInstanceOf(TarExtractError); + message = (err as Error).message; + } + expect(message).toMatch(/backslash or colon/); + expect(message).toContain(name); + expect(readdirSync(dest)).toEqual([]); + }); + + it('rejects a file with no component to strip', () => { + // `loose.txt` is selected: a rootless copy of a listed file is refused, + // not skipped. No preceding root entry, so the strip-1 rule rejects it. + expect(() => + extractTar( + tar([GLOBAL_HEADER, { name: 'loose.txt', data: 'x' }]), + tmp.path(), + LIMITS, + ), + ).toThrow(/no path below the archive root/); }); }); @@ -790,27 +870,6 @@ describe('extractTar', () => { expect(message).not.toContain('\n'); expect(message).toContain('1\\x0a Done'); }); - - // A GNU base-256 field sets the high bit of its first byte. No such byte is - // an octal digit, so the non-octal check refuses it: 0x80 directly, and 0xA0 - // because only ASCII space is trimmed (String#trim would strip U+00A0 and - // then read the octal digits behind it as the size). - it.each([ - ['0x80', 0x80], - ['0xa0 (U+00A0 in latin1)', 0xa0], - ['0xff', 0xff], - ])( - 'rejects a size field whose first byte is %s (GNU base-256), never misreading it', - (_label, byte) => { - const bytes = Buffer.concat([ - header({ name: `${ROOT}/`, type: '5' }), - header({ name: at('f.txt'), data: 'x', forgeSizeByte: byte }), - Buffer.alloc(BLOCK), - Buffer.alloc(BLOCK * 2), - ]); - expect(refusal(bytes)).toMatch(/non-octal numeric field/); - }, - ); }); // Caps. @@ -824,14 +883,14 @@ describe('extractTar', () => { expect(() => extractTar(githubArchive(many), fresh(), { select: new Set(), - limits: { ...LIMITS, maxHeaders: 3 }, + limits: { ...CAPS, maxHeaders: 3 }, }), ).toThrow(/more than 3 headers/); }); it('counts every pax global header toward the entry cap', () => { const empty: EntryInit = { name: 'pax_global_header', type: 'g', data: '' }; - const limits = { ...LIMITS, maxHeaders: 3 }; + const limits = { ...CAPS, maxHeaders: 3 }; expect( refusal(tar([empty, empty, empty, empty]), opts([], limits)), ).toMatch(/more than 3 headers/); @@ -850,7 +909,7 @@ describe('extractTar', () => { const dest = fresh(); const message = refusal( githubArchive([KEEP, { name: at('big.md'), data: 'x'.repeat(600) }]), - opts(['SKILLS_VERSION', 'big.md'], { ...LIMITS, maxWrittenBytes: 100 }), + opts(['SKILLS_VERSION', 'big.md'], { ...CAPS, maxWrittenBytes: 100 }), dest, ); expect(message).toMatch(/exceed 100 bytes/); @@ -862,7 +921,7 @@ describe('extractTar', () => { expect( refusal( githubArchive([{ name: at('pad'), data: 'x'.repeat(4096) }, KEEP]), - opts(['SKILLS_VERSION'], { ...LIMITS, maxScannedBytes: 2048 }), + opts(['SKILLS_VERSION'], { ...CAPS, maxScannedBytes: 2048 }), ), ).toMatch(/decompresses to more than 2048 bytes/); }); @@ -947,15 +1006,20 @@ describe('extractTarGz', () => { }); it('bounds the bytes written by the selected sizes (maxWrittenBytes)', async () => { + // Formerly gunzip's decompressed-size cap: the tar is streamed now, so the + // cap applies to the bytes written, not to the whole repository. await expect( extractTarGz( gzipSync( githubArchive([ - { name: at('SKILLS_VERSION'), data: 'x'.repeat(600) }, + { name: 'pharn-oss-abc1234/big.txt', data: 'x'.repeat(600) }, ]), ), - fresh(), - opts(['SKILLS_VERSION'], { ...LIMITS, maxWrittenBytes: 100 }), + tmp.path(), + { + select: new Set(['big.txt']), + limits: { ...CAPS, maxWrittenBytes: 100 }, + }, ), ).rejects.toThrow(/exceed 100 bytes/); }); @@ -981,7 +1045,7 @@ describe('extractTarGz', () => { extractTarGz( bomb, fresh(), - opts(['SKILLS_VERSION'], { ...LIMITS, maxScannedBytes: 65536 }), + opts(['SKILLS_VERSION'], { ...CAPS, maxScannedBytes: 65536 }), ), ).rejects.toThrow(/decompresses to more than 65536 bytes/); }); @@ -996,7 +1060,7 @@ describe('extractTarGz', () => { ]), ), dest, - opts(['SKILLS_VERSION'], { ...LIMITS, maxWrittenBytes: 4096 }), + opts(['SKILLS_VERSION'], { ...CAPS, maxWrittenBytes: 4096 }), ); expect(treeOf(dest)).toEqual(['SKILLS_VERSION']); }); From ab300d9b18b19bd186fb1186a6689c923f4cf219 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Przemys=C5=82aw=20Galarowicz?= Date: Wed, 25 Nov 2026 17:46:46 +0100 Subject: [PATCH 4/4] test(tar-extract): keep the base pax and byte-cap tests' assertions (CORE-386) The refusal of a listed file after a modifier header now names that header's type through describeTypeflag ("unsupported type 'x' (a pax extended header, ...)"), so the base pax test keeps its expected value. The base test "bounds the bytes written by the decompressed size" keeps its name, now over the streamed decompressed cap (maxScannedBytes). Co-Authored-By: Claude Opus 5.5 --- src/lib/tar-extract.ts | 20 ++++++++++---------- tests/repo.test.ts | 4 +++- tests/tar-extract.test.ts | 26 +++++++++++++++++++++++--- 3 files changed, 36 insertions(+), 14 deletions(-) diff --git a/src/lib/tar-extract.ts b/src/lib/tar-extract.ts index 4aeee3e1..c6b7bf74 100644 --- a/src/lib/tar-extract.ts +++ b/src/lib/tar-extract.ts @@ -315,9 +315,9 @@ class TarWalker { private dataLeft = 0; private padLeft = 0; private pending: Pending | null = null; - // The previous header was a modifier ('x', 'L', 'K'), so this one's ustar - // path and size may not be the real ones. - private modified = false; + // The typeflag of the modifier ('x', 'L', 'K') the previous header was, so + // this one's ustar path and size may not be the real ones; `null`: none. + private modifier: string | null = null; private ended = false; constructor( @@ -415,13 +415,13 @@ class TarWalker { ); } const typeflag = String.fromCharCode(block[OFF_TYPEFLAG]!); - const modified = this.modified; + const modifier = this.modifier; // A 'g' modifies nothing, so it neither sets nor consumes the flag. - if (MODIFIERS.has(typeflag)) this.modified = true; - else if (typeflag !== 'g') this.modified = false; + if (MODIFIERS.has(typeflag)) this.modifier = typeflag; + else if (typeflag !== 'g') this.modifier = null; if (isSelected(block, this.options.select)) { - this.accept(block, typeflag, modified, size); + this.accept(block, typeflag, modifier, size); } this.dataLeft = size; this.padLeft = Math.ceil(size / BLOCK) * BLOCK - size; @@ -432,7 +432,7 @@ class TarWalker { private accept( block: Buffer, typeflag: string, - modified: boolean, + modifier: string | null, size: number, ): void { // The FULL path is judged before any other rule, so no later message @@ -446,9 +446,9 @@ class TarWalker { `tar entry has an unsupported type ${describeTypeflag(typeflag)} at a path pharn installs (only a regular file is accepted there): ${fullPath}`, ); } - if (modified) { + if (modifier !== null) { throw new TarExtractError( - `tar entry follows a pax extended or GNU long-name header, whose records pharn does not honour, at a path pharn installs: ${fullPath}`, + `tar entry follows a header of unsupported type ${describeTypeflag(modifier)}, whose records pharn does not honour, at a path pharn installs: ${fullPath}`, ); } const { rel, root } = resolveEntryPath(fullPath, this.root); diff --git a/tests/repo.test.ts b/tests/repo.test.ts index 975e76c2..6f2d9c89 100644 --- a/tests/repo.test.ts +++ b/tests/repo.test.ts @@ -799,7 +799,9 @@ describe('fetchRepo — only the listed paths are unpacked (CORE-386)', () => { ); const err = await fetchRepo(release).catch((e: unknown) => e); expect(err).toBeInstanceOf(TarExtractError); - expect((err as Error).message).toMatch(/pax extended or GNU long-name/); + expect((err as Error).message).toMatch( + /unsupported type 'x'.*pax extended header/, + ); expect(leftoverTempDirs()).toEqual([]); }); diff --git a/tests/tar-extract.test.ts b/tests/tar-extract.test.ts index 23946806..91679d80 100644 --- a/tests/tar-extract.test.ts +++ b/tests/tar-extract.test.ts @@ -508,7 +508,7 @@ describe('extractTar', () => { refusal( githubArchive([{ name: '././@LongLink', type: 'L', data: 'x' }, KEEP]), ), - ).toMatch(/pax extended or GNU long-name header/); + ).toMatch(/whose records pharn does not honour/); }); it('a pax global header between the extended header and the file does not lift the refusal', () => { @@ -520,7 +520,7 @@ describe('extractTar', () => { KEEP, ]), ), - ).toMatch(/pax extended or GNU long-name header/); + ).toMatch(/whose records pharn does not honour/); }); it('rejects an absolute path', () => { @@ -632,7 +632,7 @@ describe('extractTar', () => { tmp.path(), LIMITS, ), - ).toThrow(/pax extended or GNU long-name header/); + ).toThrow(/unsupported type 'x'.*pax extended header/); }, ); @@ -1005,6 +1005,26 @@ describe('extractTarGz', () => { expect((err as Error).message).toMatch(/unsupported type '2'/); }); + // The name is the base test's: the decompressed stream is still capped + // (maxTotalBytes became maxScannedBytes, now counted as the tar streams), and + // no file can be written past that cap. The written-byte cap is the next test. + it('bounds the bytes written by the decompressed size (maxTotalBytes)', async () => { + await expect( + extractTarGz( + gzipSync( + githubArchive([ + { name: 'pharn-oss-abc1234/big.txt', data: 'x'.repeat(600) }, + ]), + ), + tmp.path(), + { + select: new Set(['big.txt']), + limits: { ...CAPS, maxScannedBytes: 100 }, + }, + ), + ).rejects.toThrow(/decompresses to more than 100 bytes/); + }); + it('bounds the bytes written by the selected sizes (maxWrittenBytes)', async () => { // Formerly gunzip's decompressed-size cap: the tar is streamed now, so the // cap applies to the bytes written, not to the whole repository.