Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/filesystem-move-into-own-subtree.md
Original file line number Diff line number Diff line change
@@ -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: <destination> is inside <source>`, instead of reporting `Parent directory does not exist` for a destination directory that does exist.
3 changes: 3 additions & 0 deletions src/filesystem/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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: <destination>
is inside <source>`, 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
Expand Down
210 changes: 210 additions & 0 deletions src/filesystem/__tests__/move-into-own-subtree.test.ts
Original file line number Diff line number Diff line change
@@ -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();
});
});
57 changes: 57 additions & 0 deletions src/filesystem/pinned-directory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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,
Expand All @@ -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 {
Expand Down
Loading