Skip to content

Commit e98713a

Browse files
committed
fix(webview-message-handler): harden markdown containment against encoded and symlinked paths
Address the automated review findings on the split PR: percent-decode tagged openFile paths to a fixed point at the containment boundary (openFile decodes after the check, so %2e%2e traversal would escape only after that later decode), and re-check containment on the real filesystem path so a workspace-internal symlink cannot resolve outside the workspace (fail closed; unresolvable targets reject). Tests now exercise the production isPathOutsideWorkspace against a mutable mock workspace (multi-root, no-folders cases) and a deterministic realpath model: encoded and double-encoded traversal rejected, legitimately encoded filenames still open, symlink escape rejected, file creation under a new directory allowed.
1 parent c607864 commit e98713a

3 files changed

Lines changed: 276 additions & 29 deletions

File tree

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

Lines changed: 152 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import { describe, it, expect, vi, beforeEach } from "vitest"
44
import * as nodePath from "path"
5+
import * as nodeFs from "fs"
56
import * as vscode from "vscode"
67
import { openFile } from "../../../integrations/misc/open-file"
78
import { webviewMessageHandler } from "../webviewMessageHandler"
@@ -10,14 +11,36 @@ import type { Task } from "../../task/Task"
1011

1112
vi.mock("../../../api/providers/fetchers/modelCache")
1213

14+
// Platform-native mock roots: the production isPathOutsideWorkspace resolves
15+
// with node's path module, so POSIX-style roots would not match on Windows.
16+
const IS_WIN = process.platform === "win32"
17+
const WORKSPACE_ROOT = IS_WIN ? "C:\\mock\\workspace" : "/mock/workspace"
18+
const OTHER_ROOT = IS_WIN ? "C:\\mock\\workspace2" : "/mock/workspace2"
19+
const OUTSIDE_ROOT = IS_WIN ? "C:\\outside" : "/outside"
20+
const MOCK_CWD = nodePath.join(WORKSPACE_ROOT, "project")
21+
const OUTSIDE_ABS = nodePath.join(OUTSIDE_ROOT, "passwd")
22+
23+
// Mirrors the i18n mock's echo format so assertions are exact on every platform.
24+
const cannotAccessPathError = (pathValue: string) =>
25+
`common:errors.cannot_access_path:${JSON.stringify({ path: pathValue, error: "common:errors.path_outside_workspace" })}`
26+
27+
// Mutable holder for the vscode mock (vi.mock factories are hoisted above the
28+
// constants above): tests reassign the workspace folders per case, and the
29+
// production isPathOutsideWorkspace reads them through this getter.
30+
const vscodeState = vi.hoisted(() => ({
31+
workspaceFolders: [] as { uri: { fsPath: string } }[],
32+
}))
33+
1334
vi.mock("vscode", () => ({
1435
window: {
1536
showInformationMessage: vi.fn(),
1637
showErrorMessage: vi.fn(),
1738
showTextDocument: vi.fn(),
1839
},
1940
workspace: {
20-
workspaceFolders: [{ uri: { fsPath: "/mock/workspace" } }],
41+
get workspaceFolders() {
42+
return vscodeState.workspaceFolders
43+
},
2144
openTextDocument: vi.fn().mockResolvedValue({}),
2245
},
2346
commands: {
@@ -35,18 +58,9 @@ vi.mock("../../../utils/fs")
3558
vi.mock("../../../utils/path")
3659
vi.mock("../../../utils/globalContext")
3760

38-
// Hand-rolled containment check mirroring isPathOutsideWorkspace, but resolving
39-
// the workspace root too so the mock works on both POSIX and Windows test runs.
40-
vi.mock("../../../utils/pathUtils", () => ({
41-
isPathOutsideWorkspace: vi.fn((filePath: string) => {
42-
const nodePath = require("path")
43-
const normalized = nodePath.resolve(filePath)
44-
const workspaceRoot = nodePath.resolve("/mock/workspace")
45-
if (normalized === workspaceRoot) return false
46-
if (normalized.startsWith(workspaceRoot + nodePath.sep)) return false
47-
return true
48-
}),
49-
}))
61+
// The real utils/pathUtils runs unmocked on purpose: the handler's
62+
// containment must be exercised through the production predicate (lexical
63+
// and realpath-based), not a hand-rolled copy.
5064

5165
vi.mock("../../mentions/resolveImageMentions", () => ({
5266
resolveImageMentions: vi.fn(async ({ text, images }: { text: string; images?: string[] }) => ({
@@ -61,7 +75,14 @@ vi.mock("../../../integrations/misc/open-file", () => ({
6175
openFile: vi.fn().mockResolvedValue(undefined),
6276
}))
6377

64-
const MOCK_CWD = "/mock/workspace/project"
78+
// Deterministic real-filesystem model for the realpath-based containment:
79+
// explicit symlink targets plus a set of "existing" paths; everything else is
80+
// ENOENT, so the real-path helper walks up to the deepest existing ancestor.
81+
// Keeps the tests portable without touching the real filesystem.
82+
const realWorld = vi.hoisted(() => ({
83+
existing: new Set<string>(),
84+
symlinks: new Map<string, string>(),
85+
}))
6586

6687
const mockProvider = {
6788
getState: vi.fn(),
@@ -93,6 +114,24 @@ const mockProvider = {
93114
describe("webviewMessageHandler - openFile markdown workspace containment", () => {
94115
beforeEach(() => {
95116
vi.clearAllMocks()
117+
vscodeState.workspaceFolders = [{ uri: { fsPath: WORKSPACE_ROOT } }]
118+
realWorld.existing.clear()
119+
realWorld.symlinks.clear()
120+
realWorld.existing.add(WORKSPACE_ROOT)
121+
realWorld.existing.add(MOCK_CWD)
122+
vi.spyOn(nodeFs.promises, "realpath").mockImplementation(async (p: string | URL) => {
123+
const key = String(p)
124+
const symlink = realWorld.symlinks.get(key)
125+
if (symlink) {
126+
return symlink
127+
}
128+
if (realWorld.existing.has(key)) {
129+
return key
130+
}
131+
const err = new Error(`ENOENT: no such file or directory, realpath '${key}'`)
132+
;(err as NodeJS.ErrnoException).code = "ENOENT"
133+
throw err
134+
})
96135
// The containment logic only reads `cwd`; a full Task would be noise. The single
97136
// assertion is safe because Task is structurally compatible with the stub.
98137
vi.mocked(mockProvider.getCurrentTask).mockReturnValue({ cwd: MOCK_CWD } as Task)
@@ -123,35 +162,126 @@ describe("webviewMessageHandler - openFile markdown workspace containment", () =
123162
})
124163

125164
expect(openFile).not.toHaveBeenCalled()
126-
expect(vscode.window.showErrorMessage).toHaveBeenCalledWith(
127-
'common:errors.cannot_access_path:{"path":"../../.env","error":"common:errors.path_outside_workspace"}',
128-
)
165+
expect(vscode.window.showErrorMessage).toHaveBeenCalledWith(cannotAccessPathError("../../.env"))
129166
})
130167

131168
it("rejects a markdown absolute path outside the workspace", async () => {
132169
await webviewMessageHandler(mockProvider, {
133170
type: "openFile",
134-
text: "/etc/passwd",
171+
text: OUTSIDE_ABS,
172+
values: { fromMarkdown: true },
173+
})
174+
175+
expect(openFile).not.toHaveBeenCalled()
176+
expect(vscode.window.showErrorMessage).toHaveBeenCalledWith(cannotAccessPathError(OUTSIDE_ABS))
177+
})
178+
179+
it("opens a markdown file using an absolute path within the workspace", async () => {
180+
await webviewMessageHandler(mockProvider, {
181+
type: "openFile",
182+
text: nodePath.join(MOCK_CWD, "src/index.ts"),
183+
values: { fromMarkdown: true },
184+
})
185+
186+
expect(openFile).toHaveBeenCalledWith(nodePath.join(MOCK_CWD, "src/index.ts"), { fromMarkdown: true })
187+
expect(vscode.window.showErrorMessage).not.toHaveBeenCalled()
188+
})
189+
190+
// openFile decodes the path AFTER the containment checks, so percent-encoded
191+
// traversal must be decoded at the containment boundary instead.
192+
it("rejects a percent-encoded traversal (%2e%2e) posted by the webview", async () => {
193+
await webviewMessageHandler(mockProvider, {
194+
type: "openFile",
195+
text: "./%2e%2e/%2e%2e/.env",
196+
values: { fromMarkdown: true },
197+
})
198+
199+
expect(openFile).not.toHaveBeenCalled()
200+
expect(vscode.window.showErrorMessage).toHaveBeenCalledWith(cannotAccessPathError("./%2e%2e/%2e%2e/.env"))
201+
})
202+
203+
it("rejects a double-encoded traversal (%252e%252e) that only escapes after two decodes", async () => {
204+
await webviewMessageHandler(mockProvider, {
205+
type: "openFile",
206+
text: "./%252e%252e/%252e%252e/.env",
135207
values: { fromMarkdown: true },
136208
})
137209

138210
expect(openFile).not.toHaveBeenCalled()
139211
expect(vscode.window.showErrorMessage).toHaveBeenCalledWith(
140-
'common:errors.cannot_access_path:{"path":"/etc/passwd","error":"common:errors.path_outside_workspace"}',
212+
cannotAccessPathError("./%252e%252e/%252e%252e/.env"),
141213
)
142214
})
143215

144-
it("opens a markdown file using an absolute path within the workspace", async () => {
216+
it("opens a legitimately percent-encoded filename within the workspace", async () => {
145217
await webviewMessageHandler(mockProvider, {
146218
type: "openFile",
147-
text: `${MOCK_CWD}/src/index.ts`,
219+
text: "src/report%202024.txt",
148220
values: { fromMarkdown: true },
149221
})
150222

151-
expect(openFile).toHaveBeenCalledWith(`${MOCK_CWD}/src/index.ts`, { fromMarkdown: true })
223+
expect(openFile).toHaveBeenCalledWith(nodePath.join(MOCK_CWD, "src/report 2024.txt"), { fromMarkdown: true })
152224
expect(vscode.window.showErrorMessage).not.toHaveBeenCalled()
153225
})
154226

227+
// Lexical containment cannot see symlinks: a link inside the workspace may
228+
// resolve to a target outside it.
229+
it("rejects a symlink inside the workspace that resolves outside of it", async () => {
230+
realWorld.symlinks.set(nodePath.join(MOCK_CWD, "link.txt"), nodePath.join(OUTSIDE_ROOT, "secret.txt"))
231+
232+
await webviewMessageHandler(mockProvider, {
233+
type: "openFile",
234+
text: "link.txt",
235+
values: { fromMarkdown: true },
236+
})
237+
238+
expect(openFile).not.toHaveBeenCalled()
239+
expect(vscode.window.showErrorMessage).toHaveBeenCalledWith(cannotAccessPathError("link.txt"))
240+
})
241+
242+
it("allows creating a new file under a new directory inside the workspace", async () => {
243+
await webviewMessageHandler(mockProvider, {
244+
type: "openFile",
245+
text: "newdir/note.txt",
246+
values: { create: true, fromMarkdown: true },
247+
})
248+
249+
// The target does not exist yet, so containment is verified against its
250+
// deepest existing ancestor (MOCK_CWD), which is inside the workspace.
251+
expect(openFile).toHaveBeenCalledWith(nodePath.join(MOCK_CWD, "newdir/note.txt"), {
252+
create: true,
253+
fromMarkdown: true,
254+
})
255+
expect(vscode.window.showErrorMessage).not.toHaveBeenCalled()
256+
})
257+
258+
it("accepts a tagged path inside a second workspace folder (multi-root)", async () => {
259+
vscodeState.workspaceFolders = [{ uri: { fsPath: WORKSPACE_ROOT } }, { uri: { fsPath: OTHER_ROOT } }]
260+
realWorld.existing.add(OTHER_ROOT)
261+
262+
await webviewMessageHandler(mockProvider, {
263+
type: "openFile",
264+
text: nodePath.join(OTHER_ROOT, "x.ts"),
265+
values: { fromMarkdown: true },
266+
})
267+
268+
expect(openFile).toHaveBeenCalledWith(nodePath.join(OTHER_ROOT, "x.ts"), { fromMarkdown: true })
269+
expect(vscode.window.showErrorMessage).not.toHaveBeenCalled()
270+
})
271+
272+
it("rejects a tagged request when no workspace folders are configured", async () => {
273+
vscodeState.workspaceFolders = []
274+
275+
await webviewMessageHandler(mockProvider, {
276+
type: "openFile",
277+
text: "src/index.ts",
278+
values: { fromMarkdown: true },
279+
})
280+
281+
expect(openFile).not.toHaveBeenCalled()
282+
expect(vscode.window.showErrorMessage).toHaveBeenCalledWith(cannotAccessPathError("src/index.ts"))
283+
})
284+
155285
// First-party callers (slash-command settings, modes, MCP) are not flagged
156286
// and keep the previous behavior, including global config files that live
157287
// outside the workspace.

‎src/core/webview/webviewMessageHandler.ts‎

Lines changed: 30 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ import { openMention } from "../mentions"
8383
import { resolveImageMentions } from "../mentions/resolveImageMentions"
8484
import { RooIgnoreController } from "../ignore/RooIgnoreController"
8585
import { getWorkspacePath } from "../../utils/path"
86-
import { isPathOutsideWorkspace } from "../../utils/pathUtils"
86+
import { isPathOutsideWorkspace, decodeUntrustedPathToStable, isRealPathOutsideWorkspace } from "../../utils/pathUtils"
8787
import { Mode, defaultModeSlug } from "../../shared/modes"
8888
import { getModels, flushModels } from "../../api/providers/fetchers/modelCache"
8989
import { GetModelsOptions } from "../../shared/api"
@@ -1526,7 +1526,28 @@ export const webviewMessageHandler = async (
15261526
// slash-command settings) may legitimately open global config files
15271527
// outside the workspace, so they keep the previous behavior.
15281528
const fromMarkdown = message.values?.fromMarkdown === true
1529+
const rejectOutsideWorkspace = () => {
1530+
void vscode.window.showErrorMessage(
1531+
t("common:errors.cannot_access_path", {
1532+
path: rawPath,
1533+
error: t("common:errors.path_outside_workspace"),
1534+
}),
1535+
)
1536+
}
15291537
let filePath = rawPath
1538+
// Markdown link targets are URL syntax: percent-decode to a fixed point
1539+
// here, at the containment boundary. openFile decodes AFTER this check,
1540+
// so a request like `%2e%2e/%2e%2e/.env` would otherwise pass
1541+
// containment as a literal and escape only after that later decode.
1542+
if (fromMarkdown) {
1543+
const decoded = decodeUntrustedPathToStable(rawPath)
1544+
// Stryker disable next-line ConditionalExpression,BlockStatement: hostile non-stabilizing encodings are unreachable from the webview (its posts are plain link targets); the bound is defensive
1545+
if (decoded === null) {
1546+
rejectOutsideWorkspace()
1547+
break
1548+
}
1549+
filePath = decoded
1550+
}
15301551
if (!path.isAbsolute(filePath)) {
15311552
const cwd = getCurrentCwd()
15321553
if (!cwd) {
@@ -1541,12 +1562,14 @@ export const webviewMessageHandler = async (
15411562
// rejects traversal in markdown anchors, but refuse any markdown path
15421563
// that still resolves outside the workspace.
15431564
if (fromMarkdown && isPathOutsideWorkspace(filePath)) {
1544-
void vscode.window.showErrorMessage(
1545-
t("common:errors.cannot_access_path", {
1546-
path: rawPath,
1547-
error: t("common:errors.path_outside_workspace"),
1548-
}),
1549-
)
1565+
rejectOutsideWorkspace()
1566+
break
1567+
}
1568+
// Lexical containment cannot see symlinks: a link inside a workspace
1569+
// folder may resolve to a target outside the workspace. Re-check the
1570+
// real filesystem path (failing closed) before opening.
1571+
if (fromMarkdown && (await isRealPathOutsideWorkspace(filePath))) {
1572+
rejectOutsideWorkspace()
15501573
break
15511574
}
15521575
await openFile(

0 commit comments

Comments
 (0)