fix(#3712): confine in-process installs to a sandboxed HOME (#3725)

* fix(#3712): confine in-process installs to a sandboxed HOME

A runtime kind may declare a global `home` override resolved from os.homedir()
rather than from the caller's configDir — codex's skills kind (`home: ".agents"`,
ADR-1239 / #2088) is the only live case. Sandboxing configDir/targetDir does not
contain it, and assertDestWithinConfigHome cannot see the class: that gate
confines a destSubpath to whatever root it is handed, and here the root IS the
escaped home. So an in-process caller that forgot to sandbox HOME wrote to, and
pruned gsd-* entries from, the developer's REAL ~/.agents/skills.

tests/agent-descriptor-parity.install.test.cjs's K1 loop did exactly that: it
iterates every agents-kind runtime (codex included) with a sandboxed targetDir
and an un-sandboxed HOME. Reproduced against a canary home on next @ adb46cdd8 —
71 gsd-* skill dirs deleted, a foreign `cloudflare` skill surviving, suite still
exit 0. It is silent because the runtime's own config home is untouched, so the
manifest keeps reporting a healthy install.

FIVE writers resolve a kind `home` and then destroy under it. Three are reachable
today — installRuntimeArtifacts, uninstallRuntimeArtifacts (install-engine.cts)
and applySurface (surface.cts). Two are descriptor-dependent and guarded against a
future descriptor change rather than a present escape: installOpencodeFamilySkills
(behind the combined-family early return) and installAgentsKindStandalone. Those
two are scoped to the single kind each destroys — passing the whole layout made
codex's unrelated skills override trip a writer that never touches it.

- src/test-home-guard.cts: refuse when a run under a test runner cannot be shown
  to have sandboxed HOME. NODE_TEST_CONTEXT (set by `node --test`) gates it, so
  installs outside a Node test context are untouched; GSD_TEST_MODE is unusable,
  as several candidate files including the offender never set it. Homes are
  compared by FILESYSTEM IDENTITY (st_dev + st_ino), not by pathname:
  path.resolve() resolves neither symlinks nor case, and realpath returns a
  canonical pathname that two routes to one directory can still disagree on (bind
  mounts). Verified on macOS/APFS — HOME=/users/<name> made the strings differ
  while naming the same directory, and the lexical form ALLOWED a write into the
  physical real home. FAILS CLOSED: a pair is "different" only when both identify,
  or one is definitively absent (ENOENT/ENOTDIR) while the other identifies; every
  other errno is "cannot tell" and refuses. Only when neither home identifies is a
  marker consulted, and it carries the sandbox PATH and must equal the home in
  effect — a boolean checked first let an ambient or stale value disarm the guard.
- helpers: promote sandboxHome() out of its two byte-identical private copies,
  which is also what makes them record the sandbox; the three withFakeHome()
  helpers record it too. The marker NAME is duplicated as a bare string rather
  than required from the compiled guard, keeping helpers.cjs's documented
  no-built-lib-at-import-time contract; a test pins the two together.
- agent-descriptor-parity: sandbox HOME across the K1 loop.
- helpers-process-isolation: #3156's canary asserts on <home>/.gsd only, and its
  `--cursor --local` spawn cannot reach `.agents` at all, so an assertion added
  there would pass with all confinement removed. Add a discriminating row — a
  `--codex --global` spawn against a seeded ambient home — which also asserts the
  runtime still declares the override. Its check is a sampled inventory (dir names
  + each SKILL.md), not a tree compare.
- install-write-confinement: predicate rows through the deps seam, covering the
  symlinked HOME, ambient and stale markers, and each sameDirectory branch
  (both-identify, one-absent, neither-identifiable), plus wiring rows that drive
  the REAL entrypoints so deleting a guard call site is red.

Verified: guard fires end-to-end against a real un-sandboxed HOME (exit 1, zero
deletions); the case-variant fail-open reproduced on APFS before the fix and
refuses after; K1 file 29/29 green with skills intact; mutation-tested — each of
the three reachable call sites, lexical-only comparison, and treating an unknown
errno as "absent" each take exactly one row red, with every mutation echoed back;
the process-isolation row negative-controlled by reverting installerEnv to its
pre-#3156 leak (16/0 -> 13/3); a full npm test leaves ~/.agents/skills at 71.

Stated residual: the two descriptor-dependent writers have no wiring test, because
no runtime declares a `home` override on those kinds and neither can be exercised
without inventing a descriptor.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* chore(#3712): add changeset

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(#3712): let a sandbox nested inside the real home through the guard

All six Windows shards of #3725 failed on legitimately sandboxed
destinations. On Windows os.tmpdir() is %LOCALAPPDATA%\Temp — inside the
user's home — so every sandbox a test creates is a descendant of the real
home, and "does this land inside the real home?" answers yes for the safe
case and the dangerous one alike. POSIX conceals this: /tmp and
/var/folders both sit outside $HOME.

Add the missing conjunct: a destination inside the real home is allowed
only when it also sits beneath a HOME that was sandboxed away from the
passwd home. Both halves are required — dropping the first re-admits a
plain un-sandboxed install, and dropping the second decays into the
"is HOME sandboxed?" check the module rejects, which a layout resolved
before the sandbox walks straight through. Each is mutation-proven by a
row that goes red without it.

Also covers the two fail-closed branches of the new exemption, which
survived mutation to `true` with the suite green, and avoids `<user>` in
a docblock — the prompt-injection scanner reads it as a delimiter tag.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(#3712): close three writer/rollback gaps found reviewing the whole PR

Cross-AI review of the full PR (not just the round's delta) surfaced
three ways the guard could still be defeated:

- The nested-sandbox exemption trusted the SPELLING of a destination.
  With HOME sandboxed to a directory inside the real home — legitimate on
  Windows — an aliased `.agents` (symlink, junction, subordinate bind
  mount) beneath it redirected an allowed path into the real home. Decide
  containment on the path the write RESOLVES to: walk up to the nearest
  existing ancestor, canonicalize, re-append the tail.

- `migrateLegacyDevPreferencesToSkill` is a SIXTH writer that resolves a
  skills-kind `home` override. It creates rather than prunes, which is
  why it was missed, and `_runLegacyInstallMigrations` runs it before
  `installRuntimeArtifacts`' own assertion. Guarded, scoped to that kind.

- Worst of the three: `bin/install.js` snapshots the resolved skills root
  before installing, and its outer catch rolls back by deleting and
  recreating every snapshotted `gsd-*` directory there. The guard's own
  throw landed in that catch, so refusing an un-sandboxed codex install
  provoked exactly the mutation the guard exists to prevent. Refusals are
  now marked and rethrown without rollback — nothing was written, so
  there is no partial install to undo. Every other error still rolls back.

Also carries the sandbox marker into `installSpawnEnv`, so spawned
installers are not refused on passwd-less CI images, and corrects three
claims that no longer hold: "every writer" (six, and named), the
unconditional "fails CLOSED" (the passwd-less marker branch is a
deliberate weakening, and TOCTOU is out of scope), and the assertion that
Windows os.tmpdir() is always %LOCALAPPDATA%\Temp (Node honors TEMP/TMP).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* docs(#3712): name the guard's two limits instead of overclaiming

Round-2 review found the prose had drifted ahead of the code. Corrected,
with no behavior change:

- The module still said FIVE writers; there are six, and the sixth is
  now named along with why it was missed (it creates rather than prunes)
  and why it carries its own assertion (it runs before the main one).
- The canonicalization docblock listed subordinate bind mounts among the
  aliases it closes. It does not close them: a bind mount is not a link,
  so realpath keeps the mount-point spelling. `sameDirectory` already
  recorded that limit; the new helper now inherits it explicitly rather
  than contradicting it. Closing it needs mount-table introspection.
- "FAILS CLOSED" was unqualified while the passwd-less marker branch is
  a deliberate weakening — with no passwd entry, nothing can contradict a
  marker naming the real home.
- "Refuses BEFORE any write" was too broad: legacy install migrations run
  ahead of the layout-driven ones, which is exactly why the two
  rollbackInstallerMigrations() calls still execute before the rethrow.
  Only the codex skills-root rollback is skipped, and that is the only
  _codexPreConfigRollback() call site — applySurface is never called from
  bin/install.js and uninstall cannot reach it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(#3712): sandbox HOME in the opencode-family home-override parity rows

The last two Windows failures, and the same platform asymmetry in a
different disguise. This row drives a skills-kind `home` override on
purpose — precisely what the guard polices — but relied on the override
temp dir happening to sit outside the real home. It does on POSIX
(/tmp, /var/folders); on Windows os.tmpdir() is under %USERPROFILE%, so
the guard correctly refused and only Windows went red.

Declare the sandbox instead of depending on the platform: HOME becomes
the override itself, which is the home the call writes under. This is the
fix the guard's own message prescribes, applied to the test rather than
to the guard.

Both failing Windows shards fail on exactly these two rows and nothing
else; every other shard is green.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(#3712): make sameDirectory answer NO when it cannot tell

Review Major 1. sameDirectory()'s only caller is the passwd-less marker
branch, which reads a `true` as permission to PROCEED:

    if (marker && sameDirectory(marker, osMod.homedir())) return;

The fallthrough returned `true` whenever neither side identified — two
absent paths, or two stats failing EACCES/EPERM/EIO on a locked-down
host — on the reasoning that "cannot tell" should make the caller refuse.
That reasoning was inverted with respect to this caller: it turned the
passwd-less escape hatch into an unconditional bypass for any marker
value at all, on precisely the hosts the fallback exists to serve. Only
two things now answer yes: one resolved pathname, or two readable
identities that match. Restoring the old fallthrough takes the new row
red.

Also from review:

- Major 2 asked whether st_dev/st_ino discriminate directories on
  Windows, where Node derives them from BY_HANDLE_FILE_INFORMATION. The
  whole guard rests on that primitive, so assert it rather than argue it:
  a row comparing two distinct temp directories, and one directory
  reached by two spellings. It runs on every platform in the matrix, so
  Windows answers the question itself.

- Minor 1: the refusal now names the real home it compared against, not
  just the destination it refused. That is the one fact needed to tell a
  true positive from a false one, and its absence is what made the
  Windows case a CI-log dig rather than a glance.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(#3712): refuse a HOME that merely spells the real home more widely

Review round: one Blocker, four Minors, a Nit.

N2 (the one with teeth) — a destination's ancestor chain is linear, so
"inside the real home AND inside the effective HOME" admits two
arrangements, not one. The intended `effectiveHome ⊂ realHome` is the
Windows temp shape; `realHome ⊂ effectiveHome` — HOME at /Users, /home,
C:\Users — is not a sandbox at all, it is the real home reached by a
wider spelling, and it was exempting a stale destination pointing
straight at ~/.agents. Third conjunct added; the docblock no longer
claims two conditions suffice. Removing the conjunct reds the new row
and nothing else.

N4 — the migration guard resolved its OWN layout, and without
capabilityRegistry, so a registry-dependent descriptor could make it
vouch for a path the migration does not write: a guard reporting safe
while the unsafe write proceeds. It now guards the destination already
resolved by _resolveDevPreferencesSkillTarget, keyed on
`installRoot !== targetDir` — which is exactly the condition under which
a `home` override was declared, read off that same result.

N1 — CONTEXT.md gains the Test Home Guard Module glossary entry that
contributor-standards.md requires of a new Module. Not CI-enforced, so
green CI was never evidence it was met.

N3 — the docs/INVENTORY.md row was misfiled between install-fs-adapter
and install-model-override-resolver; the table is alphabetical and the
manifest already had it right. Moved, and its text now names six writers
and the third conjunct.

N5 — applySurface's signature docblock was two parameters stale; this PR
added the second of them.

N6 — the duplicated rollbackInstallerMigrations() adjacent to the new
rethrow: two identical consecutive calls, not two phases.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(#3712): guard the sixth writer, and close two false-ALLOW paths

Review round 3 (NEW-1, NEW-2) plus three defects Codex found in the
whole-PR pass, each reproduced before it was fixed.

NEW-1 — migrateLegacyDevPreferencesToSkill called the guard with no
`deps`, so it bound real os/process.env and could not be wiring-tested
the way the other three reachable writers were. It now takes the same
optional `deps: { os?, env? }` tail parameter. The wiring block gains
the missing fourth row, and a fifth pinning the ALLOW half; the test
file's header docblock said "FIVE writers ... the three reachable
today", contradicting the six/four statement this PR already put in
src/test-home-guard.cts, CONTEXT.md, docs/INVENTORY.md and the
changeset. Both directions of the guard's condition now fail a row
when broken — previously neither did.

NEW-2 — derivesFromSandboxedHome's docblock claimed "THREE conditions
are required, and no two of them suffice". False for {2,3}: isInside is
reflexive, so whenever conjunct 1 fires conjunct 2 already returns
false on its own. Reworded as a fast path, which is what it is.

Codex 1 (false ALLOW) — on a host with no readable passwd entry the
marker branch returned as soon as the marker matched the effective
HOME. That attests a caller sandboxed HOME and says nothing about where
an already-resolved destination points, so a layout captured before
sandboxHome() — still naming the real ~/.agents — was waved straight
through: the same stale-layout shape the primary branch refuses by
design. The marker must now identify AND contain every destination.

Codex 2 (false ALLOW) — `installRoot !== targetDir` was the stand-in
for "the skills kind declared a home override". The two are not
equivalent: the inequality is false when the override resolves onto
targetDir itself, which is exactly a configDir of $HOME/.agents. The
guard was skipped and SKILL.md written into the real home under a test
runner. _resolveDevPreferencesSkillTarget now reports hasHomeOverride
off the same resolution instead of inferring it from two paths.

Codex 3 (prose) — the shared refusal message claimed every guarded
writer prunes; the migrate writer only creates. The changeset headline
claimed in-process installer calls can no longer reach the real home,
which is wider than the guard: writeNonClaudeDefaults still writes
~/.gsd/defaults.json through os.homedir(). INVENTORY's and CONTEXT's
fail-closed sentences omitted sameDirectory's pathname-equality
shortcut. All four narrowed to what the code does.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(#3712): let the sandbox marker follow an overridden HOME

Found by Codex in the whole-PR pass. installSpawnEnv spreads
`overrides` last so an explicit HOME wins — deliberate, and its
docblock tells callers needing per-spawn isolation to pass their own
{ HOME, USERPROFILE }. But the #3712 marker was set before that spread,
so such a caller got HOME=<theirs> and marker=<helper default>. On a
host with no readable passwd entry the guard compares the two and
refuses a legitimately sandboxed spawn — tests/install.test.cjs:7143
and install-shared.cjs's own runInstaller both take that path.

The marker is now derived from the final HOME unless the caller
supplied one explicitly. The contract test asserted HOME after an
override but not the marker, which is why it stayed green.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* docs(#3712): name the shipped guard condition, not the deleted one

Review round 4 of #3725. Two artifacts this PR adds still described
`target.installRoot !== targetDir` in the PRESENT tense as the live guard
condition on `migrateLegacyDevPreferencesToSkill`. The shipped condition is
`runtime && target.hasHomeOverride` (src/install-engine.cts:510).

This is not ordinary doc drift. The named condition is the exact false-ALLOW
the previous round closed: a `home` override resolving onto `targetDir` — a
configDir of `$HOME/.agents`, which is where codex's override points — makes
the inequality FALSE while the override is declared, so the guard was skipped.
A maintainer reading CONTEXT.md:290 as authoritative would believe the guard
still skips that case.

  - tests/install-write-confinement.test.cjs — the ALLOW-half row's comment.
    Its "teeth" rationale is unchanged and still correct as written.
  - CONTEXT.md:290 — the Test Home Guard Module glossary entry, a documented
    PR gate. Now states the condition and names the inequality only as what it
    is NOT, with the reason.

The three surviving mentions of the inequality are all past-tense or negated
(src/install-engine.cts:448, :508 and the sibling test comment at :3698) and
are correct as they stand.

Verified: `npm run lint:ci` exit 0; full `npm test` 31327 tests / 31312 pass /
0 fail / 14 skipped, run with TMPDIR unset.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(#3712): canonicalization fails closed, matching identify's errno split

Codex full-PR review of #3725, run against the round-4 head.

`resolveThroughLinks` caught EVERY realpathSync error and fell back to
`path.resolve(dest)` — the lexical spelling. That inverts the function's own
purpose. An aliased `<sandbox>/.agents` that cannot be canonicalized keeps its
sandbox spelling, satisfies the nested-sandbox exemption at :227, and the write
is ALLOWED into the real home — the exact escape this walk exists to close. The
module documents that it fails CLOSED with ONE named exception (the marker
branch); this was a second, unnamed one.

Split by errno, and deliberately by the SAME split `identify` already draws
rather than a second policy in one module — both answer "does this path exist
as named?", so they must not disagree:

  ENOENT / ENOTDIR -> walk up. The ordinary case: a fresh install resolves a
    destination nothing has created yet, so realpath fails on the leaf and on
    every not-yet-created ancestor. Refusing here rejects every install.
  anything else (EACCES, EPERM, ELOOP, EIO) -> refuse. The component exists but
    cannot be resolved, so the guard cannot tell where the write lands.

Three rows in the predicate block, beside the other aliasing rows:
  - a symlink CYCLE in the destination path (ELOOP)   -> REFUSE
  - a destination that does not exist yet (ENOENT)    -> ALLOW
  - a component behind a regular file (ENOTDIR)       -> ALLOW

Teeth checked against the artifact the test loads, not the source: reverting
the condition to the swallow-everything shape in the compiled
test-home-guard.cjs turns row 1 — and only row 1 — red. The ENOTDIR row caught
a stale build during development, which is the point of asserting on the
compiled file.

CONTEXT.md and the resolveThroughLinks docblock both record the new behaviour,
so this does not repeat the prose-vs-code drift the round-4 finding was about.

The changeset's existing scope sentence now bounds "six writers" to the
`installRuntimeArtifacts` call tree and names `cmdGenerateDevPreferences` —
which resolves the same codex `home` override through `getGlobalSkillsBase` and
writes SKILL.md beneath it unguarded. It has no in-process caller today (its
only direct require-and-call is a spawnSync with HOME sandboxed), so it is
latent rather than live, and whether it belongs in this PR is raised with the
maintainer rather than decided here.

Verified: `npm run lint:ci` exit 0; full `npm test` 31330 tests / 31315 pass /
0 fail / 14 skipped, TMPDIR unset.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Behruz Nassre Esfahani
2026-08-23 15:27:02 -07:00
committed by GitHub
parent 1178c5f995
commit a44d513566
17 changed files with 1411 additions and 39 deletions

View File

@@ -32,6 +32,7 @@ import retiredArtifactCleanup = require('./retired-artifact-cleanup.cjs');
import { posixNormalize } from './shell-command-projection.cjs';
import { isPathConfined } from './external-descriptor-trust.cjs';
import { ensureCommonJsMarker } from './commonjs-marker.cjs';
import testHomeGuard = require('./test-home-guard.cjs');
// #2874 (ADR-58 cleanup phase): the injectable fs seam for the
// installRuntimeArtifacts call tree. `installFs()` resolves to real
// `node:fs` unless a call is wrapped in `withInstallFs(deps.fs, ...)` —
@@ -436,7 +437,7 @@ function _tryResolveUserArtifactStagingRoot(configDir: string): string | null {
* no skills layout to migrate into (mirrors `migrateLegacyDevPreferencesToSkill`'s
* own early return for that case).
*/
function _resolveDevPreferencesSkillTarget(targetDir: string, runtime?: string, scope: string = 'global'): { skillFile: string; installRoot: string } | null {
function _resolveDevPreferencesSkillTarget(targetDir: string, runtime?: string, scope: string = 'global'): { skillFile: string; installRoot: string; hasHomeOverride: boolean } | null {
let skillDir: string;
// #2911: the actual install root the skill dir resolves under — defaults to
// targetDir, but a skills-kind `home` override (e.g. Codex -> $HOME/.agents)
@@ -444,6 +445,15 @@ function _resolveDevPreferencesSkillTarget(targetDir: string, runtime?: string,
// must confine against installRoot, not targetDir, or it would flag the
// legitimate override destination as an escape.
let installRoot: string = targetDir;
// Reported in Codex review of #3725: `installRoot !== targetDir` was used as the
// stand-in for "the skills kind declared a `home` override", and the two are NOT
// equivalent — a resolved `home` that happens to EQUAL targetDir (a configDir of
// `$HOME/.agents`, which is exactly where codex's override points) makes the
// inequality false while the override is very much declared, skipping the guard
// and writing SKILL.md into the real home. Report the declaration itself instead
// of inferring it from two paths, read off the SAME layout resolution the
// destination came from so the guard cannot vouch for a path this does not write.
let hasHomeOverride = false;
if (runtime) {
const layout: any = runtimeArtifactLayout.resolveRuntimeArtifactLayout(runtime, targetDir, scope as any);
const skillsKindEntry = layout.kinds.find((k: any) => k.kind === 'skills');
@@ -454,19 +464,54 @@ function _resolveDevPreferencesSkillTarget(targetDir: string, runtime?: string,
// -> $HOME/.agents) instead of always resolving against targetDir, so a
// legacy dev-preferences migration lands in the SAME tree the installer
// and surface-apply use. Runtimes with no `home` override are unaffected.
hasHomeOverride = skillsKindEntry.home != null;
installRoot = skillsKindEntry.home ?? targetDir;
skillDir = path.join(runtimeArtifactInstallPlan.assertDestWithinConfigHome(installRoot, skillsKindEntry.destSubpath), stemName);
} else {
// Legacy fallback for callers that have not yet been updated to pass runtime
skillDir = path.join(runtimeArtifactInstallPlan.assertDestWithinConfigHome(targetDir, 'skills'), 'gsd-dev-preferences');
}
return { skillFile: path.join(skillDir, 'SKILL.md'), installRoot };
return { skillFile: path.join(skillDir, 'SKILL.md'), installRoot, hasHomeOverride };
}
function migrateLegacyDevPreferencesToSkill(targetDir: string, saved: Map<string, string>, runtime?: string, scope: string = 'global'): boolean {
/**
* @param deps - #3712 test seam, mirroring the one on `installRuntimeArtifacts`
* and `uninstallRuntimeArtifacts`. This is the SIXTH writer that resolves a
* skills-kind `home`, and its guard's trigger condition — "HOME equals the
* passwd home" — cannot be reproduced without pointing at the developer's real
* home, so it is injected rather than simulated. Production callers pass
* nothing and bind real `os`/`process.env`.
*/
function migrateLegacyDevPreferencesToSkill(
targetDir: string,
saved: Map<string, string>,
runtime?: string,
scope: string = 'global',
deps: { os?: any; env?: Record<string, string | undefined> } = {},
): boolean {
if (!saved || !saved.has('dev-preferences.md')) return false;
const target = _resolveDevPreferencesSkillTarget(targetDir, runtime, scope);
if (!target) return false; // runtime has no skills layout at this scope (e.g. cline local)
// #3712 — the SIXTH writer that resolves a skills-kind `home` override.
// Exported and directly callable, and `_runLegacyInstallMigrations` runs it
// BEFORE installRuntimeArtifacts' own assertion, so a future runtime pairing a
// home override with this migration would write to the real home ahead of any
// guard. It creates rather than prunes, which is why it was missed.
//
// Guards the destination ALREADY RESOLVED above, never a second resolution of
// its own. An earlier revision re-ran resolveRuntimeArtifactLayout() here —
// and without `capabilityRegistry`, so a registry-dependent descriptor could
// make the two disagree and leave the guard vouching for a path the migration
// does not write. That is the generative-fix-divergence shape; reported in
// review of #3725. `target.hasHomeOverride` is that same resolution's own answer
// to "did the skills kind declare a `home`?" — not re-derived, and not inferred
// from `installRoot !== targetDir`, which is false whenever the override happens
// to resolve onto targetDir itself (Codex review of #3725).
if (runtime && target.hasHomeOverride) {
testHomeGuard.assertTestHomeSandboxed('migrateLegacyDevPreferencesToSkill', runtime, [
{ kind: 'skills', home: path.dirname(target.skillFile) },
], { os: deps.os, env: deps.env });
}
const { skillFile, installRoot } = target;
const skillDir = path.dirname(skillFile);
// Security fix: `existsSync` FOLLOWS symlinks and reports `false` for a
@@ -997,7 +1042,7 @@ function installRuntimeArtifacts(
resolvedProfile: any,
resolveAttribution: ResolveAttribution = () => undefined,
capabilityRegistry?: any,
deps: { fs?: any } = {},
deps: { fs?: any; os?: any; env?: Record<string, string | undefined> } = {},
): any {
return withInstallFs(deps.fs, (): any => {
// A removed descriptor kind is no longer visited by the layout loop, so it
@@ -1025,6 +1070,11 @@ function installRuntimeArtifacts(
_runLegacyInstallMigrations(runtime, configDir, scope);
const layout = runtimeArtifactLayout.resolveRuntimeArtifactLayout(runtime, configDir, scope as 'global' | 'local', capabilityRegistry);
// #3712: a global `home` override escapes the sandboxed configDir. Refuse to
// execute when a test run would land that escape in the developer's real home.
testHomeGuard.assertTestHomeSandboxed('installRuntimeArtifacts', runtime, layout?.kinds, {
os: deps.os, env: deps.env,
});
const planResult = runtimeArtifactInstallPlan.createRuntimeArtifactInstallPlan({
// `Layout` is structurally identical across the layout/install-plan .cjs
// modules but nominally distinct to tsc (untyped .cjs boundary) — bridge it.
@@ -1261,6 +1311,13 @@ function installOpencodeFamilySkills(
const layout: any = runtimeArtifactLayout.resolveRuntimeArtifactLayout(runtime, targetDir);
const skillsKindEntry = layout.kinds.find((k: any) => k.kind === 'skills');
if (!skillsKindEntry) return 0;
// #3712: combined-family runtimes take installRuntimeArtifacts' early return
// BEFORE its guard runs, and this writer honors `skillsKindEntry.home` below and
// then prunes that destination. opencode/kilo declare no `home` today, so there
// is no live escape — but that makes this a bypass waiting on a descriptor
// change rather than a safe omission, so it is guarded at the writer instead.
// Scoped to the SKILLS kind alone, for the same reason as the agents writer.
testHomeGuard.assertTestHomeSandboxed('installOpencodeFamilySkills', runtime, [skillsKindEntry]);
const rawDir = rawCommandsDir;
if (!rawDir || !installFs().existsSync(rawDir)) return 0;
@@ -1438,6 +1495,14 @@ function installAgentsKindStandalone(
const layout: any = runtimeArtifactLayout.resolveRuntimeArtifactLayout(runtime, targetDir, scope as 'global' | 'local', capabilityRegistry);
const agentsKindEntry = layout.kinds.find((k: any) => k.kind === 'agents');
if (!agentsKindEntry) return null;
// #3712: this writer selects `agentsKindEntry.home` over targetDir below and then
// prunes that destination via _removeGsdEntries, so it is a fifth route into the
// developer's real home. No agents kind declares a `home` override today, so like
// installOpencodeFamilySkills it is guarded against a descriptor change rather
// than a present escape. Scoped to the AGENTS kind alone: passing the whole
// layout made codex's unrelated skills-kind override trip a writer that never
// touches it, which is a false refusal, not a tighter guard.
testHomeGuard.assertTestHomeSandboxed('installAgentsKindStandalone', runtime, [agentsKindEntry]);
// ADR-1235 §1: same agentCtx shape createRuntimeArtifactInstallPlan builds
// for the generic layout-driven loop (runtime-artifact-install-plan.cts) —
@@ -1816,7 +1881,12 @@ function installOpencodeFamilyArtifacts(
* @param configDir resolved runtime config directory
* @param scope
*/
function uninstallRuntimeArtifacts(runtime: string, configDir: string, scope: string): void {
function uninstallRuntimeArtifacts(
runtime: string,
configDir: string,
scope: string,
deps: { os?: any; env?: Record<string, string | undefined> } = {},
): void {
// A retired descriptor kind is absent from the current uninstall plan, just
// as it is absent from the install plan. Sweep manifest-proven output from
// retired kinds before removing the current layout so a direct uninstall
@@ -1830,6 +1900,12 @@ function uninstallRuntimeArtifacts(runtime: string, configDir: string, scope: st
const stagedLegacyArtifacts = _runLegacyUninstallCleanup(runtime, configDir, scope);
const layout: any = runtimeArtifactLayout.resolveRuntimeArtifactLayout(runtime, configDir, scope as any);
// #3712: uninstall resolves the SAME `kind.home` override as install and then
// prunes it via _removeGsdEntries below, so it is a second escape route into
// the developer's real home, not a read-only path. Guard it identically.
testHomeGuard.assertTestHomeSandboxed('uninstallRuntimeArtifacts', runtime, layout?.kinds, {
os: deps.os, env: deps.env,
});
const plan: any = runtimeArtifactInstallPlan.createRuntimeArtifactUninstallPlan(layout);
const kindsByName = new Map<string, any>(layout.kinds.map((kind: any) => [kind.kind as string, kind]));
for (const item of plan.items) {

View File

@@ -12,7 +12,7 @@
* readSurface(runtimeConfigDir)
* writeSurface(runtimeConfigDir, surfaceState)
* resolveSurface(runtimeConfigDir, manifest, clusterMap?, registry?)
* applySurface(runtimeConfigDir, layout, manifest, clusterMap?, registry?)
* applySurface(runtimeConfigDir, layout, manifest, clusterMap?, registry?, opts?, deps?)
* listSurface(runtimeConfigDir, manifest, clusterMap?, registry?)
* pruneSkillDirs(skillsDir, retainedNames, prefix, manifest)
*
@@ -34,6 +34,17 @@ import path from 'node:path';
import { platformWriteSync, posixNormalize } from './shell-command-projection.cjs';
// eslint-disable-next-line @typescript-eslint/no-require-imports
import installProfiles = require('./install-profiles.cjs');
// eslint-disable-next-line @typescript-eslint/no-require-imports
import testHomeGuard = require('./test-home-guard.cjs');
/**
* #3712 test seam, mirroring the `Deps` shape in src/test-home-guard.cts. Declared
* here rather than imported because that module uses `export =` on a value.
*/
type TestHomeGuardDeps = {
os?: { homedir(): string; userInfo(): { homedir: string } };
env?: Record<string, string | undefined>;
};
const {
readActiveProfile,
resolveProfile,
@@ -360,10 +371,16 @@ function resolveSurface(runtimeConfigDir: string, manifest: Map<string, string[]
* Re-stage the active surface using the resolved layout.
* Iterates layout.kinds and syncs each artifact kind to its destination.
*/
function applySurface(runtimeConfigDir: string, layout: Layout, manifest: Map<string, string[]> | object, clusterMap?: ClusterMap | Record<string, string[]>, registry?: { capabilityClusters?: Record<string, string[]>; profileMembership?: Record<string, { tier: string; profiles: string[] }> }, opts?: ApplySurfaceOptions): { name: string; skills: Set<string>; agents: Set<string> } {
function applySurface(runtimeConfigDir: string, layout: Layout, manifest: Map<string, string[]> | object, clusterMap?: ClusterMap | Record<string, string[]>, registry?: { capabilityClusters?: Record<string, string[]>; profileMembership?: Record<string, { tier: string; profiles: string[] }> }, opts?: ApplySurfaceOptions, deps: TestHomeGuardDeps = {}): { name: string; skills: Set<string>; agents: Set<string> } {
if (path.resolve(runtimeConfigDir) !== path.resolve(layout.configDir)) {
throw new TypeError('applySurface runtimeConfigDir must match layout.configDir');
}
// #3712: the dest selection below prefers `kind.home` over layout.configDir and
// then hands it to the destructive _syncGsdDir, so surface apply is a third
// escape route into the developer's real home alongside install/uninstall.
testHomeGuard.assertTestHomeSandboxed('applySurface', layout.runtime, layout.kinds, {
os: deps.os, env: deps.env,
});
const skillManifest = normalizeSkillManifest(layout.configDir, manifest);
const resolved = resolveSurface(layout.configDir, skillManifest, clusterMap, registry);
// Profile toggles must converge retired surfaces too. Once a kind disappears

439
src/test-home-guard.cts Normal file
View File

@@ -0,0 +1,439 @@
'use strict';
/**
* #3712 — refuse to let an in-process test run reach the developer's REAL home.
*
* A runtime kind may declare a global `home` override that is resolved from
* `os.homedir()` rather than from the caller's `configDir` (today: codex's
* skills kind, `home: ".agents"`, ADR-1239 / #2088 — Codex auto-discovers
* global skills from `$HOME/.agents/skills`). Sandboxing `configDir`/`targetDir`
* therefore does NOT contain such a kind, and no `assertDestWithinConfigHome`
* check can see it: that gate confines a destSubpath to whatever root it is
* handed, and here the root IS the escaped home.
*
* The live defect: an in-process caller that forgot to sandbox HOME installed —
* and, via `_removeGsdEntries` / `_syncGsdDir`, PRUNED — inside the real
* `~/.agents/skills`, deleting every `gsd-*` skill (observed 71 -> 0, a foreign
* `cloudflare` skill surviving) while the suite still exited 0. It is silent
* because the runtime's own config home is untouched, so the manifest keeps
* reporting a healthy install.
*
* This lives in its own module because SIX writers resolve a kind `home` and then
* write or destroy what is under it. Four are reachable today —
* `installRuntimeArtifacts` and `uninstallRuntimeArtifacts` (install-engine.cts)
* and `applySurface` (surface.cts); guarding only the install path, as the first
* cut of this fix did, left the other two as live bypasses. Two more are
* descriptor-dependent and guarded against a future descriptor change rather than
* a present escape: `installOpencodeFamilySkills`, which sits behind the
* combined-family early return and honors `skillsKindEntry.home` (no
* combined-family runtime declares one), and `installAgentsKindStandalone`, which
* honors `agentsKindEntry.home` and prunes it (no agents kind declares one).
* The sixth is `migrateLegacyDevPreferencesToSkill`, which resolves the skills
* kind's `home` and writes `SKILL.md` under it. It CREATES rather than prunes,
* which is why the first pass of this fix missed it, and it runs from
* `_runLegacyInstallMigrations` — i.e. BEFORE `installRuntimeArtifacts`' own
* assertion — so it carries its own call.
*
* DETECTION — three signals, in order:
*
* 1. `NODE_TEST_CONTEXT` is set by `node --test` and inherited by children, and
* is absent from normal installs outside a Node test context, so ordinary
* production installs are untouched. Precisely: an install spawned BENEATH a
* `node --test` process with an un-sandboxed HOME is refused — that is the
* point, and it is also why this is not stated as "never affects installs".
* `GSD_TEST_MODE` is NOT usable: several in-process test files — including
* the one that caused #3712 — never set it, so gating on it would miss the
* exact case this guard exists for.
* 2. `os.userInfo().homedir` reads the passwd entry and ignores `$HOME`, while
* `os.homedir()` prefers `$HOME`. They disagree exactly when a caller
* redirected HOME and agree when one forgot. This is the PRIMARY signal and
* the only one used whenever a passwd entry is readable. It is asked about
* the DESTINATION, not about HOME state: a destination outside the passwd
* home is allowed, and one inside it is refused UNLESS it sits beneath a
* HOME that was sandboxed away from the passwd home. That last exemption is
* not a softening — on Windows the temp root is inside the user's home, so
* without it every sandboxed run is refused (#3725). Both halves are
* required; see `derivesFromSandboxedHome`.
* 3. `SANDBOX_MARKER` — consulted ONLY when the passwd entry cannot be read.
*
* FAILS CLOSED, with one named exception. If the passwd entry is unreadable
* (some CI images) we cannot establish that HOME is sandboxed, so a home-override
* kind is refused rather than allowed — UNLESS the marker below names the home in
* effect. That branch is a deliberate weakening, not a closed door: with no passwd
* entry there is nothing that could contradict a marker naming the real home, so a
* caller that sandboxed to its own real home would be believed. The alternative is
* refusing every run on such a host. Everything else in that branch answers NO
* when it cannot tell — see `sameDirectory`. The cost of a false refusal is a failed test naming its own fix;
* the cost of a false allow is silent, unrecoverable deletion of a developer's
* skills.
*
* The marker carries the sandbox PATH, not a boolean, and is checked only in that
* unreadable-passwd branch — deliberately, because a boolean checked first is not
* proof of anything. An ambient or stale `=1` inherited from a parent process, or
* left set by an earlier in-process test, would have disarmed the guard entirely
* even when HOME plainly equalled the passwd home. Requiring the value to EQUAL
* the home now in effect means a leftover marker from some other directory cannot
* vouch for this call.
*/
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
/**
* Set by tests/helpers.cjs `sandboxHome()` to the sandboxed home PATH. Only
* consulted when the passwd entry is unreadable; see the module docblock.
*/
const SANDBOX_MARKER = 'GSD_TEST_HOME_SANDBOX';
/**
* Are these two paths the same directory on disk?
*
* Compared by FILESYSTEM IDENTITY — `st_dev` + `st_ino` — not by pathname.
* `path.resolve()` normalizes separators and `..` but resolves neither symlinks
* nor case, and `realpathSync` returns a canonical *pathname*, which two routes to
* one directory can still disagree on (a Linux bind mount is the standard case).
* `statSync` follows symlinks and reports the inode itself, so a case-variant
* HOME, a symlinked HOME, and a bind-mounted HOME all compare equal.
*
* Fails CLOSED, and "closed" here means returning FALSE. The sole caller is the
* passwd-less marker branch, which READS a true as permission to proceed:
*
* if (marker && sameDirectory(marker, osMod.homedir())) return; // allows
*
* So "cannot tell" must answer NO. An earlier revision returned true for the
* unknown/unknown case (both stats failing with something other than
* ENOENT/ENOTDIR — EACCES, EPERM, EIO) on the reasoning that "cannot tell" should
* make the caller refuse; that reasoning was inverted with respect to this
* caller, and it turned an unreadable-stat environment into an unconditional
* bypass for anyone who set the marker to any value at all. Reported in review of
* #3725. Only two things now answer yes: the same resolved pathname, or two
* readable identities that match.
*/
function sameDirectory(a: string, b: string): boolean {
if (path.resolve(a) === path.resolve(b)) return true;
const ia = identify(a);
const ib = identify(b);
if (ia.kind === 'ok' && ib.kind === 'ok') return ia.dev === ib.dev && ia.ino === ib.ino;
return false;
}
type Identity =
| { kind: 'ok'; dev: number; ino: number }
| { kind: 'absent' }
| { kind: 'unknown' };
function identify(p: string): Identity {
try {
const st = fs.statSync(p);
return { kind: 'ok', dev: st.dev, ino: st.ino };
} catch (err) {
const code = (err as NodeJS.ErrnoException | undefined)?.code;
if (code === 'ENOENT' || code === 'ENOTDIR') return { kind: 'absent' };
return { kind: 'unknown' };
}
}
type Kind = { kind?: string; home?: string; destSubpath?: string };
/** The slice of `node:os` this guard needs — injected so the trigger condition is testable. */
type OsLike = { homedir(): string; userInfo(): { homedir: string } };
type Deps = { os?: OsLike; env?: Record<string, string | undefined> };
/**
* @param operation - the writer being guarded, for the error message
* (e.g. `installRuntimeArtifacts`), so a failure names its own call site.
* @param runtime - canonical runtime id, for the error message.
* @param kinds - resolved layout kinds; only those carrying `home` can escape.
* @param deps - test seam. The guard's own trigger condition is "HOME equals the
* passwd home", which cannot be reproduced without pointing at the developer's
* real home, so it is injected rather than simulated. Mirrors the `deps.os`
* seam in scripts/live-config-guard.cjs.
* @throws {Error} when a global `home` override cannot be shown to be sandboxed.
*/
/**
* Stamped on every Error this module throws.
*
* A refusal happens before any LAYOUT-DRIVEN write — legacy install migrations
* run first and are rolled back on their own path — so it is not a partial
* codex-skills install and must not trigger that rollback. `bin/install.js`'s
* pre-config rollback
* deletes and recreates every snapshotted `gsd-*` directory in the resolved
* skills root, which for an un-sandboxed codex install IS the real
* `~/.agents/skills`. Without this marker the guard's own refusal would provoke
* the mutation it exists to prevent. Found by review, not by CI.
*/
const REFUSAL_FLAG = 'gsdTestHomeGuardRefusal';
/**
* Static remediation line, shared by every refusal this module raises. Hoisted to
* module scope because `resolveThroughLinks` refuses too and sits outside
* `assertTestHomeSandboxed`'s body, where this used to be a local.
*/
const SANDBOX_FIX_HINT =
`Fix the TEST, not this guard: sandbox HOME and USERPROFILE BEFORE resolving the ` +
`layout, for the duration of the call — use sandboxHome(t, dir) from tests/helpers.cjs ` +
`(see #3712).`;
function refusal(message: string): Error {
const err = new Error(message);
(err as Error & Record<string, unknown>)[REFUSAL_FLAG] = true;
return err;
}
/** Did `err` come from this guard refusing before any write happened? */
function isTestHomeGuardRefusal(err: unknown): boolean {
return Boolean(err && typeof err === 'object' && (err as Record<string, unknown>)[REFUSAL_FLAG]);
}
function assertTestHomeSandboxed(
operation: string,
runtime: string,
kinds: Kind[] | undefined,
deps: Deps = {},
): void {
const osMod = deps.os ?? os;
const env = deps.env ?? process.env;
if (!env['NODE_TEST_CONTEXT']) return; // a real install
const overriding = (kinds ?? []).filter((k) => k && k.home);
if (overriding.length === 0) return; // nothing can escape
let passwdHome: string | null = null;
try {
passwdHome = osMod.userInfo().homedir || null;
} catch {
passwdHome = null;
}
const fix = SANDBOX_FIX_HINT;
const realHome = passwdHome === null ? { kind: 'unknown' as const } : identify(passwdHome);
if (realHome.kind === 'ok') {
let effectiveHome: string | null = null;
try {
effectiveHome = osMod.homedir() || null;
} catch {
effectiveHome = null;
}
// The question is NOT "is HOME sandboxed right now" — it is "does this
// destination land in the real home, other than by deriving from a sandbox
// beneath it". The first half alone is not enough: a layout resolved BEFORE
// sandboxHome() captures the real `~/.agents` in `kind.home`, and applySurface
// takes an already-resolved layout, so a HOME-state check returns "sandboxed"
// while the stale destination still points at the real home.
//
// The second half is not optional either — see `derivesFromSandboxedHome`.
// Containment in the real home is not by itself evidence of danger on a
// platform whose temp root lives inside the home.
for (const kind of overriding) {
const declared = path.resolve(path.join(kind.home as string, kind.destSubpath ?? ''));
// Both questions are asked of the path the write will REACH, not the one
// it was spelled as; see resolveThroughLinks.
const dest = resolveThroughLinks(declared);
if (!isInside(dest, realHome)) continue;
if (derivesFromSandboxedHome(dest, effectiveHome, realHome, passwdHome as string)) continue;
throw refusal(
`${operation}("${runtime}") was called under a test runner with a destination inside ` +
`your REAL home. The "${kind.kind}" kind declares a global home override, so it ` +
`resolves from os.homedir() and NOT from the sandboxed configDir — this call would ` +
`write inside ${dest} (and install, uninstall and surface-apply also PRUNE GSD ` +
`entries there).\nThe real home it was ` +
`compared against is ${passwdHome} — if that is not your home, this ` +
`refusal is the bug and not the call.\n${fix}`,
);
}
return;
}
// The real home cannot be identified, so containment against it cannot be
// evaluated at all. Fall back to the weaker signal: a marker naming the home
// currently in effect. Only reachable on hosts with no readable passwd entry,
// where the alternative is refusing every such run.
//
// TWO things are required, not one. An earlier revision returned as soon as the
// marker matched the effective HOME, which attested that a caller sandboxed HOME
// but said NOTHING about where these destinations resolve — so a layout captured
// BEFORE sandboxHome(), still naming the real `~/.agents`, was waved straight
// through on a passwd-less host. That is the same stale-layout shape the primary
// branch above refuses by design, and it made the marker a bypass for exactly
// the case the guard exists for. Reported in Codex review of #3725.
//
// The marker must also IDENTIFY: `sameDirectory` answers yes for two identical
// unidentifiable pathnames (see its docblock), and that is not enough to place a
// destination against.
const marker = env[SANDBOX_MARKER];
const markerId = marker ? identify(marker) : { kind: 'unknown' as const };
if (marker && markerId.kind === 'ok' && sameDirectory(marker, osMod.homedir())) {
const stale = overriding.find(
(kind) => !isInside(resolveThroughLinks(path.resolve(path.join(kind.home as string, kind.destSubpath ?? ''))), markerId),
);
if (!stale) return;
throw refusal(
`${operation}("${runtime}") was called under a test runner on a host with no identifiable ` +
`passwd home. HOME was sandboxed and recorded, but the "${stale.kind}" kind resolves to ` +
`${resolveThroughLinks(path.resolve(path.join(stale.home as string, stale.destSubpath ?? '')))}, ` +
`which is NOT beneath that sandbox — so this layout was resolved before the sandbox and still ` +
`names another home. A recorded sandbox vouches for HOME, never for a destination that does ` +
`not derive from it.\n${fix}`,
);
}
throw refusal(
`${operation}("${runtime}") was called under a test runner and this environment has no ` +
`identifiable passwd home, so GSD cannot establish where the real home is. The ` +
`"${overriding[0]?.kind}" kind declares a global home override, which resolves from ` +
`os.homedir() and would write inside whatever real home that is (and, for the pruning ` +
`writers, delete GSD entries there). Refusing rather than guessing.\n${fix}`,
);
}
/**
* The path `dest` will actually resolve to when it is written.
*
* `dest` usually does not exist yet — that is the point, it is about to be
* created — so `realpathSync` cannot be called on it directly. Walk up to the
* nearest ancestor that DOES exist, canonicalize that, and re-append the tail.
*
* Without this the sandbox exemption below is escapable: with HOME sandboxed to
* `$REAL/tmp-home` and `$REAL/tmp-home/.agents` a symlink (or Windows junction)
* onto the real `$REAL/.agents`, the lexical ancestor
* walk reaches the sandbox and the write is allowed — straight into the real
* home. Identity comparison alone does not close it, because each ancestor is
* identified in isolation and the alias sits BETWEEN dest and the sandbox.
* Found by review, not by CI.
*
* KNOWN LIMITATION — a subordinate BIND MOUNT of the real `~/.agents` at
* `<sandbox>/.agents` is NOT closed by this. A bind mount is not a link:
* `realpathSync` keeps the mount-point spelling, so the canonical destination
* still reads as "beneath the sandbox" while the write reaches the real
* directory. `sameDirectory` above already records that realpath cannot unify
* bind-mounted spellings; this inherits that limit. Closing it needs mount-table
* introspection, which is not portable, and the setup — deliberately mounting the
* one directory this guard protects into a sandbox inside the home — is not a
* shape any caller here produces. A cross-process swap of a checked directory
* between this call and the write (TOCTOU) is likewise out of reach and not
* claimed.
*
* Canonicalization itself fails CLOSED — see the errno split below. A component
* that EXISTS but cannot be resolved is refused, because falling back to the
* lexical spelling is the exact ALLOW an unresolvable alias needs.
*/
function resolveThroughLinks(dest: string): string {
const tail: string[] = [];
let cur = path.resolve(dest);
for (;;) {
try {
return path.join(fs.realpathSync(cur), ...tail);
} catch (err) {
// Same errno split `identify` already draws, and deliberately the same one:
// both functions are asking "does this path exist as named?", so they must
// not disagree. ENOENT/ENOTDIR mean NOT THERE — the expected case, since a
// fresh install resolves a destination that does not exist yet and realpath
// fails on the leaf and on every not-yet-created ancestor. That is what this
// walk is FOR, so keep walking.
//
// Any other errno means the component EXISTS but could not be canonicalized —
// EACCES/EPERM on a directory whose mode changed, ELOOP on a symlink cycle,
// EIO on a failing mount. Falling through to the lexical spelling there is a
// FAIL-OPEN that precisely inverts this function's purpose: an aliased
// `<sandbox>/.agents` that cannot be resolved keeps its sandbox spelling,
// satisfies the nested-sandbox exemption, and the write is ALLOWED straight
// into the real home. The module documents that it fails CLOSED with exactly
// ONE named exception (the marker branch); a swallowed canonicalization error
// was a second, unnamed one. Refuse instead. (Codex review of #3725.)
const code = (err as NodeJS.ErrnoException | null)?.code;
if (code !== 'ENOENT' && code !== 'ENOTDIR') {
throw refusal(
`A component of the destination could not be canonicalized, so this guard cannot ` +
`tell whether the write would reach your REAL home.\nFailed on: ${cur} ` +
`(${code ?? 'unknown error'})\nSymlinks and junctions are resolved BEFORE the ` +
`decision, because an aliased "<sandbox>/.agents" would otherwise read as confined ` +
`while pointing at the real one. A component that cannot be resolved is refused ` +
`rather than assumed safe.\n${SANDBOX_FIX_HINT}`,
);
}
const parent = path.dirname(cur);
if (parent === cur) return path.resolve(dest);
tail.unshift(path.basename(cur));
cur = parent;
}
}
}
/**
* Is `dest` inside a HOME that has been sandboxed away from the passwd home?
*
* Asked only once `dest` is already known to be inside the real home, and it is
* what makes that fact non-fatal on Windows: there `os.tmpdir()` is
* `%USERPROFILE%\AppData\Local\Temp` by default (Node honors `TEMP`/`TMP`,
* so this is the usual case rather than a guarantee) — so in practice every
* sandbox a test creates is a descendant of the real home. Containment in the
* real home is therefore true of the correctly-sandboxed case and the dangerous
* one alike, and cannot separate them by itself. POSIX conceals this, because
* `/tmp` and `/var/folders` both sit outside `$HOME`. All six Windows shards of
* #3725 failed on legitimately sandboxed destinations before this conjunct
* existed.
*
* TWO conditions carry the decision, and neither suffices alone:
*
* - the passwd home is NOT beneath that HOME — see the comment on that check;
* without it a HOME that merely spells the real home more widely (`/Users`,
* `C:\Users`) is mistaken for a sandbox.
* - `dest` is beneath that sandboxed HOME — otherwise this decays into the
* "is HOME sandboxed?" check the module docblock rejects, and a layout
* resolved before the sandbox walks straight through.
*
* The first check below — HOME differs from the passwd home — is a cheap fast
* path, NOT an independent condition: `isInside` is reflexive, so whenever HOME
* identifies the passwd home the second check already returns false on its own.
* Removing it changes no outcome; it is kept to answer the common case without
* an ancestor walk. Raised in review of #3725 against prose that claimed the
* three were independent.
*
* Fails CLOSED: an unreadable or unidentifiable HOME returns false, so the
* caller refuses rather than exempting a destination it cannot place.
*/
function derivesFromSandboxedHome(
dest: string,
effectiveHome: string | null,
realHome: { dev: number; ino: number },
passwdHome: string,
): boolean {
if (effectiveHome === null) return false;
const eff = identify(effectiveHome);
if (eff.kind !== 'ok') return false;
if (eff.dev === realHome.dev && eff.ino === realHome.ino) return false;
// A sandbox sits BENEATH the real home (the Windows temp shape) — never above
// it. A destination's ancestor chain is linear, so "inside the real home AND
// inside the effective HOME" admits two arrangements, not one: the intended
// `effectiveHome ⊂ realHome`, and `realHome ⊂ effectiveHome` — HOME pointed at
// `/Users`, `/home`, or `C:\Users`. The second is not a sandbox, it is the real
// home reached by a wider spelling, and without this it exempts a stale
// destination. Reported in review of #3725 as the one leaking cell of a
// six-row truth table.
if (isInside(passwdHome, eff)) return false;
return isInside(dest, eff);
}
/**
* Is `child` at or beneath the directory identified by `rootId`?
*
* Walks `child`'s ancestors comparing filesystem identity rather than string
* prefixes, because `child` typically does not exist yet (that is the point — it
* is about to be created) while its ancestors do. A prefix test would miss a
* case-variant or symlinked spelling of the same ancestor, which is the exact
* class this guard exists to catch.
*/
function isInside(child: string, rootId: { dev: number; ino: number }): boolean {
let cur = path.resolve(child);
for (;;) {
const id = identify(cur);
if (id.kind === 'ok' && id.dev === rootId.dev && id.ino === rootId.ino) return true;
const parent = path.dirname(cur);
if (parent === cur) return false;
cur = parent;
}
}
export = { assertTestHomeSandboxed, isTestHomeGuardRefusal, SANDBOX_MARKER };