From 0a79e33920f866aedddf96101418d41290fa3861 Mon Sep 17 00:00:00 2001 From: K <61059522+kahme247@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:47:43 +0200 Subject: [PATCH 1/2] fix(security): close listDirectory TOCTOU race (fixes #396) --- lib/hosts/workspace-listing.test.mjs | 99 ++++++++++++++++++++++++++++ lib/hosts/workspace-ops.ts | 19 +++++- 2 files changed, 115 insertions(+), 3 deletions(-) create mode 100644 lib/hosts/workspace-listing.test.mjs diff --git a/lib/hosts/workspace-listing.test.mjs b/lib/hosts/workspace-listing.test.mjs new file mode 100644 index 000000000..8ea847e30 --- /dev/null +++ b/lib/hosts/workspace-listing.test.mjs @@ -0,0 +1,99 @@ +import assert from "node:assert/strict"; +import fs, { mkdirSync, mkdtempSync, realpathSync, renameSync, rmSync, symlinkSync, unlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import test from "node:test"; +import { filePathApiSegments } from "../file-paths.ts"; +import { mockBuiltin } from "../../tests/mock-builtin.mjs"; + +/** A granted root with no live host: the direct-service pattern of + * workspace-git.test.mjs. `opsModule` supplies `createWorkspaceService` (a + * fresh import when the test fakes a builtin). */ +async function listingService(t, opsModule) { + const root = realpathSync(mkdtempSync(join(tmpdir(), "omp-listing-"))); + const previous = process.env.PI_CODING_AGENT_DIR; + process.env.PI_CODING_AGENT_DIR = join(root, "agent"); + const { grantWorkspaceRoot } = await import("./workspace-roots.ts"); + const { StagedUploads } = await import("./uploads.ts"); + const service = opsModule.createWorkspaceService(new StagedUploads(() => {}), () => {}); + t.after(() => { + service.stop(); + if (previous === undefined) delete process.env.PI_CODING_AGENT_DIR; + else process.env.PI_CODING_AGENT_DIR = previous; + rmSync(root, { recursive: true, force: true }); + }); + grantWorkspaceRoot(root); + return { root, service }; +} + +/** A granted root with no service: for tests that build their own service + * from a fresh module import. */ +async function listingRoot(t) { + const root = realpathSync(mkdtempSync(join(tmpdir(), "omp-listing-"))); + const previous = process.env.PI_CODING_AGENT_DIR; + process.env.PI_CODING_AGENT_DIR = join(root, "agent"); + const { grantWorkspaceRoot } = await import("./workspace-roots.ts"); + t.after(() => { + if (previous === undefined) delete process.env.PI_CODING_AGENT_DIR; + else process.env.PI_CODING_AGENT_DIR = previous; + rmSync(root, { recursive: true, force: true }); + }); + grantWorkspaceRoot(root); + return root; +} + +test("listFiles lists the authorized directory", async (t) => { + const opsModule = await import("./workspace-ops.ts"); + const { root, service } = await listingService(t, opsModule); + const dir = join(root, "dir"); + mkdirSync(dir); + writeFileSync(join(dir, "note.txt"), "inside\n"); + const result = await service.ops.listFiles({ segments: filePathApiSegments(dir), sessionId: null }, false); + assert.equal(result.ok, true); + assert.deepEqual(result.value.entries.map((entry) => entry.name), ["note.txt"]); +}); + +test("listFiles reports file_changed when the listed directory is swapped for a symlink mid-listing (#396)", async (t) => { + const root = await listingRoot(t); + const dir = join(root, "dir"); + const saved = join(root, "dir.saved"); + // Outside every granted root: a sibling temp directory, never granted. + const outsideRoot = realpathSync(mkdtempSync(join(tmpdir(), "omp-listing-outside-"))); + const outside = join(outsideRoot, "outside"); + mkdirSync(dir); + mkdirSync(outside); + writeFileSync(join(dir, "note.txt"), "inside\n"); + writeFileSync(join(outside, "OUTSIDE_MARKER.txt"), "outside\n"); + const realFs = fs; + let swapped = false; + // The swap lands after authorize (which runs before readdir) and before + // listDirectory's re-stat: exactly the window #396's parent swap exploits. + // The directory stays swapped, so the re-stat must see the outside + // directory's identity and refuse with 409 file_changed. + await mockBuiltin(t, "node:fs", { + readdirSync(path, options) { + if (!swapped && path === dir) { + swapped = true; + renameSync(dir, saved); + symlinkSync(outside, dir); + } + return realFs.readdirSync(path, options); + }, + }); + const fresh = await import("./workspace-ops.ts?fresh=396"); + const { StagedUploads } = await import("./uploads.ts"); + const freshService = fresh.createWorkspaceService(new StagedUploads(() => {}), () => {}); + t.after(() => freshService.stop()); + let result; + try { + result = await freshService.ops.listFiles({ segments: filePathApiSegments(dir), sessionId: null }, false); + } finally { + // The mocked readdir left the directory swapped; put it back so the + // fixture cleanup can remove it. + try { unlinkSync(dir); } catch { /* already a real directory */ } + try { renameSync(saved, dir); } catch { /* never swapped away */ } + rmSync(outsideRoot, { recursive: true, force: true }); + } + assert.equal(swapped, true, "the mocked readdir never ran for the listed directory"); + assert.deepEqual(result, { ok: false, status: 409, code: "file_changed", error: "The directory changed while it was being listed" }); +}); diff --git a/lib/hosts/workspace-ops.ts b/lib/hosts/workspace-ops.ts index 9141ef245..bc8586110 100644 --- a/lib/hosts/workspace-ops.ts +++ b/lib/hosts/workspace-ops.ts @@ -113,7 +113,21 @@ async function listDirectory(input: WorkspaceFileRequest, root: string | null) { insideRoot = existingPathWithinRootsChecker(new Set([root])); if (!insideRoot(checked.filePath)) throw new HostOpError(403, "outside_root", "Outside the explorer root"); } - const entries = fs.readdirSync(checked.filePath, { withFileTypes: true }) + const entries = fs.readdirSync(checked.filePath, { withFileTypes: true }); + // The directory was authorized above, but readdir runs after that check: a + // parent swap in between would list a directory outside the authorized + // root. Mirror openFile(): re-stat the same path and refuse when it is no + // longer the authorized directory (409 file_changed). + let listed: fs.Stats; + try { + listed = fs.statSync(checked.filePath); + } catch { + throw new HostOpError(409, "file_changed", "The directory changed while it was being listed"); + } + if (listed.dev !== checked.stat.dev || listed.ino !== checked.stat.ino) { + throw new HostOpError(409, "file_changed", "The directory changed while it was being listed"); + } + return { path: checked.filePath, entries: entries .flatMap((entry) => { const entryPath = path.join(checked.filePath, entry.name); const isDir = resolveDirentIsDirectory(entry, entryPath); @@ -127,8 +141,7 @@ async function listDirectory(input: WorkspaceFileRequest, root: string | null) { const outsideRoot = insideRoot !== null && isLink && !insideRoot(entryPath); return [{ name: entry.name, isDir: isDir ?? false, size: 0, modified: "", ...(linkTarget !== undefined && { linkTarget }), ...(outsideRoot && { outsideRoot }) }]; - }).sort((a, b) => a.isDir !== b.isDir ? (a.isDir ? -1 : 1) : a.name.localeCompare(b.name)); - return { path: checked.filePath, entries }; + }).sort((a, b) => a.isDir !== b.isDir ? (a.isDir ? -1 : 1) : a.name.localeCompare(b.name)) }; } async function openFile(input: WorkspaceFileRequest) { const checked = await access(input, true); From 161e19d190460e3029d4483465949c87f9ae97fd Mon Sep 17 00:00:00 2001 From: K <61059522+kahme247@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:34:37 +0200 Subject: [PATCH 2/2] Fix macOS/Windows Verify failures - agents-service: sameOnDiskEntry no longer trusts realpath alone to tell distinct hardlink entries apart: on macOS it collapses them, so renaming onto a distinct hardlink was silently accepted instead of throwing 'agent file already exists'. Names that are not case variants can never be the same directory entry; reject those before asking realpath anything. - workspace-listing test: match the listed directory by canonical path so the mocked readdir fires on Windows, where authorizeFileAccess hands listDirectory a native-canonical spelling (8.3 short names, drive-letter case) that differs from the test's spelling. --- lib/hosts/workspace-listing.test.mjs | 24 +++++++++++++++++++++++- lib/omp/agents-service.ts | 10 ++++++++-- 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/lib/hosts/workspace-listing.test.mjs b/lib/hosts/workspace-listing.test.mjs index 8ea847e30..63bf74694 100644 --- a/lib/hosts/workspace-listing.test.mjs +++ b/lib/hosts/workspace-listing.test.mjs @@ -70,9 +70,31 @@ test("listFiles reports file_changed when the listed directory is swapped for a // listDirectory's re-stat: exactly the window #396's parent swap exploits. // The directory stays swapped, so the re-stat must see the outside // directory's identity and refuse with 409 file_changed. + // authorizeFileAccess hands listDirectory the native-canonical spelling of + // the directory, which on Windows need not equal this test's spelling + // (8.3 short names, drive-letter case): compare canonical paths so the + // mock fires on every platform. + const canonicalDir = (() => { + try { + const native = realFs.realpathSync.native ?? realFs.realpathSync; + return native(dir); + } catch { + return dir; + } + })(); + const isListedDirectory = (spelled) => { + const candidate = typeof spelled === "string" ? spelled : spelled.toString(); + if (candidate === dir || candidate === canonicalDir) return true; + try { + const native = realFs.realpathSync.native ?? realFs.realpathSync; + return native(candidate) === canonicalDir; + } catch { + return false; + } + }; await mockBuiltin(t, "node:fs", { readdirSync(path, options) { - if (!swapped && path === dir) { + if (!swapped && isListedDirectory(path)) { swapped = true; renameSync(dir, saved); symlinkSync(outside, dir); diff --git a/lib/omp/agents-service.ts b/lib/omp/agents-service.ts index 74431b61f..87d3a951a 100644 --- a/lib/omp/agents-service.ts +++ b/lib/omp/agents-service.ts @@ -234,9 +234,15 @@ function sameAgentPath(left: string, right: string): boolean { // resolves both names to the same directory entry even though the POSIX // string compare differs. realpathSync.native (realpath(3)) returns the // on-disk casing — the JS realpathSync preserves input casing — so case -// aliases compare equal while distinct hardlink entries to the same inode -// (a real name collision) stay distinct. +// aliases compare equal. +// Distinct hardlink entries to the same inode (a real name collision) must +// stay distinct — but realpath alone cannot be trusted for that on macOS: +// Verify failed there with the hardlink collision silently accepted, while +// the same test passes on Linux and Windows. Names that are not case +// variants of each other can never be the same directory entry, so reject +// those before asking realpath anything. function sameOnDiskEntry(left: string, right: string): boolean { + if (basename(resolve(left)).toLowerCase() !== basename(resolve(right)).toLowerCase()) return false; try { return realpathSync.native(left) === realpathSync.native(right); } catch {