From 8ee5bd09b144d6b98497f025bbdc6b41f7de0786 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 1 Nov 2026 16:24:14 -0600 Subject: [PATCH 1/3] fix(pm-dispatch): resolve symlinks before enforcing session-directory confinement (#3999) resolveSessionDirectory judged containment lexically, so committed in-clone symlinks escaped it: the code clone's worktrees link (to ~/.local/share/opencode/worktree/code) and the dangling nixpkgs link were both accepted. Both the clone root and the candidate are now canonicalized component-by-component (realpath per component, readlink resolution for dangling links, .. pops the resolved parent), and containment is judged on the resolved path; nonexistent tails append lexically onto the canonical prefix. Regressions cover outside-pointing, dangling, inside-pointing, ..-after-symlink, nonexistent-tail, and root-alias cases. Full dispatch suite 98/98; live probe against the real clone now rejects both committed links. --- pm-stack/dispatch/src/validate.ts | 68 +++++++++++++++----- pm-stack/dispatch/test/validate.test.ts | 83 +++++++++++++++++++++++++ 2 files changed, 136 insertions(+), 15 deletions(-) diff --git a/pm-stack/dispatch/src/validate.ts b/pm-stack/dispatch/src/validate.ts index 973a01eb3b..64ca42b4d3 100644 --- a/pm-stack/dispatch/src/validate.ts +++ b/pm-stack/dispatch/src/validate.ts @@ -2,6 +2,8 @@ // body validators for POST /v1/sessions and POST /v1/tasks. Pure functions — // unit-tested without a server. +import { lstatSync, readlinkSync, realpathSync } from "node:fs"; + export class ValidationError extends Error { status = 400; } @@ -151,11 +153,13 @@ export function parseSessionRequest(body: unknown): SessionRequest { /** Session-directory scoping for POST /v1/sessions (issues #2903, #2664). * One rule for every caller type (OIDC and bearer alike): a missing, empty, * or whitespace-only directory resolves to the target repo's clone, and an - * explicit directory must be an absolute, normalized path equal to or inside - * that clone. Relative paths, other repos' clones, and arbitrary absolute - * paths are rejected BEFORE any issue/task/session is created. (This - * supersedes the #2903-era bearer free-form directory; extra roots and - * allowlists stay out of scope per design issue #2668.) */ + * explicit directory must be an absolute path equal to or inside that + * clone AFTER symlink resolution (issue #3999). Relative paths, other + * repos' clones, arbitrary absolute paths, and in-clone paths whose + * resolved form escapes the clone (a committed symlink such as the + * code clone's worktrees or nixpkgs links) are rejected BEFORE any + * issue/task/session is created. Extra roots and allowlists stay out + * of scope per design issue #2668. */ export function resolveSessionDirectory( callerType: "oidc" | "bearer", repo: string, @@ -166,31 +170,65 @@ export function resolveSessionDirectory( if (scoped === undefined) { throw new ValidationError(`directory: no repo directory is configured for ${repo}`); } - const root = normalizeDirectory(scoped); + const root = canonicalizeDirectory(scoped); if (directory === undefined || directory.trim() === "") return root; - const norm = normalizeDirectory(directory); - if (norm === root || norm.startsWith(`${root}/`)) return norm; + const resolved = canonicalizeDirectory(directory); + if (resolved === root || resolved.startsWith(`${root}/`)) return resolved; throw new ValidationError( `directory: ${callerType} callers may only run inside the target repo clone (${root}) or a directory within it`, ); } -/** Lexical absolute-path normalization: collapses duplicate slashes, "." - * and ".." segments and trailing slashes. Relative paths are rejected. */ -function normalizeDirectory(d: string): string { +/** Canonicalize an absolute directory path: resolve each component's + * symlinks as it is appended, so a ".." segment pops the RESOLVED parent + * (kernel order), not the lexical one. A component that does not exist + * cannot be a symlink, so the remaining tail is appended lexically onto + * the canonical prefix (the nearest-existing-ancestor rule); a dangling + * symlink still resolves through its readlink target, so a committed + * link pointing outside the clone is judged by where it points, not by + * whether its target happens to exist on this machine. Relative paths + * are rejected. */ +function canonicalizeDirectory(d: string, depth = 0): string { if (!d.startsWith("/")) { throw new ValidationError(`directory: must be an absolute path, got "${d}"`); } - const parts: string[] = []; + if (depth > 40) { + throw new ValidationError(`directory: too many symlink levels in "${d}"`); + } + let resolved = "/"; for (const seg of d.split("/")) { if (seg === "" || seg === ".") continue; if (seg === "..") { - parts.pop(); + resolved = resolved.slice(0, resolved.lastIndexOf("/")) || "/"; continue; } - parts.push(seg); + const next = resolved === "/" ? `/${seg}` : `${resolved}/${seg}`; + resolved = resolveComponent(next, depth); + } + return resolved; +} + +function resolveComponent(path: string, depth: number): string { + try { + return realpathSync(path); + } catch { + // Nonexistent (or dangling): fall through to the symlink check. + } + try { + if (lstatSync(path).isSymbolicLink()) { + const target = readlinkSync(path); + const parent = path.slice(0, path.lastIndexOf("/")) || "/"; + const absolute = target.startsWith("/") + ? target + : parent === "/" + ? `/${target}` + : `${parent}/${target}`; + return canonicalizeDirectory(absolute, depth + 1); + } + } catch { + // Not present at all: a plain lexical component. } - return `/${parts.join("/")}`; + return path; } export interface TaskRequest { diff --git a/pm-stack/dispatch/test/validate.test.ts b/pm-stack/dispatch/test/validate.test.ts index dcccfc612d..bf0c49831f 100644 --- a/pm-stack/dispatch/test/validate.test.ts +++ b/pm-stack/dispatch/test/validate.test.ts @@ -1,4 +1,7 @@ import { describe, expect, test } from "bun:test"; +import { mkdtempSync, mkdirSync, realpathSync, rmSync, symlinkSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; import { ValidationError, parseModel, @@ -301,3 +304,83 @@ describe("session blank title/directory parsing (issue #2664)", () => { expect(r.directory).toBe("/home/user/git/code/pkgs"); }); }); + +describe("session directory symlink confinement (issue #3999)", () => { + // Fixture layout under a fresh temp dir: + // base/clone/ the repo clone (configured root) + // base/clone/inner/ a real in-clone directory + // base/outside/ a directory outside the clone + // base/outside/sub/ a subdirectory of the outside directory + // clone/worktrees -> base/outside (committed-link shape) + // clone/nixpkgs -> ../nixpkgs-missing (dangling, points outside) + // clone/local-link -> inner (points inside) + const base = realpathSync(mkdtempSync(join(tmpdir(), "dispatch-3999-"))); + const clone = join(base, "clone"); + const inner = join(clone, "inner"); + const outside = join(base, "outside"); + const outsideSub = join(outside, "sub"); + mkdirSync(inner, { recursive: true }); + mkdirSync(outsideSub, { recursive: true }); + symlinkSync(outside, join(clone, "worktrees"), "dir"); + symlinkSync("../nixpkgs-missing", join(clone, "nixpkgs"), "dir"); + symlinkSync(inner, join(clone, "local-link"), "dir"); + const repoDirs = { "developing-today/code": clone }; + const code = "developing-today/code"; + // realpathSync above canonicalizes base (e.g. /tmp -> /private/tmp), so + // expectations are built from the canonical fixture paths. + test("an in-clone symlink to an outside directory is rejected", () => { + expect(() => resolveSessionDirectory("oidc", code, join(clone, "worktrees"), repoDirs)).toThrow( + ValidationError, + ); + expect(() => + resolveSessionDirectory("bearer", code, join(clone, "worktrees", "sub"), repoDirs), + ).toThrow(ValidationError); + }); + + test("a dangling in-clone symlink pointing outside is rejected", () => { + expect(() => resolveSessionDirectory("oidc", code, join(clone, "nixpkgs"), repoDirs)).toThrow( + ValidationError, + ); + }); + + test("an in-clone symlink pointing inside the clone is accepted and resolved", () => { + expect(resolveSessionDirectory("oidc", code, join(clone, "local-link"), repoDirs)).toBe(inner); + }); + + test("'..' after a symlinked component pops the resolved parent", () => { + // Lexically clone/worktrees/../inner stays inside the clone; the + // kernel resolves worktrees first, so the real path is + // base/inner, which does NOT exist inside the clone - the parent + // of outside is base, so ../inner lands at base/inner (outside). + expect(() => + resolveSessionDirectory("oidc", code, `${clone}/worktrees/../inner`, repoDirs), + ).toThrow(ValidationError); + // And outside/sub/../sub resolves within the outside tree, still out. + expect(() => + resolveSessionDirectory("oidc", code, `${clone}/worktrees/sub/../sub`, repoDirs), + ).toThrow(ValidationError); + }); + + test("a nonexistent candidate inside the clone is accepted lexically", () => { + const candidate = join(clone, "new-dir", "deeper"); + expect(resolveSessionDirectory("oidc", code, candidate, repoDirs)).toBe(candidate); + }); + + test("a nonexistent candidate under an escaping symlink is rejected", () => { + expect(() => + resolveSessionDirectory("oidc", code, join(clone, "worktrees", "not-there"), repoDirs), + ).toThrow(ValidationError); + }); + + test("the clone root reached through a symlink is the same root", () => { + const alias = join(base, "clone-alias"); + symlinkSync(clone, alias, "dir"); + expect(resolveSessionDirectory("oidc", code, alias, repoDirs)).toBe(clone); + expect(resolveSessionDirectory("oidc", code, join(alias, "inner"), repoDirs)).toBe(inner); + }); + + test("fixture cleanup", () => { + rmSync(base, { recursive: true, force: true }); + expect(true).toBe(true); + }); +}); From e52d59915b2eb24829f47084ccd9f21330216610 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 1 Nov 2026 16:29:34 -0600 Subject: [PATCH 2/3] fix(pm-dispatch): propagate symlink-depth ValidationError in directory canonicalization (#3999) Codex P2 on PR #4032: resolveComponent caught every error from its recursive canonicalizeDirectory call, including the depth-limit ValidationError, so a cyclic symlink (loop -> loop/../loop) was re-expanded segment by segment instead of rejected. Rethrow ValidationError from the catch; filesystem misses still fall through to the lexical component. Regression test pins fast rejection of a cyclic link. --- pm-stack/dispatch/src/validate.ts | 7 ++++++- pm-stack/dispatch/test/validate.test.ts | 10 ++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/pm-stack/dispatch/src/validate.ts b/pm-stack/dispatch/src/validate.ts index 64ca42b4d3..1a3b077cc9 100644 --- a/pm-stack/dispatch/src/validate.ts +++ b/pm-stack/dispatch/src/validate.ts @@ -225,7 +225,12 @@ function resolveComponent(path: string, depth: number): string { : `${parent}/${target}`; return canonicalizeDirectory(absolute, depth + 1); } - } catch { + } catch (e) { + // Our own depth-limit error must terminate traversal, not be + // swallowed as a filesystem miss: with a cyclic symlink + // (loop -> loop/../loop) swallowing it lets the caller re-expand + // the cycle segment by segment (Codex review of PR #4032). + if (e instanceof ValidationError) throw e; // Not present at all: a plain lexical component. } return path; diff --git a/pm-stack/dispatch/test/validate.test.ts b/pm-stack/dispatch/test/validate.test.ts index bf0c49831f..91d0a9fb54 100644 --- a/pm-stack/dispatch/test/validate.test.ts +++ b/pm-stack/dispatch/test/validate.test.ts @@ -372,6 +372,16 @@ describe("session directory symlink confinement (issue #3999)", () => { ).toThrow(ValidationError); }); + test("a cyclic symlink is rejected by the depth limit, not expanded", () => { + symlinkSync("loop/../loop", join(clone, "loop"), "dir"); + expect(() => resolveSessionDirectory("oidc", code, join(clone, "loop"), repoDirs)).toThrow( + ValidationError, + ); + expect(() => + resolveSessionDirectory("oidc", code, `${clone}/loop/../loop`, repoDirs), + ).toThrow(ValidationError); + }); + test("the clone root reached through a symlink is the same root", () => { const alias = join(base, "clone-alias"); symlinkSync(clone, alias, "dir"); From 8789ace7e87f79be605d9fb41515906ac6319cc1 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 1 Nov 2026 16:36:00 -0600 Subject: [PATCH 3/3] fix(pm-dispatch): bound total symlink expansions across a directory resolution (#3999) Codex round 2 on PR #4032: the depth limit is per-recursion, so a chain of dangling links lN -> l(N-1)/../l(N-1) doubles expansions per level while never tripping it. A SymlinkBudget is now shared across the whole resolveSessionDirectory call (root + candidate, all recursions); following more than 40 readlink expansions total rejects with ValidationError, mirroring the kernel MAXSYMLINKS bound inside realpathSync. Regression test builds the 17-link chain and pins rejection; full dispatch suite 100/100. --- pm-stack/dispatch/src/validate.ts | 30 ++++++++++++++++++++----- pm-stack/dispatch/test/validate.test.ts | 13 +++++++++++ 2 files changed, 37 insertions(+), 6 deletions(-) diff --git a/pm-stack/dispatch/src/validate.ts b/pm-stack/dispatch/src/validate.ts index 1a3b077cc9..30922208ad 100644 --- a/pm-stack/dispatch/src/validate.ts +++ b/pm-stack/dispatch/src/validate.ts @@ -170,9 +170,10 @@ export function resolveSessionDirectory( if (scoped === undefined) { throw new ValidationError(`directory: no repo directory is configured for ${repo}`); } - const root = canonicalizeDirectory(scoped); + const budget: SymlinkBudget = { expansions: 0 }; + const root = canonicalizeDirectory(scoped, budget); if (directory === undefined || directory.trim() === "") return root; - const resolved = canonicalizeDirectory(directory); + const resolved = canonicalizeDirectory(directory, budget); if (resolved === root || resolved.startsWith(`${root}/`)) return resolved; throw new ValidationError( `directory: ${callerType} callers may only run inside the target repo clone (${root}) or a directory within it`, @@ -188,7 +189,11 @@ export function resolveSessionDirectory( * link pointing outside the clone is judged by where it points, not by * whether its target happens to exist on this machine. Relative paths * are rejected. */ -function canonicalizeDirectory(d: string, depth = 0): string { +interface SymlinkBudget { + expansions: number; +} + +function canonicalizeDirectory(d: string, budget: SymlinkBudget, depth = 0): string { if (!d.startsWith("/")) { throw new ValidationError(`directory: must be an absolute path, got "${d}"`); } @@ -203,12 +208,12 @@ function canonicalizeDirectory(d: string, depth = 0): string { continue; } const next = resolved === "/" ? `/${seg}` : `${resolved}/${seg}`; - resolved = resolveComponent(next, depth); + resolved = resolveComponent(next, budget, depth); } return resolved; } -function resolveComponent(path: string, depth: number): string { +function resolveComponent(path: string, budget: SymlinkBudget, depth: number): string { try { return realpathSync(path); } catch { @@ -223,7 +228,20 @@ function resolveComponent(path: string, depth: number): string { : parent === "/" ? `/${target}` : `${parent}/${target}`; - return canonicalizeDirectory(absolute, depth + 1); + // The budget is shared across the WHOLE resolution, not per + // recursion: a chain of dangling links shaped + // lN -> l(N-1)/../l(N-1) doubles the expansions per level while + // every individual recursion stays under the depth limit, so + // only a global cap keeps total work linear (Codex review + // round 2 of PR #4032). The kernel's per-syscall MAXSYMLINKS + // bound inside realpathSync has the same shape. + budget.expansions += 1; + if (budget.expansions > 40) { + throw new ValidationError( + `directory: too many symlink expansions resolving "${path}"`, + ); + } + return canonicalizeDirectory(absolute, budget, depth + 1); } } catch (e) { // Our own depth-limit error must terminate traversal, not be diff --git a/pm-stack/dispatch/test/validate.test.ts b/pm-stack/dispatch/test/validate.test.ts index 91d0a9fb54..a602eb6c68 100644 --- a/pm-stack/dispatch/test/validate.test.ts +++ b/pm-stack/dispatch/test/validate.test.ts @@ -382,6 +382,19 @@ describe("session directory symlink confinement (issue #3999)", () => { ).toThrow(ValidationError); }); + test("a dangling-link expansion chain is bounded by the shared budget", () => { + // l0 dangles; each lN names l(N-1) twice, so a per-recursion + // depth limit alone permits exponential expansions (Codex round + // 2). The shared budget must reject the chain outright. + symlinkSync("missing-target", join(clone, "l0"), "dir"); + for (let n = 1; n <= 17; n++) { + symlinkSync(`l${n - 1}/../l${n - 1}`, join(clone, `l${n}`), "dir"); + } + expect(() => resolveSessionDirectory("oidc", code, join(clone, "l17"), repoDirs)).toThrow( + ValidationError, + ); + }); + test("the clone root reached through a symlink is the same root", () => { const alias = join(base, "clone-alias"); symlinkSync(clone, alias, "dir");