Skip to content

Commit 7f3668d

Browse files
committed
fix(extension): fail closed on dangling symlinks in realpath containment
A dangling symlink inside a workspace folder fails realpath with ENOENT without being a nonexistent path: the ancestor walk would treat it as missing and check the (in-workspace) ancestor instead, while a creation flow (mkdir -p) would follow the link and escape the workspace. ENOENT from realpath now lstat's the entry first: an existing symlink whose target cannot be resolved fails closed; a genuinely absent entry keeps walking to its deepest existing ancestor. Unexpected lstat errors also fail closed. Adds the regression tests: dangling symlink rejected (handler and helper), a symlinked workspace root realized to the real root, and the lstat EACCES fail-closed path
1 parent 1c076f0 commit 7f3668d

2 files changed

Lines changed: 145 additions & 3 deletions

File tree

‎src/core/webview/__tests__/webviewMessageHandler.openFile.spec.ts‎

Lines changed: 122 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import { describe, it, expect, vi, beforeEach } from "vitest"
44
import * as nodePath from "path"
55
import * as nodeFs from "fs"
6-
import type { PathLike } from "fs"
6+
import type { PathLike, Stats } from "fs"
77
import * as vscode from "vscode"
88
import { openFile } from "../../../integrations/misc/open-file"
99
import { webviewMessageHandler } from "../webviewMessageHandler"
@@ -84,6 +84,11 @@ vi.mock("../../../integrations/misc/open-file", () => ({
8484
const realWorld = vi.hoisted(() => ({
8585
existing: new Set<string>(),
8686
symlinks: new Map<string, string>(),
87+
// Existing entries whose symlink target is missing: realpath fails with
88+
// ENOENT, lstat still reports them as symlinks.
89+
dangling: new Set<string>(),
90+
// Paths where lstat must throw a specific error code (fail-closed test).
91+
lstatErrors: new Map<string, string>(),
8792
}))
8893

8994
const mockProvider = {
@@ -119,10 +124,19 @@ describe("webviewMessageHandler - openFile markdown workspace containment", () =
119124
vscodeState.workspaceFolders = [{ uri: { fsPath: WORKSPACE_ROOT } }]
120125
realWorld.existing.clear()
121126
realWorld.symlinks.clear()
127+
realWorld.dangling.clear()
128+
realWorld.lstatErrors.clear()
122129
realWorld.existing.add(WORKSPACE_ROOT)
123130
realWorld.existing.add(MOCK_CWD)
124131
vi.spyOn(nodeFs.promises, "realpath").mockImplementation(async (p: PathLike) => {
125132
const key = String(p)
133+
// A dangling symlink's target is missing, so realpath fails with
134+
// ENOENT exactly like a nonexistent path; lstat distinguishes it.
135+
if (realWorld.dangling.has(key)) {
136+
const err = new Error(`ENOENT: no such file or directory, realpath '${key}'`)
137+
;(err as NodeJS.ErrnoException).code = "ENOENT"
138+
throw err
139+
}
126140
const symlink = realWorld.symlinks.get(key)
127141
if (symlink) {
128142
return symlink
@@ -134,6 +148,25 @@ describe("webviewMessageHandler - openFile markdown workspace containment", () =
134148
;(err as NodeJS.ErrnoException).code = "ENOENT"
135149
throw err
136150
})
151+
// lstat does not follow the final entry: a dangling symlink is still a
152+
// directory entry and reports as a symlink, while a genuinely absent
153+
// entry is ENOENT.
154+
vi.spyOn(nodeFs.promises, "lstat").mockImplementation(async (p: PathLike) => {
155+
const key = String(p)
156+
const code = realWorld.lstatErrors.get(key)
157+
if (code) {
158+
const err = new Error(`${code}: error, lstat '${key}'`)
159+
;(err as NodeJS.ErrnoException).code = code
160+
throw err
161+
}
162+
if (realWorld.dangling.has(key) || realWorld.symlinks.has(key) || realWorld.existing.has(key)) {
163+
// Minimal test double; the containment code only reads isSymbolicLink().
164+
return { isSymbolicLink: () => realWorld.dangling.has(key) || realWorld.symlinks.has(key) } as Stats
165+
}
166+
const err = new Error(`ENOENT: no such file or directory, lstat '${key}'`)
167+
;(err as NodeJS.ErrnoException).code = "ENOENT"
168+
throw err
169+
})
137170
// The containment logic only reads `cwd`; a full Task would be noise. The single
138171
// assertion is safe because Task is structurally compatible with the stub.
139172
vi.mocked(mockProvider.getCurrentTask).mockReturnValue({ cwd: MOCK_CWD } as Task)
@@ -241,6 +274,56 @@ describe("webviewMessageHandler - openFile markdown workspace containment", () =
241274
expect(vscode.window.showErrorMessage).toHaveBeenCalledWith(cannotAccessPathError("link.txt"))
242275
})
243276

277+
// A dangling symlink inside the workspace — an existing entry whose target
278+
// is missing — must be rejected fail-closed: a creation flow (mkdir -p)
279+
// would follow it and could escape the workspace.
280+
it("rejects a tagged path that is a dangling symlink inside the workspace", async () => {
281+
realWorld.dangling.add(nodePath.join(MOCK_CWD, "link-out"))
282+
283+
await webviewMessageHandler(mockProvider, {
284+
type: "openFile",
285+
text: "link-out",
286+
values: { create: true, fromMarkdown: true },
287+
})
288+
289+
expect(openFile).not.toHaveBeenCalled()
290+
expect(vscode.window.showErrorMessage).toHaveBeenCalledWith(cannotAccessPathError("link-out"))
291+
})
292+
293+
// A workspace root that is itself a symlink must be realized before the
294+
// containment test: a target whose deepest existing ancestor resolves
295+
// inside the real root is inside the workspace.
296+
it("opens a markdown file when the workspace root is a symlink to the real root", async () => {
297+
const realRoot = IS_WIN ? "C:\\mock\\workspace-real" : "/mock/workspace-real"
298+
realWorld.existing.clear()
299+
realWorld.existing.add(realRoot)
300+
realWorld.symlinks.set(WORKSPACE_ROOT, realRoot)
301+
realWorld.symlinks.set(MOCK_CWD, nodePath.join(realRoot, "project"))
302+
303+
await webviewMessageHandler(mockProvider, {
304+
type: "openFile",
305+
text: "src/index.ts",
306+
values: { line: 3, fromMarkdown: true },
307+
})
308+
309+
expect(openFile).toHaveBeenCalledWith(nodePath.join(MOCK_CWD, "src/index.ts"), { line: 3, fromMarkdown: true })
310+
expect(vscode.window.showErrorMessage).not.toHaveBeenCalled()
311+
})
312+
313+
// An unexpected lstat error on the containment walk fails closed.
314+
it("fails closed when lstat errors during the realpath containment walk", async () => {
315+
realWorld.lstatErrors.set(nodePath.join(MOCK_CWD, "note.txt"), "EACCES")
316+
317+
await webviewMessageHandler(mockProvider, {
318+
type: "openFile",
319+
text: "note.txt",
320+
values: { fromMarkdown: true },
321+
})
322+
323+
expect(openFile).not.toHaveBeenCalled()
324+
expect(vscode.window.showErrorMessage).toHaveBeenCalledWith(cannotAccessPathError("note.txt"))
325+
})
326+
244327
it("allows creating a new file under a new directory inside the workspace", async () => {
245328
await webviewMessageHandler(mockProvider, {
246329
type: "openFile",
@@ -376,10 +459,19 @@ describe("utils/pathUtils containment helpers", () => {
376459
vscodeState.workspaceFolders = [{ uri: { fsPath: WORKSPACE_ROOT } }]
377460
realWorld.existing.clear()
378461
realWorld.symlinks.clear()
462+
realWorld.dangling.clear()
463+
realWorld.lstatErrors.clear()
379464
realWorld.existing.add(WORKSPACE_ROOT)
380465
realWorld.existing.add(MOCK_CWD)
381466
vi.spyOn(nodeFs.promises, "realpath").mockImplementation(async (p: PathLike) => {
382467
const key = String(p)
468+
// A dangling symlink's target is missing, so realpath fails with
469+
// ENOENT exactly like a nonexistent path; lstat distinguishes it.
470+
if (realWorld.dangling.has(key)) {
471+
const err = new Error(`ENOENT: no such file or directory, realpath '${key}'`)
472+
;(err as NodeJS.ErrnoException).code = "ENOENT"
473+
throw err
474+
}
383475
const symlink = realWorld.symlinks.get(key)
384476
if (symlink) {
385477
return symlink
@@ -391,6 +483,25 @@ describe("utils/pathUtils containment helpers", () => {
391483
;(err as NodeJS.ErrnoException).code = "ENOENT"
392484
throw err
393485
})
486+
// lstat does not follow the final entry: a dangling symlink is still a
487+
// directory entry and reports as a symlink, while a genuinely absent
488+
// entry is ENOENT.
489+
vi.spyOn(nodeFs.promises, "lstat").mockImplementation(async (p: PathLike) => {
490+
const key = String(p)
491+
const code = realWorld.lstatErrors.get(key)
492+
if (code) {
493+
const err = new Error(`${code}: error, lstat '${key}'`)
494+
;(err as NodeJS.ErrnoException).code = code
495+
throw err
496+
}
497+
if (realWorld.dangling.has(key) || realWorld.symlinks.has(key) || realWorld.existing.has(key)) {
498+
// Minimal test double; the containment code only reads isSymbolicLink().
499+
return { isSymbolicLink: () => realWorld.dangling.has(key) || realWorld.symlinks.has(key) } as Stats
500+
}
501+
const err = new Error(`ENOENT: no such file or directory, lstat '${key}'`)
502+
;(err as NodeJS.ErrnoException).code = "ENOENT"
503+
throw err
504+
})
394505
})
395506

396507
describe("decodeUntrustedPathToStable", () => {
@@ -437,6 +548,16 @@ describe("utils/pathUtils containment helpers", () => {
437548
await expect(isRealPathOutsideWorkspace(nodePath.join(MOCK_CWD, "link.txt"))).resolves.toBe(true)
438549
})
439550

551+
it("counts a dangling symlink as outside the workspace (fail-closed)", async () => {
552+
realWorld.dangling.add(nodePath.join(MOCK_CWD, "gone"))
553+
await expect(isRealPathOutsideWorkspace(nodePath.join(MOCK_CWD, "gone"))).resolves.toBe(true)
554+
})
555+
556+
it("fails closed when lstat returns an unexpected error", async () => {
557+
realWorld.lstatErrors.set(nodePath.join(MOCK_CWD, "blocked"), "EACCES")
558+
await expect(isRealPathOutsideWorkspace(nodePath.join(MOCK_CWD, "blocked"))).resolves.toBe(true)
559+
})
560+
440561
it("fails closed on an unexpected filesystem error", async () => {
441562
const err = new Error("EACCES: permission denied")
442563
;(err as NodeJS.ErrnoException).code = "EACCES"

‎src/utils/pathUtils.ts‎

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -61,8 +61,11 @@ export function decodeUntrustedPathToStable(filePath: string, maxIterations = 8)
6161
}
6262

6363
// Realpath of the deepest existing ancestor of `filePath` (the path itself
64-
// when it exists). Returns null on unexpected errors: containment for
65-
// untrusted paths fails closed.
64+
// when it exists). A dangling symlink — an entry that exists but whose target
65+
// cannot be resolved — fails realpath with ENOENT without being a
66+
// nonexistent path: creation flows (mkdir -p) would follow it and could
67+
// escape the workspace, so such entries fail closed. Returns null on
68+
// unexpected errors: containment for untrusted paths fails closed.
6669
async function realPathOfExistingAncestor(filePath: string): Promise<string | null> {
6770
let current = filePath
6871
for (;;) {
@@ -74,6 +77,24 @@ async function realPathOfExistingAncestor(filePath: string): Promise<string | nu
7477
if (code !== "ENOENT") {
7578
return null
7679
}
80+
// ENOENT from realpath is ambiguous: the entry may simply not exist
81+
// yet, or it may be a dangling symlink whose target is missing.
82+
// lstat does not follow the final entry, so it distinguishes the two.
83+
// A dangling symlink must fail closed (a creation flow would follow
84+
// it and could escape the workspace); a genuinely absent entry keeps
85+
// walking to its deepest existing ancestor.
86+
try {
87+
const stat = await fs.promises.lstat(current)
88+
if (stat.isSymbolicLink()) {
89+
return null
90+
}
91+
} catch (lstatError) {
92+
const lstatCode = (lstatError as NodeJS.ErrnoException).code
93+
// Stryker disable next-line EqualityOperator,ConditionalExpression,BlockStatement: only ENOENT means the entry is genuinely absent and the walk may continue; any other lstat error (EACCES, EIO, ...) must fail closed
94+
if (lstatCode !== "ENOENT") {
95+
return null
96+
}
97+
}
7798
const parent = path.dirname(current)
7899
// Stryker disable next-line EqualityOperator,ConditionalExpression,BlockStatement: root guard against a non-terminating walk (path.dirname stabilizes at the filesystem root)
79100
if (parent === current) {

0 commit comments

Comments
 (0)