Skip to content

Commit 704bd35

Browse files
cliffhallclaude
andcommitted
Merge branch 'v2/fix/GHSA-4gxg-m5jx-9j57' into v2/fix/GHSA-53mr-w429-c597
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Signed-off-by: cliffhall <cliff@futurescale.com>
2 parents 9380684 + 86b398a commit 704bd35

4 files changed

Lines changed: 167 additions & 24 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: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,11 @@ const mockReaddir = vi.mocked(
4949
) => Promise<Dirent[]>,
5050
);
5151

52+
// The path resolver calls the plain overload, which lists names as strings.
53+
const mockReaddirNames = vi.mocked(
54+
fs.readdir as (path: PathLike) => Promise<string[]>,
55+
);
56+
5257
interface MockFileHandle {
5358
read: Mock;
5459
close: Mock;
@@ -276,6 +281,11 @@ describe("Lib Functions", () => {
276281
mockFs.realpath.mockImplementation(async (path: PathLike) =>
277282
path.toString(),
278283
);
284+
// A name the path resolver lstats is missing unless a test says
285+
// otherwise, so an unmatched component starts the missing tail.
286+
const enoent = new Error("ENOENT") as NodeJS.ErrnoException;
287+
enoent.code = "ENOENT";
288+
mockFs.lstat.mockRejectedValue(enoent);
279289
});
280290

281291
it("validates allowed paths", async () => {
@@ -339,6 +349,44 @@ describe("Lib Functions", () => {
339349
expect(result).toBe(path.resolve(newFilePath));
340350
});
341351

352+
it("checks a component no entry matches by spelling when the OS still finds it", async () => {
353+
// On a case-insensitive file system "LINK" opens the symlink listed as
354+
// "link"; it must be resolved and checked, not treated as missing.
355+
const base =
356+
process.platform === "win32" ? "C:\\Users\\test" : "/home/user";
357+
const outsideDir =
358+
process.platform === "win32" ? "C:\\outside" : "/outside";
359+
const enoentError = new Error("ENOENT") as NodeJS.ErrnoException;
360+
enoentError.code = "ENOENT";
361+
mockFs.realpath
362+
.mockRejectedValueOnce(enoentError)
363+
.mockResolvedValueOnce(base)
364+
.mockResolvedValueOnce(outsideDir);
365+
mockReaddirNames.mockResolvedValueOnce(["link"]);
366+
mockFs.lstat.mockResolvedValueOnce({} as Stats);
367+
368+
await expect(
369+
validatePath(path.join(base, "LINK", "a"), allowedDirs),
370+
).rejects.toThrow(
371+
`Access denied - symlink target outside allowed directories: ${outsideDir}`,
372+
);
373+
expect(mockFs.lstat).toHaveBeenCalledWith(path.join(base, "LINK"));
374+
});
375+
376+
it("reports an lstat failure other than ENOENT on an unmatched component as is", async () => {
377+
const base =
378+
process.platform === "win32" ? "C:\\Users\\test" : "/home/user";
379+
const enoentError = new Error("ENOENT") as NodeJS.ErrnoException;
380+
enoentError.code = "ENOENT";
381+
mockFs.realpath.mockRejectedValueOnce(enoentError);
382+
mockReaddirNames.mockResolvedValueOnce([]);
383+
mockFs.lstat.mockRejectedValueOnce(new Error("EACCES lstat"));
384+
385+
await expect(
386+
validatePath(path.join(base, "new", "f.txt"), allowedDirs),
387+
).rejects.toThrow("EACCES lstat");
388+
});
389+
342390
it("rejects when no ancestor directory exists at all", async () => {
343391
const newFilePath =
344392
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: 28 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,17 @@ function respellAllowedDirectoryPrefix(
139139
return absolutePath;
140140
}
141141

142+
// Whether a directory entry of this name exists, without following it.
143+
async function entryExists(entryPath: string): Promise<boolean> {
144+
try {
145+
await fs.lstat(entryPath);
146+
return true;
147+
} catch (error) {
148+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return false;
149+
throw error;
150+
}
151+
}
152+
142153
async function resolveUnicodeEquivalentPath(
143154
absolutePath: string,
144155
allowedDirectories: readonly string[],
@@ -174,32 +185,25 @@ async function resolveUnicodeEquivalentPath(
174185
throw new Error(`Ambiguous Unicode path component: ${requestedPart}`);
175186
}
176187

177-
let nextPath: string;
178-
if (equivalentMatches.length === 0) {
179-
// No entry spells the component, but a case-insensitive volume (APFS,
180-
// NTFS) can still find it under another case, or Windows under its name
181-
// without trailing dots and spaces. Ask realpath, so an existing
182-
// directory always comes back in its on-disk spelling, which the write
183-
// operations compare against where they really are.
184-
try {
185-
nextPath = await fs.realpath(path.join(currentPath, requestedPart));
186-
} catch (error) {
187-
if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
188-
throw error;
189-
}
190-
// Nothing below this point exists yet, so there are no symlinks left
191-
// to resolve. currentPath is already realpath'd and inside an allowed
192-
// directory; append the missing tail so create_directory can mkdir -p
193-
// it.
194-
return path.join(currentPath, ...relativeParts.slice(index));
195-
}
196-
} else {
197-
nextPath = await fs.realpath(
198-
path.join(currentPath, equivalentMatches[0]),
199-
);
188+
// When no entry matches by spelling, the requested name still goes to the
189+
// OS as it is: on a case-insensitive file system (macOS and Windows by
190+
// default) it can name an existing entry spelled with other letter case,
191+
// and that entry can be a symlink that leaves the allowed directories. So
192+
// it is resolved and checked like a match, and only a name that does not
193+
// exist at all (lstat, so a dangling symlink still counts as existing)
194+
// starts the missing tail.
195+
const candidate = path.join(
196+
currentPath,
197+
equivalentMatches[0] ?? requestedPart,
198+
);
199+
if (equivalentMatches.length === 0 && !(await entryExists(candidate))) {
200+
// Nothing below this point exists yet, so there are no symlinks left to
201+
// resolve. currentPath is already realpath'd and inside an allowed
202+
// directory; append the missing tail so create_directory can mkdir -p it.
203+
return path.join(currentPath, ...relativeParts.slice(index));
200204
}
201205

202-
currentPath = nextPath;
206+
currentPath = await fs.realpath(candidate);
203207
if (
204208
!isPathWithinAllowedDirectories(
205209
normalizePath(currentPath),

0 commit comments

Comments
 (0)