Skip to content

Commit c607864

Browse files
committed
fix(webview-message-handler): enforce workspace containment for markdown-sourced openFile requests
1 parent f780647 commit c607864

20 files changed

Lines changed: 247 additions & 4 deletions
Lines changed: 192 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,192 @@
1+
// npx vitest core/webview/__tests__/webviewMessageHandler.openFile.spec.ts
2+
3+
import { describe, it, expect, vi, beforeEach } from "vitest"
4+
import * as nodePath from "path"
5+
import * as vscode from "vscode"
6+
import { openFile } from "../../../integrations/misc/open-file"
7+
import { webviewMessageHandler } from "../webviewMessageHandler"
8+
import type { ClineProvider } from "../ClineProvider"
9+
import type { Task } from "../../task/Task"
10+
11+
vi.mock("../../../api/providers/fetchers/modelCache")
12+
13+
vi.mock("vscode", () => ({
14+
window: {
15+
showInformationMessage: vi.fn(),
16+
showErrorMessage: vi.fn(),
17+
showTextDocument: vi.fn(),
18+
},
19+
workspace: {
20+
workspaceFolders: [{ uri: { fsPath: "/mock/workspace" } }],
21+
openTextDocument: vi.fn().mockResolvedValue({}),
22+
},
23+
commands: {
24+
executeCommand: vi.fn(),
25+
},
26+
}))
27+
28+
vi.mock("../../../i18n", () => ({
29+
// Echo the key with params serialized so tests can assert the full
30+
// message arguments without loading a real i18n catalogue.
31+
t: vi.fn((key: string, params?: Record<string, unknown>) => (params ? `${key}:${JSON.stringify(params)}` : key)),
32+
}))
33+
34+
vi.mock("../../../utils/fs")
35+
vi.mock("../../../utils/path")
36+
vi.mock("../../../utils/globalContext")
37+
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+
}))
50+
51+
vi.mock("../../mentions/resolveImageMentions", () => ({
52+
resolveImageMentions: vi.fn(async ({ text, images }: { text: string; images?: string[] }) => ({
53+
text,
54+
images: [...(images ?? [])],
55+
})),
56+
}))
57+
58+
// Mock the openFile module so the test observes the handler's resolved path and
59+
// proves markdown-sourced requests never reach out-of-workspace targets.
60+
vi.mock("../../../integrations/misc/open-file", () => ({
61+
openFile: vi.fn().mockResolvedValue(undefined),
62+
}))
63+
64+
const MOCK_CWD = "/mock/workspace/project"
65+
66+
const mockProvider = {
67+
getState: vi.fn(),
68+
postMessageToWebview: vi.fn(),
69+
customModesManager: {
70+
getCustomModes: vi.fn(),
71+
deleteCustomMode: vi.fn(),
72+
},
73+
context: {
74+
extensionPath: "/mock/extension/path",
75+
globalStorageUri: { fsPath: "/mock/global/storage" },
76+
},
77+
contextProxy: {
78+
context: {
79+
extensionPath: "/mock/extension/path",
80+
globalStorageUri: { fsPath: "/mock/global/storage" },
81+
},
82+
setValue: vi.fn(),
83+
getValue: vi.fn(),
84+
},
85+
log: vi.fn(),
86+
postStateToWebview: vi.fn(),
87+
getCurrentTask: vi.fn().mockReturnValue({ cwd: MOCK_CWD }),
88+
getTaskWithId: vi.fn(),
89+
createTaskWithHistoryItem: vi.fn(),
90+
cwd: MOCK_CWD,
91+
} as unknown as ClineProvider
92+
93+
describe("webviewMessageHandler - openFile markdown workspace containment", () => {
94+
beforeEach(() => {
95+
vi.clearAllMocks()
96+
// The containment logic only reads `cwd`; a full Task would be noise. The single
97+
// assertion is safe because Task is structurally compatible with the stub.
98+
vi.mocked(mockProvider.getCurrentTask).mockReturnValue({ cwd: MOCK_CWD } as Task)
99+
;(mockProvider as { cwd?: string }).cwd = MOCK_CWD
100+
})
101+
102+
// MarkdownBlock tags its openFile posts with fromMarkdown, flagging the
103+
// request as sourced from untrusted task markdown.
104+
it("opens a markdown file within the workspace using a relative path", async () => {
105+
await webviewMessageHandler(mockProvider, {
106+
type: "openFile",
107+
text: "src/index.ts",
108+
values: { line: 3, fromMarkdown: true },
109+
})
110+
111+
expect(openFile).toHaveBeenCalledWith(nodePath.resolve(MOCK_CWD, "src/index.ts"), {
112+
line: 3,
113+
fromMarkdown: true,
114+
})
115+
expect(vscode.window.showErrorMessage).not.toHaveBeenCalled()
116+
})
117+
118+
it("rejects a markdown relative path that traverses outside the workspace", async () => {
119+
await webviewMessageHandler(mockProvider, {
120+
type: "openFile",
121+
text: "../../.env",
122+
values: { fromMarkdown: true },
123+
})
124+
125+
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+
)
129+
})
130+
131+
it("rejects a markdown absolute path outside the workspace", async () => {
132+
await webviewMessageHandler(mockProvider, {
133+
type: "openFile",
134+
text: "/etc/passwd",
135+
values: { fromMarkdown: true },
136+
})
137+
138+
expect(openFile).not.toHaveBeenCalled()
139+
expect(vscode.window.showErrorMessage).toHaveBeenCalledWith(
140+
'common:errors.cannot_access_path:{"path":"/etc/passwd","error":"common:errors.path_outside_workspace"}',
141+
)
142+
})
143+
144+
it("opens a markdown file using an absolute path within the workspace", async () => {
145+
await webviewMessageHandler(mockProvider, {
146+
type: "openFile",
147+
text: `${MOCK_CWD}/src/index.ts`,
148+
values: { fromMarkdown: true },
149+
})
150+
151+
expect(openFile).toHaveBeenCalledWith(`${MOCK_CWD}/src/index.ts`, { fromMarkdown: true })
152+
expect(vscode.window.showErrorMessage).not.toHaveBeenCalled()
153+
})
154+
155+
// First-party callers (slash-command settings, modes, MCP) are not flagged
156+
// and keep the previous behavior, including global config files that live
157+
// outside the workspace.
158+
it("keeps legacy behavior for untagged callers opening paths outside the workspace", async () => {
159+
await webviewMessageHandler(mockProvider, {
160+
type: "openFile",
161+
text: "/global/roo/commands/my-command.md",
162+
})
163+
164+
expect(openFile).toHaveBeenCalledWith("/global/roo/commands/my-command.md", undefined)
165+
expect(vscode.window.showErrorMessage).not.toHaveBeenCalled()
166+
})
167+
168+
it("does nothing when no path is provided", async () => {
169+
await webviewMessageHandler(mockProvider, {
170+
type: "openFile",
171+
})
172+
173+
expect(openFile).not.toHaveBeenCalled()
174+
expect(vscode.window.showErrorMessage).not.toHaveBeenCalled()
175+
})
176+
177+
it("shows an error when no workspace cwd is available", async () => {
178+
vi.mocked(mockProvider.getCurrentTask).mockReturnValue(undefined)
179+
;(mockProvider as { cwd?: string }).cwd = undefined
180+
181+
await webviewMessageHandler(mockProvider, {
182+
type: "openFile",
183+
text: "src/index.ts",
184+
values: { fromMarkdown: true },
185+
})
186+
187+
expect(openFile).not.toHaveBeenCalled()
188+
expect(vscode.window.showErrorMessage).toHaveBeenCalledWith(
189+
'common:errors.could_not_open_file:{"errorMessage":"common:errors.no_workspace"}',
190+
)
191+
})
192+
})

‎src/core/webview/webviewMessageHandler.ts‎

Lines changed: 37 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1515,13 +1515,46 @@ export const webviewMessageHandler = async (
15151515
}
15161516
}
15171517
break
1518-
case "openFile":
1519-
let filePath: string = message.text!
1518+
case "openFile": {
1519+
const rawPath = message.text || ""
1520+
if (!rawPath) {
1521+
break
1522+
}
1523+
// Task markdown links are untrusted, so markdown-sourced openFile
1524+
// requests (flagged by the webview with fromMarkdown) must resolve
1525+
// inside the current workspace. First-party callers (modes, MCP,
1526+
// slash-command settings) may legitimately open global config files
1527+
// outside the workspace, so they keep the previous behavior.
1528+
const fromMarkdown = message.values?.fromMarkdown === true
1529+
let filePath = rawPath
15201530
if (!path.isAbsolute(filePath)) {
1521-
filePath = path.join(getCurrentCwd(), filePath)
1531+
const cwd = getCurrentCwd()
1532+
if (!cwd) {
1533+
void vscode.window.showErrorMessage(
1534+
t("common:errors.could_not_open_file", { errorMessage: t("common:errors.no_workspace") }),
1535+
)
1536+
break
1537+
}
1538+
filePath = path.resolve(cwd, filePath)
1539+
}
1540+
// Workspace-boundary validation (defense in depth): the webview already
1541+
// rejects traversal in markdown anchors, but refuse any markdown path
1542+
// that still resolves outside the workspace.
1543+
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+
)
1550+
break
15221551
}
1523-
await openFile(filePath, message.values as { create?: boolean; content?: string; line?: number })
1552+
await openFile(
1553+
filePath,
1554+
message.values as { create?: boolean; content?: string; line?: number; fromMarkdown?: boolean },
1555+
)
15241556
break
1557+
}
15251558
case "readFileContent": {
15261559
const relPath = message.text || ""
15271560
if (!relPath) {

‎src/i18n/locales/ca/common.json‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎src/i18n/locales/de/common.json‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎src/i18n/locales/en/common.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@
5555
"failed_remove_directory": "Failed to remove task directory: {{error}}",
5656
"custom_storage_path_unusable": "Custom storage path \"{{path}}\" is unusable, will use default path",
5757
"cannot_access_path": "Cannot access path {{path}}: {{error}}",
58+
"path_outside_workspace": "Path is outside the workspace",
5859
"settings_import_failed": "Settings import failed: {{error}}.",
5960
"mistake_limit_guidance": "This may indicate a failure in the model's thought process or inability to use a tool properly, which can be mitigated with some user guidance (e.g. \"Try breaking down the task into smaller steps\").",
6061
"violated_organization_allowlist": "Failed to run task: the current profile isn't compatible with your organization settings",

‎src/i18n/locales/es/common.json‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎src/i18n/locales/fr/common.json‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎src/i18n/locales/hi/common.json‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎src/i18n/locales/id/common.json‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎src/i18n/locales/it/common.json‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)