From 37a1f2f8dd72a6912969ac990f556422caa801fa Mon Sep 17 00:00:00 2001 From: cliffhall Date: Wed, 18 Nov 2026 12:57:41 -0500 Subject: [PATCH] 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: is inside ". 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 Signed-off-by: cliffhall --- .../filesystem-move-into-own-subtree.md | 5 + src/filesystem/README.md | 3 + .../__tests__/move-into-own-subtree.test.ts | 210 ++++++++++++++++++ src/filesystem/pinned-directory.ts | 57 +++++ 4 files changed, 275 insertions(+) create mode 100644 .changeset/filesystem-move-into-own-subtree.md create mode 100644 src/filesystem/__tests__/move-into-own-subtree.test.ts diff --git a/.changeset/filesystem-move-into-own-subtree.md b/.changeset/filesystem-move-into-own-subtree.md new file mode 100644 index 0000000000..ed979868ec --- /dev/null +++ b/.changeset/filesystem-move-into-own-subtree.md @@ -0,0 +1,5 @@ +--- +"@modelcontextprotocol/server-filesystem": patch +--- + +`move_file` now refuses to move a directory into itself with `Cannot move a directory into itself: is inside `, instead of reporting `Parent directory does not exist` for a destination directory that does exist. diff --git a/src/filesystem/README.md b/src/filesystem/README.md index 0335ff5551..e5aa3419be 100644 --- a/src/filesystem/README.md +++ b/src/filesystem/README.md @@ -256,6 +256,9 @@ Files inside the allowed directories are also [resources](https://modelcontextpr - `source` (string) - `destination` (string) - Fails if destination exists + - A directory cannot be moved into itself: a destination inside the source + directory fails with `Cannot move a directory into itself: + is inside `, and nothing is moved - Across filesystems (the source and destination on different mounts or disks), a regular file is moved by copying it to a newly created destination, with its permissions and modification time, and then removing diff --git a/src/filesystem/__tests__/move-into-own-subtree.test.ts b/src/filesystem/__tests__/move-into-own-subtree.test.ts new file mode 100644 index 0000000000..1dd528d2ec --- /dev/null +++ b/src/filesystem/__tests__/move-into-own-subtree.test.ts @@ -0,0 +1,210 @@ +// Moving a directory into itself is refused for what it is (#5555). The +// same-device move first renames its source to a staging name, which carries +// the destination's directory away with it when that directory is inside the +// source, so the move went on to report "Parent directory does not exist" for +// a directory that did exist. The refusal now comes before anything is +// renamed, with EINVAL and a message naming both paths. The protocol-level +// tests drive move_file through a client; the unit tests below them call +// renameIntoDirectory directly, for the spellings validatePath would have +// resolved away and for the moves that must still go through. + +import fs from "fs"; +import path from "path"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import type { Client } from "@modelcontextprotocol/client"; +import { renameIntoDirectory } from "../pinned-directory.js"; +import { + call, + connect, + makeTempDir, + quietStderr, + textOf, + type Connected, +} from "./helpers.js"; + +const symlinks = process.platform !== "win32"; + +let dir: string; +let cwd: string; +let conn: Connected; +let client: Client; + +beforeEach(async () => { + quietStderr(); + cwd = process.cwd(); + dir = await makeTempDir("mcp-fs-move-into-self-"); + fs.mkdirSync(path.join(dir, "sub", "inner"), { recursive: true }); + fs.writeFileSync(path.join(dir, "sub", "x.txt"), "x"); + conn = await connect([dir]); + client = conn.client; +}); + +afterEach(async () => { + vi.restoreAllMocks(); + process.chdir(cwd); + await conn.close(); + fs.rmSync(dir, { recursive: true, force: true }); +}); + +/** Every name under `directory`, relative to it, sorted. */ +function tree(directory: string): string[] { + return fs + .readdirSync(directory, { recursive: true, encoding: "utf-8" }) + .map((name) => name.split(path.sep).join("/")) + .sort(); +} + +/** The source is where it was, and no staging name was left behind. */ +function expectUntouched(): void { + expect(tree(dir)).toEqual(["sub", "sub/inner", "sub/x.txt"]); + expect(fs.readFileSync(path.join(dir, "sub", "x.txt"), "utf-8")).toBe("x"); + expect(process.cwd()).toBe(cwd); +} + +function refusal(source: string, destination: string): string { + return `Cannot move a directory into itself: ${destination} is inside ${source}`; +} + +/** What renameIntoDirectory throws for this move. */ +function errorOf(source: string, destination: string): NodeJS.ErrnoException { + try { + renameIntoDirectory(source, destination); + } catch (error) { + return error as NodeJS.ErrnoException; + } + throw new Error("expected renameIntoDirectory to throw"); +} + +describe("move_file of a directory into itself (#5555)", () => { + it("refuses a destination below the source, naming the real reason", async () => { + const source = path.join(dir, "sub"); + const destination = path.join(dir, "sub", "inner", "sub"); + const result = await call(client, "move_file", { source, destination }); + expect(result.isError).toBe(true); + expect(textOf(result)).toBe(refusal(source, destination)); + expect(textOf(result)).not.toContain("Parent directory does not exist"); + expectUntouched(); + }); + + it("refuses a destination directly inside the source", async () => { + const source = path.join(dir, "sub"); + const destination = path.join(dir, "sub", "new"); + const result = await call(client, "move_file", { source, destination }); + expect(result.isError).toBe(true); + expect(textOf(result)).toBe(refusal(source, destination)); + expectUntouched(); + }); + + it("refuses a source given with a trailing separator", async () => { + const source = path.join(dir, "sub"); + const destination = path.join(dir, "sub", "inner", "sub"); + const result = await call(client, "move_file", { + source: source + path.sep, + destination, + }); + expect(result.isError).toBe(true); + expect(textOf(result)).toBe(refusal(source, destination)); + expectUntouched(); + }); + + it("still reports a destination directory that really is missing", async () => { + const missing = path.join(dir, "nope"); + const result = await call(client, "move_file", { + source: path.join(dir, "sub"), + destination: path.join(missing, "sub"), + }); + expect(result.isError).toBe(true); + expect(textOf(result)).toBe(`Parent directory does not exist: ${missing}`); + expectUntouched(); + }); + + it("still moves a directory beside itself, under a name that extends its own", async () => { + const result = await call(client, "move_file", { + source: path.join(dir, "sub"), + destination: path.join(dir, "sub2"), + }); + expect(result.isError).toBeFalsy(); + expect(tree(dir)).toEqual(["sub2", "sub2/inner", "sub2/x.txt"]); + }); + + it("still moves a directory out of its own subtree, into its parent", async () => { + const result = await call(client, "move_file", { + source: path.join(dir, "sub", "inner"), + destination: path.join(dir, "inner"), + }); + expect(result.isError).toBeFalsy(); + expect(tree(dir)).toEqual(["inner", "sub", "sub/x.txt"]); + }); + + it("still moves a file into a directory beside it", async () => { + const result = await call(client, "move_file", { + source: path.join(dir, "sub", "x.txt"), + destination: path.join(dir, "sub", "inner", "x.txt"), + }); + expect(result.isError).toBeFalsy(); + expect(tree(dir)).toEqual(["sub", "sub/inner", "sub/inner/x.txt"]); + }); +}); + +describe("renameIntoDirectory, for a directory moved into itself (#5555)", () => { + it("fails with EINVAL before anything is renamed", () => { + const source = path.join(dir, "sub"); + const destination = path.join(dir, "sub", "inner", "sub"); + const rename = vi.spyOn(fs, "renameSync"); + const error = errorOf(source, destination); + expect(error.code).toBe("EINVAL"); + expect(error.message).toBe(refusal(source, destination)); + expect(rename).not.toHaveBeenCalled(); + expectUntouched(); + }); + + it("refuses a destination directory that does not exist below the source", () => { + const source = path.join(dir, "sub"); + const destination = path.join(dir, "sub", "nope", "sub"); + const error = errorOf(source, destination); + expect(error.code).toBe("EINVAL"); + expect(error.message).toBe(refusal(source, destination)); + expectUntouched(); + }); + + // The directory is compared by identity, so a spelling of it that a string + // comparison would take for another directory is still the source. + it("refuses another case of the source on a case-insensitive volume", (context) => { + if (!fs.existsSync(path.join(dir, "SUB"))) { + context.skip(); + } + const source = path.join(dir, "sub"); + const destination = path.join(dir, "SUB", "inner", "sub"); + const error = errorOf(source, destination); + expect(error.code).toBe("EINVAL"); + expect(error.message).toBe(refusal(source, destination)); + expectUntouched(); + }); + + // A symlink to a directory is not that directory: moving the link moves + // only the link, so its target's subtree is a fine place for it. + it.skipIf(!symlinks)( + "moves a symlink to a directory into that directory", + () => { + fs.symlinkSync(path.join(dir, "sub"), path.join(dir, "link")); + renameIntoDirectory( + path.join(dir, "link"), + path.join(dir, "sub", "inner", "link"), + ); + expect( + fs.lstatSync(path.join(dir, "sub", "inner", "link")).isSymbolicLink(), + ).toBe(true); + expect(fs.existsSync(path.join(dir, "link"))).toBe(false); + expect(fs.existsSync(path.join(dir, "sub", "x.txt"))).toBe(true); + }, + ); + + it("leaves a missing source to the rename, which names it", () => { + const source = path.join(dir, "gone"); + const error = errorOf(source, path.join(dir, "sub", "gone")); + expect(error.code).toBe("ENOENT"); + expect(error.message).toContain(source); + expect(error.message).not.toContain("into itself"); + expectUntouched(); + }); +}); diff --git a/src/filesystem/pinned-directory.ts b/src/filesystem/pinned-directory.ts index 7374c9b7a9..223b6ef973 100644 --- a/src/filesystem/pinned-directory.ts +++ b/src/filesystem/pinned-directory.ts @@ -417,6 +417,50 @@ function returnStaged(staged: string, name: string): boolean { } } +/** + * Whether `destinationDirectory` is the directory at `sourcePath` or lies + * inside it (#5555), so the move would put a directory into itself. Decided + * by identity, not by comparing path strings: each directory from + * `destinationDirectory` up to the root is stat'd and compared with the + * source, so another spelling of the same directory (a different case on a + * case-insensitive volume, another normalization) cannot slip past. The + * paths are as validatePath resolved them, so going up one name at a time + * does not have to see through a symlink. A source that is not a directory + * itself, a symlink to one included, has no subtree to be moved into. + * + * This is a refusal, not an anchor: it reads by path, and when it is wrong + * (a directory swapped in between) the anchored steps of the move still hold. + */ +function isInsideSource( + sourcePath: string, + destinationDirectory: string, +): boolean { + let source: fs.BigIntStats; + try { + source = fs.lstatSync(sourcePath, { bigint: true }); + } catch { + // A missing source is the rename's error to report. + return false; + } + if (!source.isDirectory()) { + return false; + } + for (let directory = destinationDirectory; ; ) { + try { + if (isSameEntry(fs.statSync(directory, { bigint: true }), source)) { + return true; + } + } catch { + // Missing or unreadable, so not the source; one above it still can be. + } + const parent = path.dirname(directory); + if (parent === directory) { + return false; + } + directory = parent; + } +} + /** * Rename `sourcePath` to `destinationPath`, keeping both inside their * validated directories. rename() takes two paths and Node has no @@ -436,6 +480,11 @@ function returnStaged(staged: string, name: string): boolean { * cannot go back (something took its name in the meantime, or its directory * no longer resolves to the one validated, which is never entered), the error * says where it was left. + * + * A directory cannot be moved into itself, and that is refused (EINVAL) + * before step 1 (#5555): step 1 moves the source away, and with it the + * destination's directory, so step 2 would report that directory, which + * exists, as missing. */ export function renameIntoDirectory( sourcePath: string, @@ -444,6 +493,14 @@ export function renameIntoDirectory( const sourceDirectory = path.dirname(sourcePath); const name = path.basename(sourcePath); const destinationDirectory = path.dirname(destinationPath); + if (isInsideSource(sourcePath, destinationDirectory)) { + throw Object.assign( + new Error( + `Cannot move a directory into itself: ${destinationPath} is inside ${sourcePath}`, + ), + { code: "EINVAL" }, + ); + } const held = stagingName(); const expected = inDirectory(sourceDirectory, () => { try {