Skip to content

Commit 37a1f2f

Browse files
cliffhallclaude
andcommitted
fix(filesystem): refuse to move a directory into itself with the real reason
move_file of a directory to a destination inside that directory reported "Parent directory does not exist" (ENOENT) for a destination directory that did exist: the same-device move renames its source to a staging name first, which carries the destination's directory away with it. renameIntoDirectory now refuses that move before anything is renamed, with EINVAL and "Cannot move a directory into itself: <destination> is inside <source>". The check compares directories by identity from the destination's directory up to the root, so another spelling of the source (a different case on a case-insensitive volume) is still caught, and a symlink to a directory, which is not a directory move, is not. Closes #5555 Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Signed-off-by: cliffhall <cliff@futurescale.com>
1 parent 7f383a8 commit 37a1f2f

4 files changed

Lines changed: 275 additions & 0 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+
`move_file` now refuses to move a directory into itself with `Cannot move a directory into itself: <destination> is inside <source>`, instead of reporting `Parent directory does not exist` for a destination directory that does exist.

‎src/filesystem/README.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -256,6 +256,9 @@ Files inside the allowed directories are also [resources](https://modelcontextpr
256256
- `source` (string)
257257
- `destination` (string)
258258
- Fails if destination exists
259+
- A directory cannot be moved into itself: a destination inside the source
260+
directory fails with `Cannot move a directory into itself: <destination>
261+
is inside <source>`, and nothing is moved
259262
- Across filesystems (the source and destination on different mounts or
260263
disks), a regular file is moved by copying it to a newly created
261264
destination, with its permissions and modification time, and then removing
Lines changed: 210 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,210 @@
1+
// Moving a directory into itself is refused for what it is (#5555). The
2+
// same-device move first renames its source to a staging name, which carries
3+
// the destination's directory away with it when that directory is inside the
4+
// source, so the move went on to report "Parent directory does not exist" for
5+
// a directory that did exist. The refusal now comes before anything is
6+
// renamed, with EINVAL and a message naming both paths. The protocol-level
7+
// tests drive move_file through a client; the unit tests below them call
8+
// renameIntoDirectory directly, for the spellings validatePath would have
9+
// resolved away and for the moves that must still go through.
10+
11+
import fs from "fs";
12+
import path from "path";
13+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
14+
import type { Client } from "@modelcontextprotocol/client";
15+
import { renameIntoDirectory } from "../pinned-directory.js";
16+
import {
17+
call,
18+
connect,
19+
makeTempDir,
20+
quietStderr,
21+
textOf,
22+
type Connected,
23+
} from "./helpers.js";
24+
25+
const symlinks = process.platform !== "win32";
26+
27+
let dir: string;
28+
let cwd: string;
29+
let conn: Connected;
30+
let client: Client;
31+
32+
beforeEach(async () => {
33+
quietStderr();
34+
cwd = process.cwd();
35+
dir = await makeTempDir("mcp-fs-move-into-self-");
36+
fs.mkdirSync(path.join(dir, "sub", "inner"), { recursive: true });
37+
fs.writeFileSync(path.join(dir, "sub", "x.txt"), "x");
38+
conn = await connect([dir]);
39+
client = conn.client;
40+
});
41+
42+
afterEach(async () => {
43+
vi.restoreAllMocks();
44+
process.chdir(cwd);
45+
await conn.close();
46+
fs.rmSync(dir, { recursive: true, force: true });
47+
});
48+
49+
/** Every name under `directory`, relative to it, sorted. */
50+
function tree(directory: string): string[] {
51+
return fs
52+
.readdirSync(directory, { recursive: true, encoding: "utf-8" })
53+
.map((name) => name.split(path.sep).join("/"))
54+
.sort();
55+
}
56+
57+
/** The source is where it was, and no staging name was left behind. */
58+
function expectUntouched(): void {
59+
expect(tree(dir)).toEqual(["sub", "sub/inner", "sub/x.txt"]);
60+
expect(fs.readFileSync(path.join(dir, "sub", "x.txt"), "utf-8")).toBe("x");
61+
expect(process.cwd()).toBe(cwd);
62+
}
63+
64+
function refusal(source: string, destination: string): string {
65+
return `Cannot move a directory into itself: ${destination} is inside ${source}`;
66+
}
67+
68+
/** What renameIntoDirectory throws for this move. */
69+
function errorOf(source: string, destination: string): NodeJS.ErrnoException {
70+
try {
71+
renameIntoDirectory(source, destination);
72+
} catch (error) {
73+
return error as NodeJS.ErrnoException;
74+
}
75+
throw new Error("expected renameIntoDirectory to throw");
76+
}
77+
78+
describe("move_file of a directory into itself (#5555)", () => {
79+
it("refuses a destination below the source, naming the real reason", async () => {
80+
const source = path.join(dir, "sub");
81+
const destination = path.join(dir, "sub", "inner", "sub");
82+
const result = await call(client, "move_file", { source, destination });
83+
expect(result.isError).toBe(true);
84+
expect(textOf(result)).toBe(refusal(source, destination));
85+
expect(textOf(result)).not.toContain("Parent directory does not exist");
86+
expectUntouched();
87+
});
88+
89+
it("refuses a destination directly inside the source", async () => {
90+
const source = path.join(dir, "sub");
91+
const destination = path.join(dir, "sub", "new");
92+
const result = await call(client, "move_file", { source, destination });
93+
expect(result.isError).toBe(true);
94+
expect(textOf(result)).toBe(refusal(source, destination));
95+
expectUntouched();
96+
});
97+
98+
it("refuses a source given with a trailing separator", async () => {
99+
const source = path.join(dir, "sub");
100+
const destination = path.join(dir, "sub", "inner", "sub");
101+
const result = await call(client, "move_file", {
102+
source: source + path.sep,
103+
destination,
104+
});
105+
expect(result.isError).toBe(true);
106+
expect(textOf(result)).toBe(refusal(source, destination));
107+
expectUntouched();
108+
});
109+
110+
it("still reports a destination directory that really is missing", async () => {
111+
const missing = path.join(dir, "nope");
112+
const result = await call(client, "move_file", {
113+
source: path.join(dir, "sub"),
114+
destination: path.join(missing, "sub"),
115+
});
116+
expect(result.isError).toBe(true);
117+
expect(textOf(result)).toBe(`Parent directory does not exist: ${missing}`);
118+
expectUntouched();
119+
});
120+
121+
it("still moves a directory beside itself, under a name that extends its own", async () => {
122+
const result = await call(client, "move_file", {
123+
source: path.join(dir, "sub"),
124+
destination: path.join(dir, "sub2"),
125+
});
126+
expect(result.isError).toBeFalsy();
127+
expect(tree(dir)).toEqual(["sub2", "sub2/inner", "sub2/x.txt"]);
128+
});
129+
130+
it("still moves a directory out of its own subtree, into its parent", async () => {
131+
const result = await call(client, "move_file", {
132+
source: path.join(dir, "sub", "inner"),
133+
destination: path.join(dir, "inner"),
134+
});
135+
expect(result.isError).toBeFalsy();
136+
expect(tree(dir)).toEqual(["inner", "sub", "sub/x.txt"]);
137+
});
138+
139+
it("still moves a file into a directory beside it", async () => {
140+
const result = await call(client, "move_file", {
141+
source: path.join(dir, "sub", "x.txt"),
142+
destination: path.join(dir, "sub", "inner", "x.txt"),
143+
});
144+
expect(result.isError).toBeFalsy();
145+
expect(tree(dir)).toEqual(["sub", "sub/inner", "sub/inner/x.txt"]);
146+
});
147+
});
148+
149+
describe("renameIntoDirectory, for a directory moved into itself (#5555)", () => {
150+
it("fails with EINVAL before anything is renamed", () => {
151+
const source = path.join(dir, "sub");
152+
const destination = path.join(dir, "sub", "inner", "sub");
153+
const rename = vi.spyOn(fs, "renameSync");
154+
const error = errorOf(source, destination);
155+
expect(error.code).toBe("EINVAL");
156+
expect(error.message).toBe(refusal(source, destination));
157+
expect(rename).not.toHaveBeenCalled();
158+
expectUntouched();
159+
});
160+
161+
it("refuses a destination directory that does not exist below the source", () => {
162+
const source = path.join(dir, "sub");
163+
const destination = path.join(dir, "sub", "nope", "sub");
164+
const error = errorOf(source, destination);
165+
expect(error.code).toBe("EINVAL");
166+
expect(error.message).toBe(refusal(source, destination));
167+
expectUntouched();
168+
});
169+
170+
// The directory is compared by identity, so a spelling of it that a string
171+
// comparison would take for another directory is still the source.
172+
it("refuses another case of the source on a case-insensitive volume", (context) => {
173+
if (!fs.existsSync(path.join(dir, "SUB"))) {
174+
context.skip();
175+
}
176+
const source = path.join(dir, "sub");
177+
const destination = path.join(dir, "SUB", "inner", "sub");
178+
const error = errorOf(source, destination);
179+
expect(error.code).toBe("EINVAL");
180+
expect(error.message).toBe(refusal(source, destination));
181+
expectUntouched();
182+
});
183+
184+
// A symlink to a directory is not that directory: moving the link moves
185+
// only the link, so its target's subtree is a fine place for it.
186+
it.skipIf(!symlinks)(
187+
"moves a symlink to a directory into that directory",
188+
() => {
189+
fs.symlinkSync(path.join(dir, "sub"), path.join(dir, "link"));
190+
renameIntoDirectory(
191+
path.join(dir, "link"),
192+
path.join(dir, "sub", "inner", "link"),
193+
);
194+
expect(
195+
fs.lstatSync(path.join(dir, "sub", "inner", "link")).isSymbolicLink(),
196+
).toBe(true);
197+
expect(fs.existsSync(path.join(dir, "link"))).toBe(false);
198+
expect(fs.existsSync(path.join(dir, "sub", "x.txt"))).toBe(true);
199+
},
200+
);
201+
202+
it("leaves a missing source to the rename, which names it", () => {
203+
const source = path.join(dir, "gone");
204+
const error = errorOf(source, path.join(dir, "sub", "gone"));
205+
expect(error.code).toBe("ENOENT");
206+
expect(error.message).toContain(source);
207+
expect(error.message).not.toContain("into itself");
208+
expectUntouched();
209+
});
210+
});

‎src/filesystem/pinned-directory.ts‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -417,6 +417,50 @@ function returnStaged(staged: string, name: string): boolean {
417417
}
418418
}
419419

420+
/**
421+
* Whether `destinationDirectory` is the directory at `sourcePath` or lies
422+
* inside it (#5555), so the move would put a directory into itself. Decided
423+
* by identity, not by comparing path strings: each directory from
424+
* `destinationDirectory` up to the root is stat'd and compared with the
425+
* source, so another spelling of the same directory (a different case on a
426+
* case-insensitive volume, another normalization) cannot slip past. The
427+
* paths are as validatePath resolved them, so going up one name at a time
428+
* does not have to see through a symlink. A source that is not a directory
429+
* itself, a symlink to one included, has no subtree to be moved into.
430+
*
431+
* This is a refusal, not an anchor: it reads by path, and when it is wrong
432+
* (a directory swapped in between) the anchored steps of the move still hold.
433+
*/
434+
function isInsideSource(
435+
sourcePath: string,
436+
destinationDirectory: string,
437+
): boolean {
438+
let source: fs.BigIntStats;
439+
try {
440+
source = fs.lstatSync(sourcePath, { bigint: true });
441+
} catch {
442+
// A missing source is the rename's error to report.
443+
return false;
444+
}
445+
if (!source.isDirectory()) {
446+
return false;
447+
}
448+
for (let directory = destinationDirectory; ; ) {
449+
try {
450+
if (isSameEntry(fs.statSync(directory, { bigint: true }), source)) {
451+
return true;
452+
}
453+
} catch {
454+
// Missing or unreadable, so not the source; one above it still can be.
455+
}
456+
const parent = path.dirname(directory);
457+
if (parent === directory) {
458+
return false;
459+
}
460+
directory = parent;
461+
}
462+
}
463+
420464
/**
421465
* Rename `sourcePath` to `destinationPath`, keeping both inside their
422466
* validated directories. rename() takes two paths and Node has no
@@ -436,6 +480,11 @@ function returnStaged(staged: string, name: string): boolean {
436480
* cannot go back (something took its name in the meantime, or its directory
437481
* no longer resolves to the one validated, which is never entered), the error
438482
* says where it was left.
483+
*
484+
* A directory cannot be moved into itself, and that is refused (EINVAL)
485+
* before step 1 (#5555): step 1 moves the source away, and with it the
486+
* destination's directory, so step 2 would report that directory, which
487+
* exists, as missing.
439488
*/
440489
export function renameIntoDirectory(
441490
sourcePath: string,
@@ -444,6 +493,14 @@ export function renameIntoDirectory(
444493
const sourceDirectory = path.dirname(sourcePath);
445494
const name = path.basename(sourcePath);
446495
const destinationDirectory = path.dirname(destinationPath);
496+
if (isInsideSource(sourcePath, destinationDirectory)) {
497+
throw Object.assign(
498+
new Error(
499+
`Cannot move a directory into itself: ${destinationPath} is inside ${sourcePath}`,
500+
),
501+
{ code: "EINVAL" },
502+
);
503+
}
447504
const held = stagingName();
448505
const expected = inDirectory(sourceDirectory, () => {
449506
try {

0 commit comments

Comments
 (0)