Skip to content

Commit bd89c54

Browse files
committed
Merge origin/v2/main into v2/feat/5553-filesystem-search-files-examples
Catch up with #5622, which changed src/filesystem/ under this PR. Signed-off-by: cliffhall <cliff@futurescale.com>
2 parents 63461de + 257d888 commit bd89c54

5 files changed

Lines changed: 279 additions & 41 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+
On Windows, `list_directory`, `list_directory_with_sizes`, `directory_tree` and `search_files` now check the directory they list before and after reading it: its path must have no junction or symlink on it and must name the same directory both times, or the call is refused with "Access denied - a directory on the path changed during the operation". A directory swapped for a junction after the path was validated is no longer listed. A swap made and undone while the directory is being read is still not detected; the README's "Limit on Windows" entry says what holds. macOS and Linux are unchanged.

‎src/filesystem/README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,7 @@ The server's directory access control follows this flow:
128128
- A path is checked and then used, so on macOS and Linux each write, each read of a file's content or metadata, and each directory listing (`list_directory`, `list_directory_with_sizes`, `directory_tree`, `search_files`) acts from inside the directory that was checked. If a directory on the path is replaced in between, the call is refused with "Access denied - a directory on the path changed during the operation" rather than following the replacement. A listing therefore needs to enter the directory it lists: a directory the server can read but not enter (read permission without execute) is refused with `EACCES`, as an unreadable one is
129129
- On Windows, a path naming an NTFS alternate data stream (`file.txt:stream`, `file.txt::$DATA`) is refused with "Access denied - NTFS alternate data stream paths are not supported", even inside an allowed directory: a colon is accepted only as a drive letter's (`C:\`, `\\?\C:\`). A stream holds data that no directory listing or diff of the file shows. On macOS and Linux a colon is an ordinary file-name character and is not refused
130130
- On Windows, a path any of whose components is a reserved device name (`CON`, `PRN`, `AUX`, `NUL`, `COM1`-`COM9`, `LPT1`-`LPT9`, in any case and with or without an extension, such as `NUL.txt`) is refused with "Access denied - Windows reserved device names ... are not supported", and one any of whose components ends in a dot or a space (`file.txt.`, `dir \file.txt`) with "Access denied - Windows path components ending in a dot or a space are not supported". Windows opens the device rather than a file in the directory, and strips trailing dots and spaces so the name refers to a different file. `.` and `..` are not affected. On macOS and Linux these are ordinary file names and are not refused
131-
- **Limit on Windows: a parent directory swapped during an operation.** A path is checked and then used, and a directory on it could be replaced in between. On Linux and macOS the server anchors every write, and every read of a file's content or metadata, to the directory it validated, so a directory replaced with a symlink after the check cannot redirect the operation. **On Windows it cannot do that, and the operation is not protected**: a second local process that can already write inside an allowed directory can replace a parent directory with a junction (or a directory symlink) between the server's check and its open, and so redirect a read or a write outside the allowed directories. The server still checks the final component there (a write refuses a symlink or junction at the file's own name, and the file opened must be the one the directory holds at that name afterwards), which narrows the window without closing it
131+
- **Limit on Windows: a parent directory swapped during an operation.** A path is checked and then used, and a directory on it could be replaced in between. On Linux and macOS the server anchors every write, every read of a file's content or metadata, and every directory listing, to the directory it validated, so a directory replaced with a symlink after the check cannot redirect the operation. **On Windows it cannot do that, and the operation is not protected**: a second local process that can already write inside an allowed directory can replace a parent directory with a junction (or a directory symlink) between the server's check and its open, and so redirect a read, a write or a directory listing outside the allowed directories. The server still checks the final component there (a write refuses a symlink or junction at the file's own name, and the file opened must be the one the directory holds at that name afterwards), which narrows the window without closing it. A directory listing (`list_directory`, `list_directory_with_sizes`, `directory_tree`, `search_files`) is checked on both sides of the read instead: before and after it, the listed path must have no junction or symlink on it and must name the same directory, or the call is refused with "Access denied - a directory on the path changed during the operation". That refuses a replacement still in place when the read starts or when it ends. One made and undone in between is not detected, and returns the entry names of the directory it pointed to, so this too narrows the window without closing it
132132
- **What it takes**: a concurrent local process with write access inside an allowed directory, winning a race against the server. No tool of this server creates a junction or a symlink, so it cannot be set up through the server alone
133133
- **Guidance**: on Windows, do not allow a directory that untrusted local processes or users can write to
134134
- **Why it is not fixed**: closing the window needs opens relative to a directory handle, which Node does not expose, so it would take native code, and that is out of scope for a reference server ([#5260](https://github.com/modelcontextprotocol/servers/issues/5260)). It may be revisited when Node ships a stable built-in FFI under this package's `engines` floor
Lines changed: 180 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,180 @@
1+
// The Windows listing check (#5600): readDirectoryInPlace cannot anchor a
2+
// listing on Windows (the working directory is a path string there), so it
3+
// checks the listed directory before and after the read: the path must
4+
// resolve to itself, with no junction or symlink on it, and must name the
5+
// same directory both times (pinned-directory.ts).
6+
//
7+
// These tests run that branch on every host. On Windows (the CI Windows leg)
8+
// it runs for real, against real junctions. Elsewhere process.platform is
9+
// set to "win32", which is all the branch reads; the filesystem stays the
10+
// host's, so the swaps are real there too, and the coverage gate (which runs
11+
// on Linux) sees the branch.
12+
//
13+
// A swap staged from inside the read can be refused by the host: Windows will
14+
// not rename a directory a process is in, and the server is in the listed
15+
// directory. So those tests assert what must hold either way: the entries
16+
// returned are never the outside directory's, and a swap that did happen is
17+
// refused. The protocol-level tests of a swap staged before the listing are
18+
// in list-anchored.test.ts, and run on Windows too.
19+
20+
import fsSync from "fs";
21+
import path from "path";
22+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
23+
import { readDirectoryInPlace } from "../pinned-directory.js";
24+
import { makeTempDir } from "./helpers.js";
25+
26+
const OUTSIDE_NAME = "OUTSIDE-NAME-CANARY.txt";
27+
const INSIDE_NAME = "inside-marker.txt";
28+
const DIRECTORY_CHANGED =
29+
/Access denied - a directory on the path changed during the operation/;
30+
31+
const realPlatform = process.platform;
32+
33+
let dir: string;
34+
let outside: string;
35+
let middle: string;
36+
let listed: string;
37+
38+
beforeEach(async () => {
39+
dir = await makeTempDir("mcp-fs-list-win-");
40+
outside = await makeTempDir("mcp-fs-list-win-outside-");
41+
middle = path.join(dir, "middle");
42+
listed = path.join(middle, "listed");
43+
fsSync.mkdirSync(listed, { recursive: true });
44+
fsSync.writeFileSync(path.join(listed, INSIDE_NAME), "inside");
45+
// The outside tree mirrors the inside one, so a swapped parent still leads
46+
// to a real directory named "listed".
47+
fsSync.mkdirSync(path.join(outside, "listed"));
48+
fsSync.writeFileSync(path.join(outside, OUTSIDE_NAME), "outside");
49+
fsSync.writeFileSync(path.join(outside, "listed", OUTSIDE_NAME), "outside");
50+
Object.defineProperty(process, "platform", { value: "win32" });
51+
});
52+
53+
afterEach(() => {
54+
vi.restoreAllMocks();
55+
Object.defineProperty(process, "platform", { value: realPlatform });
56+
fsSync.rmSync(dir, { recursive: true, force: true });
57+
fsSync.rmSync(outside, { recursive: true, force: true });
58+
});
59+
60+
/** A junction on Windows, which needs no privilege; a symlink elsewhere. */
61+
function link(target: string, at: string): void {
62+
fsSync.symlinkSync(target, at, "junction");
63+
}
64+
65+
/** Run `swap` on the first readdirSync, before the real read; say if it ran. */
66+
function swapDuringRead(swap: () => void): { swapped: () => boolean } {
67+
const realReaddirSync = fsSync.readdirSync.bind(fsSync) as (
68+
target: fsSync.PathLike,
69+
options: { withFileTypes: true },
70+
) => fsSync.Dirent[];
71+
let attempted = false;
72+
let swapped = false;
73+
vi.spyOn(fsSync, "readdirSync").mockImplementation(((
74+
target: fsSync.PathLike,
75+
options: { withFileTypes: true },
76+
) => {
77+
if (!attempted) {
78+
attempted = true;
79+
try {
80+
swap();
81+
swapped = true;
82+
} catch {
83+
// The host refused the swap (see the header); nothing changed.
84+
}
85+
}
86+
return realReaddirSync(target, options);
87+
}) as typeof fsSync.readdirSync);
88+
return { swapped: () => swapped };
89+
}
90+
91+
/** List `listed`; the names it returned, or the refusal it threw. */
92+
function listNames(): { names?: string[]; refusal?: string } {
93+
try {
94+
return { names: readDirectoryInPlace(listed).map((entry) => entry.name) };
95+
} catch (error) {
96+
return { refusal: (error as Error).message };
97+
}
98+
}
99+
100+
describe("the Windows listing check", () => {
101+
it("lists a directory nothing was swapped on, naming it as the parent", () => {
102+
const entries = readDirectoryInPlace(listed);
103+
expect(entries.map((entry) => entry.name)).toEqual([INSIDE_NAME]);
104+
expect(entries[0].parentPath).toBe(listed);
105+
expect(entries[0].isFile()).toBe(true);
106+
});
107+
108+
it("refuses a directory that is now a link to one outside", () => {
109+
fsSync.renameSync(listed, path.join(middle, "listed-real"));
110+
link(outside, listed);
111+
const { names, refusal } = listNames();
112+
expect(names).toBeUndefined();
113+
expect(refusal).toMatch(DIRECTORY_CHANGED);
114+
});
115+
116+
it("refuses a directory whose parent is now a link to one outside", () => {
117+
// The last component is a real directory, the outside tree's "listed", so
118+
// only the path's real location shows the swap.
119+
fsSync.renameSync(middle, path.join(dir, "middle-real"));
120+
link(outside, middle);
121+
const { names, refusal } = listNames();
122+
expect(names).toBeUndefined();
123+
expect(refusal).toMatch(DIRECTORY_CHANGED);
124+
});
125+
126+
it("never returns the outside entries when the directory is swapped for a link during the read", () => {
127+
const { swapped } = swapDuringRead(() => {
128+
fsSync.renameSync(listed, path.join(middle, "listed-real"));
129+
link(outside, listed);
130+
});
131+
const { names, refusal } = listNames();
132+
expect(names ?? []).not.toContain(OUTSIDE_NAME);
133+
if (swapped()) {
134+
expect(refusal).toMatch(DIRECTORY_CHANGED);
135+
} else {
136+
expect(names).toEqual([INSIDE_NAME]);
137+
}
138+
});
139+
140+
it("never returns the outside entries when a parent is swapped for a link during the read", () => {
141+
const { swapped } = swapDuringRead(() => {
142+
fsSync.renameSync(middle, path.join(dir, "middle-real"));
143+
link(outside, middle);
144+
});
145+
const { names, refusal } = listNames();
146+
expect(names ?? []).not.toContain(OUTSIDE_NAME);
147+
if (swapped()) {
148+
expect(refusal).toMatch(DIRECTORY_CHANGED);
149+
} else {
150+
expect(names).toEqual([INSIDE_NAME]);
151+
}
152+
});
153+
154+
it("refuses when another directory takes the name during the read", () => {
155+
// No link anywhere, so only the identity shows it is not the directory
156+
// the first check saw.
157+
const { swapped } = swapDuringRead(() => {
158+
fsSync.renameSync(listed, path.join(middle, "listed-real"));
159+
fsSync.mkdirSync(listed);
160+
});
161+
const { names, refusal } = listNames();
162+
if (swapped()) {
163+
expect(refusal).toMatch(DIRECTORY_CHANGED);
164+
} else {
165+
expect(names).toEqual([INSIDE_NAME]);
166+
}
167+
});
168+
169+
it.skipIf(realPlatform === "win32")(
170+
"is not applied off Windows, where the listing is anchored",
171+
() => {
172+
Object.defineProperty(process, "platform", { value: realPlatform });
173+
const lstat = vi.spyOn(fsSync, "lstatSync");
174+
expect(readDirectoryInPlace(listed).map((entry) => entry.name)).toEqual([
175+
INSIDE_NAME,
176+
]);
177+
expect(lstat).not.toHaveBeenCalled();
178+
},
179+
);
180+
});

‎src/filesystem/__tests__/list-anchored.test.ts‎

Lines changed: 42 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,10 @@
66
// is swapped for a symlink to a directory outside the allowed one. Each
77
// listing must then refuse rather than return the outside directory's entry
88
// names. Before listings were anchored, each of these returned them.
9+
//
10+
// They run on Windows too (#5600), where the swap is a junction, which needs
11+
// no privilege, and the refusal comes from the check made around the read
12+
// rather than from an anchor (list-anchored-windows.test.ts).
913

1014
import fs from "fs/promises";
1115
import fsSync from "fs";
@@ -52,16 +56,19 @@ afterEach(async () => {
5256
await fs.rm(outside, { recursive: true, force: true });
5357
});
5458

55-
/** Swap `flip` for a symlink to `outside`, once, right after it is realpath'd. */
59+
/**
60+
* Swap `flip` for a link to `outside`, once, right after it is realpath'd.
61+
* "junction" picks the link type on Windows and is ignored elsewhere.
62+
*/
5663
function swapAfterRealpath(): void {
5764
const realRealpath = fs.realpath.bind(fs);
5865
let swapped = false;
5966
vi.spyOn(fs, "realpath").mockImplementation(async (p, opts) => {
6067
const resolved = await realRealpath(p, opts);
61-
if (!swapped && p === flip) {
68+
if (!swapped && String(p).toLowerCase() === flip.toLowerCase()) {
6269
swapped = true;
6370
fsSync.renameSync(flip, flipReal);
64-
fsSync.symlinkSync(outside, flip);
71+
fsSync.symlinkSync(outside, flip, "junction");
6572
}
6673
return resolved;
6774
});
@@ -70,44 +77,41 @@ function swapAfterRealpath(): void {
7077
const DIRECTORY_CHANGED =
7178
/Access denied - a directory on the path changed during the operation/;
7279

73-
describe.skipIf(process.platform === "win32")(
74-
"a listed directory swapped for a symlink after validation",
75-
() => {
76-
it.each([
77-
["list_directory", {}],
78-
["list_directory_with_sizes", {}],
79-
["directory_tree", {}],
80-
["search_files", { pattern: "**" }],
81-
])("%s does not list through it", async (tool, extra) => {
82-
swapAfterRealpath();
83-
const result = await call(client, tool, { path: flip, ...extra });
84-
expect(result.isError).toBe(true);
85-
expect(textOf(result)).toMatch(DIRECTORY_CHANGED);
86-
expect(JSON.stringify(result)).not.toContain(OUTSIDE_NAME);
87-
});
80+
describe("a listed directory swapped for a link after validation", () => {
81+
it.each([
82+
["list_directory", {}],
83+
["list_directory_with_sizes", {}],
84+
["directory_tree", {}],
85+
["search_files", { pattern: "**" }],
86+
])("%s does not list through it", async (tool, extra) => {
87+
swapAfterRealpath();
88+
const result = await call(client, tool, { path: flip, ...extra });
89+
expect(result.isError).toBe(true);
90+
expect(textOf(result)).toMatch(DIRECTORY_CHANGED);
91+
expect(JSON.stringify(result)).not.toContain(OUTSIDE_NAME);
92+
});
8893

89-
it("directory_tree does not list a subdirectory through it", async () => {
90-
swapAfterRealpath();
91-
const result = await call(client, "directory_tree", { path: dir });
92-
expect(result.isError).toBe(true);
93-
expect(textOf(result)).toMatch(DIRECTORY_CHANGED);
94-
expect(JSON.stringify(result)).not.toContain(OUTSIDE_NAME);
95-
});
94+
it("directory_tree does not list a subdirectory through it", async () => {
95+
swapAfterRealpath();
96+
const result = await call(client, "directory_tree", { path: dir });
97+
expect(result.isError).toBe(true);
98+
expect(textOf(result)).toMatch(DIRECTORY_CHANGED);
99+
expect(JSON.stringify(result)).not.toContain(OUTSIDE_NAME);
100+
});
96101

97-
it("search_files does not search a subdirectory through it, and says so", async () => {
98-
swapAfterRealpath();
99-
const result = await call(client, "search_files", {
100-
path: dir,
101-
pattern: "**",
102-
});
103-
expect(result.isError).toBeFalsy();
104-
expect(JSON.stringify(result)).not.toContain(OUTSIDE_NAME);
105-
// The swapped directory is reported as unreadable, not as empty.
106-
expect(textOf(result)).toContain(`${flip}`);
107-
expect(textOf(result)).toMatch(/could not be read/i);
102+
it("search_files does not search a subdirectory through it, and says so", async () => {
103+
swapAfterRealpath();
104+
const result = await call(client, "search_files", {
105+
path: dir,
106+
pattern: "**",
108107
});
109-
},
110-
);
108+
expect(result.isError).toBeFalsy();
109+
expect(JSON.stringify(result)).not.toContain(OUTSIDE_NAME);
110+
// The swapped directory is reported as unreadable, not as empty.
111+
expect(textOf(result)).toContain(`${flip}`);
112+
expect(textOf(result)).toMatch(/could not be read/i);
113+
});
114+
});
111115

112116
describe("listings that are not swapped", () => {
113117
it("list every tool's way, from the directory validation resolved", async () => {

0 commit comments

Comments
 (0)