Skip to content

Commit a2fd82c

Browse files
cliffhallclaude
andcommitted
fix(filesystem): harden path handling for new paths
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: cliffhall <[email protected]>
1 parent 69b53e9 commit a2fd82c

4 files changed

Lines changed: 158 additions & 4 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@modelcontextprotocol/server-filesystem": patch
3+
---
4+
5+
Harden path validation for new files and directories.

‎src/filesystem/__tests__/lib.test.ts‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,11 @@ const mockReaddir = vi.mocked(
4343
) => Promise<Dirent[]>,
4444
);
4545

46+
// The path resolver calls the plain overload, which lists names as strings.
47+
const mockReaddirNames = vi.mocked(
48+
fs.readdir as (path: PathLike) => Promise<string[]>,
49+
);
50+
4651
interface MockFileHandle {
4752
read: Mock;
4853
close: Mock;
@@ -356,6 +361,44 @@ describe("Lib Functions", () => {
356361
expect(result).toBe(path.resolve(newFilePath));
357362
});
358363

364+
it("checks a component no entry matches by spelling when the OS still finds it", async () => {
365+
// On a case-insensitive file system "LINK" opens the symlink listed as
366+
// "link"; it must be resolved and checked, not treated as missing.
367+
const base =
368+
process.platform === "win32" ? "C:\\Users\\test" : "/home/user";
369+
const outsideDir =
370+
process.platform === "win32" ? "C:\\outside" : "/outside";
371+
const enoentError = new Error("ENOENT") as NodeJS.ErrnoException;
372+
enoentError.code = "ENOENT";
373+
mockFs.realpath
374+
.mockRejectedValueOnce(enoentError)
375+
.mockResolvedValueOnce(base)
376+
.mockResolvedValueOnce(outsideDir);
377+
mockReaddirNames.mockResolvedValueOnce(["link"]);
378+
mockFs.lstat.mockResolvedValueOnce({} as Stats);
379+
380+
await expect(
381+
validatePath(path.join(base, "LINK", "a"), allowedDirs),
382+
).rejects.toThrow(
383+
`Access denied - symlink target outside allowed directories: ${outsideDir}`,
384+
);
385+
expect(mockFs.lstat).toHaveBeenCalledWith(path.join(base, "LINK"));
386+
});
387+
388+
it("reports an lstat failure other than ENOENT on an unmatched component as is", async () => {
389+
const base =
390+
process.platform === "win32" ? "C:\\Users\\test" : "/home/user";
391+
const enoentError = new Error("ENOENT") as NodeJS.ErrnoException;
392+
enoentError.code = "ENOENT";
393+
mockFs.realpath.mockRejectedValueOnce(enoentError);
394+
mockReaddirNames.mockResolvedValueOnce([]);
395+
mockFs.lstat.mockRejectedValueOnce(new Error("EACCES lstat"));
396+
397+
await expect(
398+
validatePath(path.join(base, "new", "f.txt"), allowedDirs),
399+
).rejects.toThrow("EACCES lstat");
400+
});
401+
359402
it("rejects when no ancestor directory exists at all", async () => {
360403
const newFilePath =
361404
process.platform === "win32"

‎src/filesystem/__tests__/server-paths.test.ts‎

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,23 @@ async function holdsBothNormalizationForms(): Promise<boolean> {
3535

3636
const distinctForms = await holdsBothNormalizationForms();
3737

38+
/** True when this file system finds "name" when asked for "NAME" (macOS and Windows by default). */
39+
async function foldsCase(): Promise<boolean> {
40+
const probe = await makeTempDir("mcp-case-probe-");
41+
try {
42+
await fs.mkdir(path.join(probe, "name"));
43+
await fs.lstat(path.join(probe, "NAME"));
44+
return true;
45+
} catch (error) {
46+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return false;
47+
throw error;
48+
} finally {
49+
await fs.rm(probe, { recursive: true, force: true });
50+
}
51+
}
52+
53+
const caseInsensitive = await foldsCase();
54+
3855
let dir: string;
3956
let outside: string;
4057
let conn: Connected;
@@ -199,6 +216,75 @@ describe("symlinks", () => {
199216
expect(await fs.readdir(outside)).toEqual(["secret.txt"]);
200217
});
201218

219+
describe.skipIf(!caseInsensitive)(
220+
"spelled with other letter case on a case-insensitive file system",
221+
() => {
222+
const refusal = () =>
223+
`Access denied - symlink target outside allowed directories: ${outside} not in ${dir}`;
224+
225+
it("refuses create_directory under a symlink that leaves", async () => {
226+
await fs.symlink(outside, path.join(dir, "link"), "junction");
227+
const result = await call(client, "create_directory", {
228+
path: path.join(dir, "LINK", "a"),
229+
});
230+
expect(textOf(result)).toBe(refusal());
231+
expect(await fs.readdir(outside)).toEqual(["secret.txt"]);
232+
});
233+
234+
it("refuses write_file when only an ancestor of the symlink is respelled", async () => {
235+
await fs.mkdir(path.join(dir, "sub"));
236+
await fs.symlink(outside, path.join(dir, "sub", "ln2"), "junction");
237+
const result = await call(client, "write_file", {
238+
path: path.join(dir, "SUB", "ln2", "nested.txt"),
239+
content: "x",
240+
});
241+
expect(textOf(result)).toBe(refusal());
242+
expect(await fs.readdir(outside)).toEqual(["secret.txt"]);
243+
});
244+
245+
it("refuses a move_file destination under a symlink that leaves", async () => {
246+
await fs.symlink(outside, path.join(dir, "link"), "junction");
247+
await fs.writeFile(path.join(dir, "note.txt"), "note");
248+
const result = await call(client, "move_file", {
249+
source: path.join(dir, "note.txt"),
250+
destination: path.join(dir, "lInK", "moved.txt"),
251+
});
252+
expect(textOf(result)).toBe(refusal());
253+
expect(await fs.readdir(outside)).toEqual(["secret.txt"]);
254+
expect(await fs.readFile(path.join(dir, "note.txt"), "utf8")).toBe(
255+
"note",
256+
);
257+
});
258+
259+
it("still writes a new file under a respelled directory that stays inside", async () => {
260+
await fs.mkdir(path.join(dir, "sub"));
261+
const result = await call(client, "write_file", {
262+
path: path.join(dir, "SUB", "new.txt"),
263+
content: "x",
264+
});
265+
expect(result.isError).toBeFalsy();
266+
expect(
267+
await fs.readFile(path.join(dir, "sub", "new.txt"), "utf8"),
268+
).toBe("x");
269+
});
270+
271+
it("refuses to write under a respelled dangling symlink, reporting a missing parent", async () => {
272+
await fs.symlink(
273+
path.join(outside, "not-yet"),
274+
path.join(dir, "dangling"),
275+
);
276+
const result = await call(client, "write_file", {
277+
path: path.join(dir, "DANGLING", "f.txt"),
278+
content: "x",
279+
});
280+
expect(textOf(result)).toBe(
281+
`Parent directory does not exist: ${path.join(dir, "DANGLING")}`,
282+
);
283+
await expect(fs.stat(path.join(outside, "not-yet"))).rejects.toThrow();
284+
});
285+
},
286+
);
287+
202288
it("refuses to write through a dangling symlink, reporting a missing parent", async () => {
203289
const link = path.join(dir, "dangling");
204290
await fs.symlink(path.join(outside, "not-yet"), link);

‎src/filesystem/lib.ts‎

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,17 @@ function respellAllowedDirectoryPrefix(
133133
return absolutePath;
134134
}
135135

136+
// Whether a directory entry of this name exists, without following it.
137+
async function entryExists(entryPath: string): Promise<boolean> {
138+
try {
139+
await fs.lstat(entryPath);
140+
return true;
141+
} catch (error) {
142+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return false;
143+
throw error;
144+
}
145+
}
146+
136147
async function resolveUnicodeEquivalentPath(
137148
absolutePath: string,
138149
allowedDirectories: readonly string[],
@@ -168,16 +179,25 @@ async function resolveUnicodeEquivalentPath(
168179
throw new Error(`Ambiguous Unicode path component: ${requestedPart}`);
169180
}
170181

171-
if (equivalentMatches.length === 0) {
182+
// When no entry matches by spelling, the requested name still goes to the
183+
// OS as it is: on a case-insensitive file system (macOS and Windows by
184+
// default) it can name an existing entry spelled with other letter case,
185+
// and that entry can be a symlink that leaves the allowed directories. So
186+
// it is resolved and checked like a match, and only a name that does not
187+
// exist at all (lstat, so a dangling symlink still counts as existing)
188+
// starts the missing tail.
189+
const candidate = path.join(
190+
currentPath,
191+
equivalentMatches[0] ?? requestedPart,
192+
);
193+
if (equivalentMatches.length === 0 && !(await entryExists(candidate))) {
172194
// Nothing below this point exists yet, so there are no symlinks left to
173195
// resolve. currentPath is already realpath'd and inside an allowed
174196
// directory; append the missing tail so create_directory can mkdir -p it.
175197
return path.join(currentPath, ...relativeParts.slice(index));
176198
}
177199

178-
currentPath = await fs.realpath(
179-
path.join(currentPath, equivalentMatches[0]),
180-
);
200+
currentPath = await fs.realpath(candidate);
181201
if (
182202
!isPathWithinAllowedDirectories(
183203
normalizePath(currentPath),

0 commit comments

Comments
 (0)