Skip to content

Commit 387bf15

Browse files
authored
fix(engine): allow symlinks that resolve inside the project root (#500)
1 parent 9a114b3 commit 387bf15

4 files changed

Lines changed: 283 additions & 103 deletions

File tree

‎.claude/agent-memory/archgate-developer/project_rules_engine_internals.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,3 +16,7 @@ metadata:
1616
- **Scanner walk drops any node `AstNodeSchema.safeParse` rejects — WITH its whole subtree — so an over-strict schema is a silent security false-negative, not a validation nicety. Now ADR-governed (ARCH-024 clause 7).** `parseNode()` returns null on schema failure and the walk skips it (`if (child) walk(child)`), so a banned global/eval/import nested inside a rejected node goes unscanned and `check` reports pass. `type` is always present and every typed child field recurses, so a `Literal`'s `value` is the ONLY leaf that can independently fail — keep it `z.unknown().optional()` (read only via `typeof … === "string"` guards). Fired twice: null `source` on `export`-without-`from` (#493), and exotic `value` — meriyah emits `{}` for a RegExpLiteral and a `bigint` for `123n` (#494, e.g. `/x/.constructor.constructor` = Function ctor off a regex receiver). Always fix by WIDENING the schema (the block already exists, it's just unreached), never by adding a new check. Zod gotcha: `z.unknown()` is NON-optional in this Zod (v4) — bare `z.unknown()` made every node lacking `value` fail; needs `.optional()`.
1717
- **`Bun.Transpiler` strips provably-dead code before the scanner sees it — this is correct, not a gap.** `const y = /x/ || import("node:child_process")` transpiles to `const y = /x/;` (a RegExp literal is always truthy, so the `||` right side is unreachable and eliminated). Unreachable payloads genuinely never run, so not scanning them is right. When writing an escape regression test, put the payload in a REACHABLE position (`[/x/, import(...)]`, comma operator, a separate statement) and confirm `transformSync` keeps it — else the test passes for the wrong reason.
1818
- **Spawning a language interpreter to parse an untrusted project file is an RCE surface — the specifics are now ADR-governed (ARCH-022), noted here for any FUTURE interpreter-subprocess feature.** (1) `python -c` puts the target project cwd on `sys.path`, so a planted `ast.py`/`json.py` executes when the serializer imports stdlib — always pass `-I` (isolated). Verified: without `-I`, `import ast` resolves to a cwd shadow. (2) Python's plain `utf-8` codec keeps the BOM as U+FEFF and `ast.parse` then errors — read with `utf-8-sig` (`r:bom|utf-8` for Ruby). (3) `meriyah` `loc` after `Bun.Transpiler` is transpiled-relative, NOT original-source lines (type-only/comment/blank lines dropped) — re-locate via `readFile`+`indexOf` for the TS path; JS is parsed untranspiled so its `loc` is accurate. (4) Windows: probe the `py` launcher too (python.org registers it even when PATH opt-in is unchecked). The single sanctioned meriyah call site is `src/engine/js-parser.ts`; interpreter probe/spawn is `src/engine/ast-support.ts`.
19+
- **Fire-test a guard in BOTH directions: that it blocks the bad case AND still permits the legitimate one.** Proving a guard is load-bearing (stub it out → test fails) only shows the gate closes; it says nothing about over-rejection. 2026-07-25: the ARCH-024 ancestor-symlink guard (#499) passed a green suite while rejecting _every_ symlinked component below the project root, including links pointing back INSIDE the project — which breaks workspace monorepos (pnpm/npm/yarn/bun symlink `node_modules/<pkg>` → `packages/<pkg>`) and symlinked shared source dirs. It reached main before the false positive was caught; fixed in #500 by gating on the link's resolved TARGET rather than its existence. For any boundary check, write the allow-case test alongside the deny-case one.
20+
- **`realpath` comparisons must be realpath-against-realpath, never realpath-against-lexical.** `realpathSync` case-canonicalizes on Windows and macOS, so comparing its output against a lexically-built path rejects case-mismatched-but-legitimate paths. Resolve both sides — see `realRootOf` in `src/engine/safe-path.ts`. This is why the first version of the symlink walk deliberately used boolean `lstat` instead.
21+
- **When testing an "empty X" case, test the degenerate form, not a near-empty variant.** A test named "returns {} for an empty frontmatter block" used `---\n\n---` — a blank line the body group can capture — and passed, hiding that the truly empty `---\n---` did not match at all. The near-miss variant exercises a different path than the one the test name claims.
22+
- **Never chain cleanup of a temp script with `&&`, and never `git add -A` after using one.** `python fix.py && rm -f fix.py` leaves the script behind whenever it exits non-zero — exactly when a failed edit makes cleanup most necessary — and a later `git add -A` commits it. A throwaway `fix-sec-test.py` reached PR #500 this way (2026-07-25) and the maintainer caught it in review; nothing in `validate` flags a stray root-level `.py` (not linted, not in `src/`, invisible to knip). Use `; rm -f` or a `trap`, prefer `git add <explicit paths>`, and check `git diff --name-only origin/main...HEAD | grep -v /` before pushing.

‎src/engine/safe-path.ts‎

Lines changed: 64 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
// SPDX-License-Identifier: Apache-2.0
22
// Copyright 2026 Archgate
3-
import { lstatSync } from "node:fs";
3+
import { lstatSync, realpathSync } from "node:fs";
44
import { resolve, isAbsolute, join, relative } from "node:path";
55

66
import { UserError } from "../helpers/user-error";
@@ -31,23 +31,45 @@ export function isWithinRoot(resolvedRoot: string, absPath: string): boolean {
3131
}
3232

3333
/**
34-
* Directories verified as real (non-symlink), memoized per process: safePath
35-
* runs once per glob result and siblings share every ancestor, so without this
36-
* the walk below re-lstats the same directories thousands of times per run.
34+
* Real (non-symlink) components already verified, memoized per process:
35+
* safePath runs once per glob result and siblings share every ancestor.
36+
* Symlinks are never stored — they are re-resolved on every access. Nested per
37+
* root, since a link leaving root A may land inside an enclosing root B.
3738
*/
38-
const verifiedRealDirs = new Set<string>();
39+
const verifiedComponents = new Map<string, Set<string>>();
40+
41+
/** Project roots resolved through `realpath`, memoized per process. */
42+
const realRoots = new Map<string, string>();
43+
44+
/**
45+
* The project root with symlinks in its own path resolved, so a link target
46+
* compares against it like-for-like. Falls back to the lexical root.
47+
*/
48+
function realRootOf(resolvedRoot: string): string {
49+
let hit = realRoots.get(resolvedRoot);
50+
if (hit === undefined) {
51+
try {
52+
hit = realpathSync(resolvedRoot);
53+
} catch {
54+
hit = resolvedRoot;
55+
}
56+
realRoots.set(resolvedRoot, hit);
57+
}
58+
return hit;
59+
}
3960

4061
/**
41-
* Reject a symlink anywhere in the path below the project root — the leaf OR
42-
* any ancestor, since a linked ancestor makes the leaf look like an ordinary
43-
* file to both `isWithinRoot` and a leaf `lstat`. Components at or above the
44-
* root are deliberately not inspected, and each test is a boolean `lstat`
45-
* rather than a `realpath` comparison.
62+
* Reject a path whose real target lies outside the project root, testing every
63+
* component below it — the leaf AND every ancestor, since a linked ancestor
64+
* makes the leaf look ordinary to both `isWithinRoot` and a leaf `lstat`. The
65+
* gate is where a link POINTS, not that one exists: links resolving back
66+
* inside the project are a normal layout (workspace monorepos, shared dirs).
4667
*
47-
* @throws {UserError} When any component below the root is a symbolic link.
48-
* @see ARCH-022 — why the walk stops at the root and avoids `realpath`
68+
* @throws {UserError} When a component resolves outside the project root.
69+
* @see ARCH-022 — why the walk stops at the root
70+
* @see .claude/agent-memory/archgate-developer/project_rules_engine_internals.md — why both sides are realpath'd
4971
*/
50-
function assertNoSymlinkInPath(
72+
function assertNoEscapingSymlink(
5173
resolvedRoot: string,
5274
absPath: string,
5375
userPath: string
@@ -57,10 +79,16 @@ function assertNoSymlinkInPath(
5779
if (!rel || rel.startsWith("..")) return;
5880

5981
const segments = rel.split(/[/\\]/u);
82+
let verified = verifiedComponents.get(resolvedRoot);
83+
if (!verified) {
84+
verified = new Set();
85+
verifiedComponents.set(resolvedRoot, verified);
86+
}
87+
6088
let current = resolvedRoot;
61-
for (const [index, segment] of segments.entries()) {
89+
for (const segment of segments) {
6290
current = join(current, segment);
63-
if (verifiedRealDirs.has(current)) continue;
91+
if (verified.has(current)) continue;
6492
let stat;
6593
try {
6694
stat = lstatSync(current);
@@ -70,20 +98,31 @@ function assertNoSymlinkInPath(
7098
return;
7199
}
72100
if (stat.isSymbolicLink()) {
73-
throw new UserError(
74-
index === segments.length - 1
75-
? `Path "${userPath}" is a symbolic link — access denied`
76-
: `Path "${userPath}" traverses symbolic link "${segment}" — access denied`
77-
);
101+
let target: string;
102+
try {
103+
target = realpathSync(current);
104+
} catch {
105+
return; // Broken link — resolves to nothing, so it reaches nothing.
106+
}
107+
if (!isWithinRoot(realRootOf(resolvedRoot), target)) {
108+
throw new UserError(
109+
`Path "${userPath}" resolves outside the project through symbolic link "${segment}" — access denied`
110+
);
111+
}
112+
// Deliberately NOT memoized: a link is re-resolved on every access, so a
113+
// target repointed later in the process cannot ride an earlier pass.
114+
continue;
78115
}
79-
if (stat.isDirectory()) verifiedRealDirs.add(current);
116+
verified.add(current);
80117
}
81118
}
82119

83120
/**
84-
* Resolve a user-supplied path and ensure it stays within projectRoot.
85-
* Throws if the resolved path escapes the project boundary, is a symlink, or
86-
* reaches its target through a symlinked ancestor directory.
121+
* Resolve a user-supplied path and ensure it stays within projectRoot, either
122+
* lexically or after resolving symlinks at any component. Links resolving back
123+
* inside the project are allowed.
124+
*
125+
* @throws {UserError} When the path escapes the project root.
87126
*/
88127
export function safePath(resolvedRoot: string, userPath: string): string {
89128
const absPath = resolveUserPath(resolvedRoot, userPath);
@@ -92,6 +131,6 @@ export function safePath(resolvedRoot: string, userPath: string): string {
92131
`Path "${userPath}" escapes project root — access denied`
93132
);
94133
}
95-
assertNoSymlinkInPath(resolvedRoot, absPath, userPath);
134+
assertNoEscapingSymlink(resolvedRoot, absPath, userPath);
96135
return absPath;
97136
}

‎tests/commands/check-security.test.ts‎

Lines changed: 74 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -14,21 +14,60 @@ import { join } from "node:path";
1414
import { loadRuleAdrs } from "../../src/engine/loader";
1515
import { runChecks } from "../../src/engine/runner";
1616

17+
/**
18+
* Whether this platform/account can create a link of the given kind. Windows
19+
* allows directory junctions unprivileged but needs elevation for file
20+
* symlinks, so the two are probed separately.
21+
*/
22+
function canLink(kind: "dir" | "file"): boolean {
23+
const probe = mkdtempSync(join(tmpdir(), "archgate-linkprobe-"));
24+
try {
25+
if (kind === "dir") {
26+
symlinkSync(probe, join(probe, "link"), "junction");
27+
} else {
28+
writeFileSync(join(probe, "f.txt"), "x");
29+
symlinkSync(join(probe, "f.txt"), join(probe, "link.txt"));
30+
}
31+
return true;
32+
} catch {
33+
return false;
34+
} finally {
35+
rmSync(probe, { recursive: true, force: true });
36+
}
37+
}
38+
39+
const DIR_LINKS = canLink("dir");
40+
const FILE_LINKS = canLink("file");
41+
1742
describe("check command security", () => {
1843
let tempDir: string;
1944
let adrsDir: string;
45+
let outsideDirs: string[];
2046

2147
beforeEach(() => {
2248
tempDir = mkdtempSync(join(tmpdir(), "archgate-check-sec-"));
2349
adrsDir = join(tempDir, ".archgate", "adrs");
2450
mkdirSync(adrsDir, { recursive: true });
2551
mkdirSync(join(tempDir, "src"), { recursive: true });
52+
outsideDirs = [];
2653
});
2754

55+
// Cleanup runs here, not after each assertion: a failing expect() throws
56+
// immediately, so a trailing rmSync would be skipped and leak the dir.
2857
afterEach(() => {
2958
rmSync(tempDir, { recursive: true, force: true });
59+
for (const dir of outsideDirs) {
60+
rmSync(dir, { recursive: true, force: true });
61+
}
3062
});
3163

64+
/** A temp directory outside the project root, removed in afterEach. */
65+
function makeOutsideDir(): string {
66+
const dir = mkdtempSync(join(tmpdir(), "archgate-outside-"));
67+
outsideDirs.push(dir);
68+
return dir;
69+
}
70+
3271
const adrTemplate = (id: string) =>
3372
`---\nid: ${id}\ntitle: Security Test\ndomain: general\nrules: true\n---\n`;
3473

@@ -146,25 +185,19 @@ describe("check command security", () => {
146185
expect(result.results[0].error).toContain("access denied");
147186
});
148187

149-
test("blocks symlink to file outside project", async () => {
150-
const outsideDir = mkdtempSync(join(tmpdir(), "archgate-outside-"));
151-
writeFileSync(join(outsideDir, "secret.txt"), "sensitive data");
152-
153-
// Create a symlink inside the project pointing outside
154-
try {
188+
test.skipIf(!FILE_LINKS)(
189+
"blocks symlink to file outside project",
190+
async () => {
191+
const outsideDir = makeOutsideDir();
192+
writeFileSync(join(outsideDir, "secret.txt"), "sensitive data");
155193
symlinkSync(
156194
join(outsideDir, "secret.txt"),
157195
join(tempDir, "src", "linked.txt")
158196
);
159-
} catch {
160-
// Symlink creation may fail on Windows without admin privileges — skip
161-
rmSync(outsideDir, { recursive: true, force: true });
162-
return;
163-
}
164197

165-
writeAdrAndRule(
166-
"SEC-006",
167-
`export default {
198+
writeAdrAndRule(
199+
"SEC-006",
200+
`export default {
168201
rules: {
169202
"read-symlink": {
170203
description: "Attempt to read symlinked file",
@@ -175,36 +208,29 @@ describe("check command security", () => {
175208
},
176209
};
177210
`
178-
);
179-
180-
const loaded = await loadRuleAdrs(tempDir);
181-
const result = await runChecks(tempDir, loaded);
182-
expect(result.results[0].error).toContain("symbolic link");
183-
184-
rmSync(outsideDir, { recursive: true, force: true });
185-
});
211+
);
186212

187-
test("blocks reads that tunnel out through a symlinked ancestor directory", async () => {
188-
// The leaf here is an ordinary file — only an ANCESTOR is the symlink, so
189-
// a leaf-only lstat reports "not a link" while the OS still resolves the
190-
// real path outside the project and reads it.
191-
const outsideDir = mkdtempSync(join(tmpdir(), "archgate-outside-"));
192-
writeFileSync(join(outsideDir, "secret.txt"), "sensitive data");
193-
194-
try {
195-
// "junction" is ignored on POSIX (plain symlink) but on Windows creates
196-
// a directory junction, which needs no admin privileges and which
197-
// lstat() reports as a symbolic link — so unlike the file-symlink test
198-
// above, this case runs for real on every platform instead of skipping.
199-
symlinkSync(outsideDir, join(tempDir, "src", "linkdir"), "junction");
200-
} catch {
201-
rmSync(outsideDir, { recursive: true, force: true });
202-
return;
213+
const loaded = await loadRuleAdrs(tempDir);
214+
const result = await runChecks(tempDir, loaded);
215+
expect(result.results[0].error).toContain("symbolic link");
203216
}
217+
);
218+
219+
test.skipIf(!DIR_LINKS)(
220+
"blocks reads that tunnel out through a symlinked ancestor directory",
221+
async () => {
222+
// The leaf here is an ordinary file — only an ANCESTOR is the symlink, so
223+
// a leaf-only lstat reports "not a link" while the OS still resolves the
224+
// real path outside the project and reads it.
225+
const outsideDir = makeOutsideDir();
226+
writeFileSync(join(outsideDir, "secret.txt"), "sensitive data");
227+
// "junction" is ignored on POSIX; on Windows it needs no elevation and
228+
// lstat reports it as a symlink, so this runs on every platform.
229+
symlinkSync(outsideDir, join(tempDir, "src", "linkdir"), "junction");
204230

205-
writeAdrAndRule(
206-
"SEC-007",
207-
`export default {
231+
writeAdrAndRule(
232+
"SEC-007",
233+
`export default {
208234
rules: {
209235
"read-through-symlinked-dir": {
210236
description: "Attempt to read a real file via a symlinked parent",
@@ -215,15 +241,14 @@ describe("check command security", () => {
215241
},
216242
};
217243
`
218-
);
219-
220-
const loaded = await loadRuleAdrs(tempDir);
221-
const result = await runChecks(tempDir, loaded);
222-
expect(result.results[0].error).toContain("access denied");
223-
expect(result.results[0].error).toContain("symbolic link");
244+
);
224245

225-
rmSync(outsideDir, { recursive: true, force: true });
226-
});
246+
const loaded = await loadRuleAdrs(tempDir);
247+
const result = await runChecks(tempDir, loaded);
248+
expect(result.results[0].error).toContain("access denied");
249+
expect(result.results[0].error).toContain("symbolic link");
250+
}
251+
);
227252

228253
test("allows reads under real nested directories (no false positives)", async () => {
229254
// Guards the ancestor walk against over-rejecting: a deep, entirely real

0 commit comments

Comments
 (0)