22
33import { describe , it , expect , vi , beforeEach } from "vitest"
44import * as nodePath from "path"
5+ import * as nodeFs from "fs"
56import * as vscode from "vscode"
67import { openFile } from "../../../integrations/misc/open-file"
78import { webviewMessageHandler } from "../webviewMessageHandler"
@@ -10,14 +11,36 @@ import type { Task } from "../../task/Task"
1011
1112vi . 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+
1334vi . 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")
3558vi . mock ( "../../../utils/path" )
3659vi . 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
5165vi . 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
6687const mockProvider = {
6788 getState : vi . fn ( ) ,
@@ -93,6 +114,24 @@ const mockProvider = {
93114describe ( "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.
0 commit comments