Skip to content

Commit b57b04c

Browse files
cliffhallclaude
andcommitted
fix(filesystem): respell an allowed directory's letter case per segment
A request that spells an allowed directory's own name in a case matching neither the configured nor the on-disk spelling was refused by the allow-list prefix check, a string comparison that runs before realpath. Respell such a request onto the allowed directory only where the file system confirms, component by component, that both spellings name one entry: the parent holds exactly one case-insensitive match and both spellings lstat to the same device and inode. A case-sensitive directory answers no, so a sibling differing only in case is still refused. Closes #470 Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: cliffhall <[email protected]>
1 parent 66e3dec commit b57b04c

4 files changed

Lines changed: 293 additions & 1 deletion

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+
A path that spells an allowed directory's own name in a letter case matching neither the configured nor the on-disk spelling (for example `C:\Work\CASETEST\file.txt` for an allowed `C:\Work\CaseTest`) is no longer refused on a case-insensitive file system (Windows NTFS, default macOS APFS). The request is mapped onto the allowed directory only where the file system confirms, component by component, that both spellings name one entry, so a sibling directory differing only in case is still refused on a case-sensitive directory.

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

Lines changed: 97 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import {
88
type Mock,
99
} from "vitest";
1010
import fs, { type FileHandle } from "fs/promises";
11-
import type { Dirent, PathLike, Stats } from "fs";
11+
import type { BigIntStats, Dirent, PathLike, Stats } from "fs";
1212
import path from "path";
1313
import {
1414
// Pure utility functions
@@ -54,6 +54,15 @@ const mockReaddirNames = vi.mocked(
5454
fs.readdir as (path: PathLike) => Promise<string[]>,
5555
);
5656

57+
// The case respelling (#470) lstats with { bigint: true }, to compare inodes
58+
// Windows reports as 64-bit file IDs without losing precision.
59+
const mockLstatBigInt = vi.mocked(
60+
fs.lstat as (
61+
path: PathLike,
62+
options: { bigint: true },
63+
) => Promise<BigIntStats>,
64+
);
65+
5766
interface MockFileHandle {
5867
read: Mock;
5968
close: Mock;
@@ -429,6 +438,93 @@ describe("Lib Functions", () => {
429438
process.cwd = originalCwd;
430439
}
431440
});
441+
442+
// #470: the allowed directory's own name spelled in a letter case that
443+
// matches neither the configured nor the on-disk spelling. It is
444+
// respelled only where the file system confirms, component by
445+
// component, that both spellings name one entry.
446+
describe("letter case of an allowed directory's own name (#470)", () => {
447+
const win = process.platform === "win32";
448+
const configured = win ? "C:\\Users\\test" : "/home/user";
449+
const requestedFile = win
450+
? "C:\\USERS\\Test\\file.txt"
451+
: "/HOME/User/file.txt";
452+
const respelled = path.join(configured, "file.txt");
453+
// Each directory the walk lists, as the configured spelling names it.
454+
const listings: Record<string, string[]> = win
455+
? { "C:\\": ["Users"], "C:\\Users": ["test"] }
456+
: { "/": ["home"], "/home": ["user"] };
457+
458+
// lstat on a case-insensitive file system: any spelling of a listed
459+
// entry is that entry, one inode per lowercased path.
460+
function foldingLstat() {
461+
mockLstatBigInt.mockImplementation(
462+
async (p: PathLike) =>
463+
({
464+
dev: 1n,
465+
ino: BigInt(p.toString().toLowerCase().length),
466+
}) as BigIntStats,
467+
);
468+
}
469+
470+
beforeEach(() => {
471+
mockReaddirNames.mockImplementation(
472+
async (p: PathLike) => listings[p.toString()] ?? [],
473+
);
474+
});
475+
476+
it("respells the request onto the allowed directory when the file system folds case", async () => {
477+
foldingLstat();
478+
await expect(validatePath(requestedFile, allowedDirs)).resolves.toBe(
479+
respelled,
480+
);
481+
});
482+
483+
it("refuses when a directory holds two entries differing only in case", async () => {
484+
foldingLstat();
485+
const [first, second] = win ? ["Users", "test"] : ["home", "user"];
486+
const parent = win ? "C:\\" : "/";
487+
mockReaddirNames.mockImplementation(async (p: PathLike) =>
488+
p.toString() === parent ? [first, first.toUpperCase()] : [second],
489+
);
490+
await expect(
491+
validatePath(requestedFile, allowedDirs),
492+
).rejects.toThrow("Access denied - path outside allowed directories");
493+
});
494+
495+
it("refuses when the requested spelling does not exist (a case-sensitive directory)", async () => {
496+
// beforeEach makes every lstat ENOENT.
497+
await expect(
498+
validatePath(requestedFile, allowedDirs),
499+
).rejects.toThrow("Access denied - path outside allowed directories");
500+
});
501+
502+
it("refuses when the two spellings are different entries", async () => {
503+
let ino = 0n;
504+
mockLstatBigInt.mockImplementation(
505+
async () => ({ dev: 1n, ino: ++ino }) as BigIntStats,
506+
);
507+
await expect(
508+
validatePath(requestedFile, allowedDirs),
509+
).rejects.toThrow("Access denied - path outside allowed directories");
510+
});
511+
512+
it("refuses when a directory cannot be listed", async () => {
513+
foldingLstat();
514+
mockReaddirNames.mockRejectedValue(new Error("EACCES readdir"));
515+
await expect(
516+
validatePath(requestedFile, allowedDirs),
517+
).rejects.toThrow("Access denied - path outside allowed directories");
518+
});
519+
520+
it("still refuses a name that only folds onto part of an allowed directory", async () => {
521+
foldingLstat();
522+
const parentOnly = win ? "C:\\USERS\\x.txt" : "/HOME/x.txt";
523+
await expect(validatePath(parentOnly, allowedDirs)).rejects.toThrow(
524+
"Access denied - path outside allowed directories",
525+
);
526+
});
527+
});
432528
});
433529
});
434530

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

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -496,3 +496,85 @@ describe("Unicode space separators (#1970)", () => {
496496
expect(textOf(result)).toBe("Ambiguous Unicode path component: a b");
497497
});
498498
});
499+
500+
// #470: an allowed directory spelled in a letter case that matches neither
501+
// the configured nor the on-disk spelling failed the allow-list prefix check,
502+
// a string comparison, before the path was resolved. A case-folded compare
503+
// would admit a sibling on a case-sensitive directory, so the request is
504+
// respelled only where the file system says both spellings name one entry.
505+
describe("letter case of the allowed directory's own name (#470)", () => {
506+
let root: string;
507+
let scoped: Connected;
508+
509+
beforeEach(async () => {
510+
root = path.join(dir, "CaseTest");
511+
await fs.mkdir(path.join(root, "Sub"), { recursive: true });
512+
await fs.writeFile(path.join(root, "Sub", "File.txt"), "inside");
513+
scoped = await connect([root]);
514+
});
515+
516+
afterEach(async () => {
517+
await scoped.close();
518+
});
519+
520+
const requested = () => path.join(dir, "CASETEST", "SUB", "FILE.TXT");
521+
522+
it.skipIf(!caseInsensitive)(
523+
"reads through a respelled allowed directory on a case-insensitive file system",
524+
async () => {
525+
const result = await call(scoped.client, "read_text_file", {
526+
path: requested(),
527+
});
528+
expect(textOf(result)).toBe("inside");
529+
},
530+
);
531+
532+
it.skipIf(!caseInsensitive)(
533+
"creates a new file under a respelled allowed directory, inside it",
534+
async () => {
535+
const result = await call(scoped.client, "write_file", {
536+
path: path.join(dir, "casetest", "sub", "New.txt"),
537+
content: "new",
538+
});
539+
expect(result.isError).toBeFalsy();
540+
expect(await fs.readdir(path.join(root, "Sub"))).toContain("New.txt");
541+
},
542+
);
543+
544+
it.skipIf(caseInsensitive)(
545+
"refuses the respelling on a case-sensitive file system",
546+
async () => {
547+
const result = await call(scoped.client, "read_text_file", {
548+
path: requested(),
549+
});
550+
expect(textOf(result)).toMatch(/^Access denied - path outside/);
551+
},
552+
);
553+
554+
it.skipIf(caseInsensitive)(
555+
"never admits a sibling that differs from the allowed directory only in case",
556+
async () => {
557+
const sibling = path.join(dir, "casetest");
558+
await fs.mkdir(sibling);
559+
await fs.writeFile(path.join(sibling, "secret.txt"), "secret");
560+
const result = await call(scoped.client, "read_text_file", {
561+
path: path.join(sibling, "secret.txt"),
562+
});
563+
expect(textOf(result)).toMatch(/^Access denied - path outside/);
564+
},
565+
);
566+
567+
it("refuses a .. escape through a respelled allowed directory", async () => {
568+
const result = await call(scoped.client, "read_text_file", {
569+
path: path.join(
570+
dir,
571+
"CASETEST",
572+
"..",
573+
"..",
574+
path.basename(outside),
575+
"secret.txt",
576+
),
577+
});
578+
expect(textOf(result)).toMatch(/^Access denied - path outside/);
579+
});
580+
});

‎src/filesystem/lib.ts‎

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,104 @@ function respellAllowedDirectoryPrefix(
139139
return absolutePath;
140140
}
141141

142+
// The form two components are compared in when only their letter case may
143+
// differ (#470). Folding alone proves nothing: whether two spellings name one
144+
// entry is the file system's call, and namesOneEntry asks it.
145+
function caseMatchKey(component: string): string {
146+
return unicodeMatchKey(component).toLowerCase();
147+
}
148+
149+
// Whether `requested` names the same entry of `parent` as `configured`, an
150+
// allowed directory's own component. Asked of the file system rather than
151+
// folded, because NTFS and APFS directories can be case-sensitive, and there a
152+
// name differing only in case is another entry, or none (#470). Both
153+
// conditions must hold: `parent` holds exactly one entry matching the request
154+
// case-insensitively, and the two spellings lstat to the same device and
155+
// inode. Any error, a missing name included, answers no, so the request is
156+
// refused as before.
157+
async function namesOneEntry(
158+
parent: string,
159+
requested: string,
160+
configured: string,
161+
): Promise<boolean> {
162+
try {
163+
const key = caseMatchKey(requested);
164+
const entries = (await fs.readdir(parent)) ?? [];
165+
if (entries.filter((entry) => caseMatchKey(entry) === key).length !== 1) {
166+
return false;
167+
}
168+
const requestedStats = await fs.lstat(path.join(parent, requested), {
169+
bigint: true,
170+
});
171+
const configuredStats = await fs.lstat(path.join(parent, configured), {
172+
bigint: true,
173+
});
174+
return (
175+
requestedStats.dev === configuredStats.dev &&
176+
requestedStats.ino === configuredStats.ino
177+
);
178+
} catch {
179+
return false;
180+
}
181+
}
182+
183+
// An allowed directory whose own name the request spells in another letter
184+
// case, matching neither the configured nor the on-disk spelling, fails the
185+
// allow-list check, which compares strings (#470). Like the Unicode respelling
186+
// above, map such a request onto the allowed directory's own spelling, but
187+
// only where every component that differs in case is confirmed, segment by
188+
// segment, by namesOneEntry. The result is inside that directory by
189+
// construction, and every later check still runs against the real allow-list.
190+
async function respellAllowedDirectoryCase(
191+
absolutePath: string,
192+
allowedDirectories: readonly string[],
193+
): Promise<string> {
194+
const requestedRoot = path.parse(absolutePath).root;
195+
const requestedParts = absolutePath
196+
.slice(requestedRoot.length)
197+
.split(path.sep)
198+
.filter(Boolean);
199+
const candidates = allowedDirectories
200+
.map((directory) => path.resolve(directory))
201+
.sort((left, right) => right.length - left.length);
202+
for (const directory of candidates) {
203+
const root = path.parse(directory).root;
204+
const directoryParts = directory
205+
.slice(root.length)
206+
.split(path.sep)
207+
.filter(Boolean);
208+
// A root is "/" off Windows; on Windows its drive letter or UNC server
209+
// and share are case-insensitive by definition, so folding it is safe.
210+
if (
211+
caseMatchKey(root) !== caseMatchKey(requestedRoot) ||
212+
directoryParts.length > requestedParts.length ||
213+
!directoryParts.every(
214+
(part, index) =>
215+
caseMatchKey(part) === caseMatchKey(requestedParts[index]),
216+
)
217+
) {
218+
continue;
219+
}
220+
let parent = root;
221+
let confirmed = true;
222+
for (let index = 0; index < directoryParts.length && confirmed; index++) {
223+
const part = directoryParts[index];
224+
const requestedPart = requestedParts[index];
225+
confirmed =
226+
unicodeMatchKey(part) === unicodeMatchKey(requestedPart) ||
227+
(await namesOneEntry(parent, requestedPart, part));
228+
parent = path.join(parent, part);
229+
}
230+
if (confirmed) {
231+
return path.join(
232+
directory,
233+
...requestedParts.slice(directoryParts.length),
234+
);
235+
}
236+
}
237+
return absolutePath;
238+
}
239+
142240
// Whether a directory entry of this name exists, without following it.
143241
async function entryExists(entryPath: string): Promise<boolean> {
144242
try {
@@ -253,6 +351,17 @@ export async function validatePath(
253351
)
254352
) {
255353
absolute = respellAllowedDirectoryPrefix(absolute, allowedDirectories);
354+
if (
355+
!isPathWithinAllowedDirectories(
356+
normalizePathFormat(absolute),
357+
allowedDirectories,
358+
)
359+
) {
360+
absolute = await respellAllowedDirectoryCase(
361+
absolute,
362+
allowedDirectories,
363+
);
364+
}
256365
}
257366

258367
const normalizedRequested = normalizePathFormat(absolute);

0 commit comments

Comments
 (0)