diff --git a/pm-stack/dispatch/src/validate.ts b/pm-stack/dispatch/src/validate.ts index 973a01eb3b..30922208ad 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,88 @@ export function resolveSessionDirectory( if (scoped === undefined) { throw new ValidationError(`directory: no repo directory is configured for ${repo}`); } - const root = normalizeDirectory(scoped); + const budget: SymlinkBudget = { expansions: 0 }; + const root = canonicalizeDirectory(scoped, budget); if (directory === undefined || directory.trim() === "") return root; - const norm = normalizeDirectory(directory); - if (norm === root || norm.startsWith(`${root}/`)) return norm; + 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`, ); } -/** 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. */ +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}"`); } - 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, budget, depth); + } + return resolved; +} + +function resolveComponent(path: string, budget: SymlinkBudget, 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}`; + // 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 + // 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 `/${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..a602eb6c68 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,106 @@ 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("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("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"); + 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); + }); +});