Skip to content

Commit f438a62

Browse files
cliffhallclaude
andcommitted
fix(filesystem): move a file across filesystems by copying it (#5188)
rename() cannot cross a device boundary, so move_file failed with EXDEV between allowed directories on different mounts. On EXDEV, moveFile now falls back to moveFileAcrossDevices, which opens the source and creates the destination relative to their anchored directories (O_EXCL, no symlinks followed), copies the content, mode and times, then removes the source only while it is still the file copied. A failed step removes the copy and leaves the source in place. A directory or symlink is refused with a clear error rather than copied. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: cliffhall <[email protected]>
1 parent 1513547 commit f438a62

7 files changed

Lines changed: 476 additions & 2 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 moves a regular file between allowed directories on different filesystems (mounts, disks or shares), where it used to fail with `EXDEV`: it copies the file to a newly created destination, keeping its permissions and modification time, then removes the source, and removes a partial copy if anything fails. A directory or a symbolic link still cannot be moved across filesystems, and now fails with an error that says so.

‎src/filesystem/README.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,13 @@ The server's directory access control follows this flow:
161161
- `source` (string)
162162
- `destination` (string)
163163
- Fails if destination exists
164+
- Across filesystems (the source and destination on different mounts or
165+
disks), a regular file is moved by copying it to a newly created
166+
destination, with its permissions and modification time, and then removing
167+
the source. If the copy fails, the partial destination is removed and the
168+
source is left in place. A directory or a symbolic link cannot be moved
169+
across filesystems and fails with an error; move a directory's files one
170+
at a time instead
164171

165172
- **search_files**
166173
- Recursively search for files/directories that match or do not match patterns

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

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -703,6 +703,40 @@ describe("Lib Functions", () => {
703703

704704
expect(mockPinned.renameIntoDirectory).not.toHaveBeenCalled();
705705
});
706+
707+
it("copies and removes instead when the rename crosses a device (EXDEV)", async () => {
708+
mockFs.lstat.mockRejectedValueOnce(
709+
Object.assign(new Error("not found"), { code: "ENOENT" }),
710+
);
711+
mockPinned.renameIntoDirectory.mockImplementationOnce(() => {
712+
throw Object.assign(new Error("EXDEV: cross-device link"), {
713+
code: "EXDEV",
714+
});
715+
});
716+
717+
await moveFile("/test/source.txt", "/mnt/other/dest.txt");
718+
719+
expect(mockPinned.moveFileAcrossDevices).toHaveBeenCalledWith(
720+
"/test/source.txt",
721+
"/mnt/other/dest.txt",
722+
);
723+
});
724+
725+
it("reports a rename failure other than EXDEV as is, without copying", async () => {
726+
mockFs.lstat.mockRejectedValueOnce(
727+
Object.assign(new Error("not found"), { code: "ENOENT" }),
728+
);
729+
mockPinned.renameIntoDirectory.mockImplementationOnce(() => {
730+
throw Object.assign(new Error("EACCES: permission denied"), {
731+
code: "EACCES",
732+
});
733+
});
734+
735+
await expect(
736+
moveFile("/test/source.txt", "/test/dest.txt"),
737+
).rejects.toThrow("EACCES: permission denied");
738+
expect(mockPinned.moveFileAcrossDevices).not.toHaveBeenCalled();
739+
});
706740
});
707741
});
708742

‎src/filesystem/__tests__/pinned-directory.test.ts‎

Lines changed: 178 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import {
1313
createFileInDirectory,
1414
isChildDirectory,
1515
isSameDirectory,
16+
moveFileAcrossDevices,
1617
overwriteFileInDirectory,
1718
renameIntoDirectory,
1819
} from "../pinned-directory.js";
@@ -429,6 +430,183 @@ describe("renameIntoDirectory", () => {
429430
);
430431
});
431432

433+
// Each test here runs on one device: the helper is what moveFile falls back
434+
// to on EXDEV, and it never calls rename, so one device exercises it fully.
435+
describe("moveFileAcrossDevices", () => {
436+
const fail = (code: string) =>
437+
((...args: unknown[]) => {
438+
(args[args.length - 1] as (error: Error) => void)(errno(code));
439+
}) as never;
440+
441+
it("copies the content, mode and times, then removes the source", async () => {
442+
const source = path.join(dir, "a.bin");
443+
const destination = path.join(outside, "b.bin");
444+
// More than one 64 KiB chunk.
445+
const content = Buffer.alloc(200 * 1024, 7);
446+
fs.writeFileSync(source, content);
447+
fs.chmodSync(source, 0o640);
448+
fs.utimesSync(source, new Date(1_000_000_000), new Date(1_000_000_000));
449+
await moveFileAcrossDevices(source, destination);
450+
expect(fs.readFileSync(destination).equals(content)).toBe(true);
451+
expect(fs.existsSync(source)).toBe(false);
452+
const moved = fs.statSync(destination);
453+
if (process.platform !== "win32") {
454+
expect(moved.mode & 0o777).toBe(0o640);
455+
}
456+
expect(moved.mtimeMs).toBe(1_000_000_000);
457+
expect(process.cwd()).toBe(cwd);
458+
});
459+
460+
it("moves an empty file", async () => {
461+
const source = path.join(dir, "empty");
462+
fs.writeFileSync(source, "");
463+
await moveFileAcrossDevices(source, path.join(outside, "empty"));
464+
expect(fs.readFileSync(path.join(outside, "empty"), "utf-8")).toBe("");
465+
expect(fs.existsSync(source)).toBe(false);
466+
});
467+
468+
it("refuses a directory, and leaves it in place", async () => {
469+
const source = path.join(dir, "d");
470+
fs.mkdirSync(source);
471+
await expect(
472+
moveFileAcrossDevices(source, path.join(outside, "d")),
473+
).rejects.toThrow(`Cannot move a directory across filesystems: ${source}.`);
474+
expect(fs.statSync(source).isDirectory()).toBe(true);
475+
expect(fs.readdirSync(outside)).toEqual([]);
476+
});
477+
478+
it.skipIf(!symlinks)(
479+
"refuses a symlink rather than following or recreating it",
480+
async () => {
481+
const target = path.join(dir, "t.txt");
482+
fs.writeFileSync(target, "t");
483+
const source = path.join(dir, "l.txt");
484+
fs.symlinkSync(target, source);
485+
await expect(
486+
moveFileAcrossDevices(source, path.join(outside, "l.txt")),
487+
).rejects.toThrow(
488+
`Cannot move across filesystems: not a regular file: ${source}`,
489+
);
490+
expect(fs.lstatSync(source).isSymbolicLink()).toBe(true);
491+
expect(fs.readdirSync(outside)).toEqual([]);
492+
},
493+
);
494+
495+
it("refuses an existing destination with EEXIST, and keeps both", async () => {
496+
const source = path.join(dir, "a.txt");
497+
const destination = path.join(outside, "b.txt");
498+
fs.writeFileSync(source, "a");
499+
fs.writeFileSync(destination, "b");
500+
await expect(moveFileAcrossDevices(source, destination)).rejects.toThrow(
501+
expect.objectContaining({ code: "EEXIST" }),
502+
);
503+
expect(fs.readFileSync(source, "utf-8")).toBe("a");
504+
expect(fs.readFileSync(destination, "utf-8")).toBe("b");
505+
});
506+
507+
it.skipIf(!symlinks)(
508+
"refuses a destination directory that resolves somewhere else",
509+
async () => {
510+
fs.symlinkSync(outside, path.join(dir, "link"));
511+
const source = path.join(dir, "a.txt");
512+
fs.writeFileSync(source, "a");
513+
await expect(
514+
moveFileAcrossDevices(source, path.join(dir, "link", "b.txt")),
515+
).rejects.toThrow("Access denied");
516+
expect(fs.readdirSync(outside)).toEqual([]);
517+
expect(fs.readFileSync(source, "utf-8")).toBe("a");
518+
},
519+
);
520+
521+
it.each([
522+
["another file", { ino: -1 }],
523+
["not a regular file", { isFile: () => false }],
524+
])(
525+
"refuses, and closes the source, when it was replaced while being opened (%s)",
526+
async (_, replaced) => {
527+
const source = path.join(dir, "a.txt");
528+
fs.writeFileSync(source, "a");
529+
const realFstat = fs.fstatSync;
530+
vi.spyOn(fs, "fstatSync").mockImplementationOnce((fd) =>
531+
Object.assign(realFstat(fd), replaced),
532+
);
533+
const closeSync = vi.spyOn(fs, "closeSync");
534+
await expect(
535+
moveFileAcrossDevices(source, path.join(outside, "b.txt")),
536+
).rejects.toThrow(
537+
`Refusing to move: ${source} was replaced while it was being opened`,
538+
);
539+
expect(closeSync).toHaveBeenCalled();
540+
expect(fs.readdirSync(outside)).toEqual([]);
541+
},
542+
);
543+
544+
it.each(["read", "writeFile", "fchmod", "futimes"] as const)(
545+
"removes the partial copy, and keeps the source, when %s fails",
546+
async (step) => {
547+
const source = path.join(dir, "a.txt");
548+
fs.writeFileSync(source, "a");
549+
vi.spyOn(fs, step).mockImplementationOnce(fail("EIO"));
550+
await expect(
551+
moveFileAcrossDevices(source, path.join(outside, "b.txt")),
552+
).rejects.toThrow("EIO");
553+
expect(fs.readdirSync(outside)).toEqual([]);
554+
expect(fs.readFileSync(source, "utf-8")).toBe("a");
555+
},
556+
);
557+
558+
it("reports the copy's failure when removing the copy fails too", async () => {
559+
const source = path.join(dir, "a.txt");
560+
fs.writeFileSync(source, "a");
561+
vi.spyOn(fs, "read").mockImplementationOnce(fail("EIO"));
562+
vi.spyOn(fs, "unlinkSync").mockImplementationOnce(() => {
563+
throw errno("EBUSY");
564+
});
565+
await expect(
566+
moveFileAcrossDevices(source, path.join(outside, "b.txt")),
567+
).rejects.toThrow("EIO");
568+
expect(fs.readFileSync(source, "utf-8")).toBe("a");
569+
});
570+
571+
it("removes the copy, and keeps the source, when the source cannot be removed", async () => {
572+
const source = path.join(dir, "a.txt");
573+
fs.writeFileSync(source, "a");
574+
const realUnlink = fs.unlinkSync;
575+
vi.spyOn(fs, "unlinkSync")
576+
.mockImplementationOnce(() => {
577+
throw errno("EACCES");
578+
})
579+
.mockImplementation(realUnlink);
580+
await expect(
581+
moveFileAcrossDevices(source, path.join(outside, "b.txt")),
582+
).rejects.toThrow("EACCES");
583+
expect(fs.readdirSync(outside)).toEqual([]);
584+
expect(fs.readFileSync(source, "utf-8")).toBe("a");
585+
});
586+
587+
it("removes the copy, and leaves the new file, when the source was replaced during the copy", async () => {
588+
const source = path.join(dir, "a.txt");
589+
fs.writeFileSync(source, "a");
590+
const realFchmod = fs.fchmod;
591+
vi.spyOn(fs, "fchmod").mockImplementationOnce(((
592+
fd: number,
593+
mode: number,
594+
callback: (error: NodeJS.ErrnoException | null) => void,
595+
) => {
596+
fs.unlinkSync(source);
597+
fs.writeFileSync(source, "replacement");
598+
realFchmod(fd, mode, callback);
599+
}) as typeof fs.fchmod);
600+
await expect(
601+
moveFileAcrossDevices(source, path.join(outside, "b.txt")),
602+
).rejects.toThrow(
603+
`Refusing to remove: ${source} was replaced during the move`,
604+
);
605+
expect(fs.readdirSync(outside)).toEqual([]);
606+
expect(fs.readFileSync(source, "utf-8")).toBe("replacement");
607+
});
608+
});
609+
432610
describe("createDirectoryInPlace", () => {
433611
it("creates missing parents, and restores the working directory", () => {
434612
createDirectoryInPlace(path.join(dir, "a", "b", "c"));

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

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1383,6 +1383,72 @@ describe("move_file", () => {
13831383
expect(textOf(result)).toMatch(/^ENOENT/);
13841384
});
13851385

1386+
// #5188: rename cannot cross a device boundary. A second mount cannot be
1387+
// staged in a test, so the rename is made to fail as it would across one.
1388+
describe("across filesystems (rename fails with EXDEV)", () => {
1389+
const crossDevice = () =>
1390+
vi.spyOn(fsSync, "renameSync").mockImplementation(() => {
1391+
throw Object.assign(
1392+
new Error("EXDEV: cross-device link not permitted"),
1393+
{
1394+
code: "EXDEV",
1395+
},
1396+
);
1397+
});
1398+
1399+
it("moves a file by copying it and removing the source", async () => {
1400+
const source = path.join(dir, "a.txt");
1401+
const destination = path.join(dir, "sub", "b.txt");
1402+
await fs.mkdir(path.join(dir, "sub"));
1403+
await fs.writeFile(source, "across");
1404+
const rename = crossDevice();
1405+
const result = await call(client, "move_file", { source, destination });
1406+
expect(rename).toHaveBeenCalled();
1407+
expect(result.isError).toBeFalsy();
1408+
expect(textOf(result)).toBe(
1409+
`Successfully moved ${source} to ${destination}`,
1410+
);
1411+
expect(await fs.readFile(destination, "utf-8")).toBe("across");
1412+
await expect(fs.stat(source)).rejects.toThrow();
1413+
});
1414+
1415+
it("refuses a directory with a clear error, and leaves it in place", async () => {
1416+
const source = path.join(dir, "d1");
1417+
await fs.mkdir(source);
1418+
await fs.writeFile(path.join(source, "f"), "x");
1419+
crossDevice();
1420+
const result = await call(client, "move_file", {
1421+
source,
1422+
destination: path.join(dir, "d2"),
1423+
});
1424+
expect(result.isError).toBe(true);
1425+
expect(textOf(result)).toBe(
1426+
`Cannot move a directory across filesystems: ${source}. ` +
1427+
"Create the directory at the destination and move its files one at a time.",
1428+
);
1429+
expect(await fs.readFile(path.join(source, "f"), "utf-8")).toBe("x");
1430+
await expect(fs.stat(path.join(dir, "d2"))).rejects.toThrow();
1431+
});
1432+
1433+
it("leaves no partial destination when the copy fails", async () => {
1434+
const source = path.join(dir, "a.txt");
1435+
await fs.writeFile(source, "keep");
1436+
crossDevice();
1437+
vi.spyOn(fsSync, "read").mockImplementationOnce(((...args: unknown[]) => {
1438+
(args[args.length - 1] as (error: Error) => void)(
1439+
Object.assign(new Error("EIO: i/o error, read"), { code: "EIO" }),
1440+
);
1441+
}) as typeof fsSync.read);
1442+
const result = await call(client, "move_file", {
1443+
source,
1444+
destination: path.join(dir, "b.txt"),
1445+
});
1446+
expect(textOf(result)).toBe("EIO: i/o error, read");
1447+
expect(await fs.readdir(dir)).toEqual(["a.txt"]);
1448+
expect(await fs.readFile(source, "utf-8")).toBe("keep");
1449+
});
1450+
});
1451+
13861452
it("reports a destination lstat failure other than ENOENT as is", async () => {
13871453
await fs.writeFile(path.join(dir, "a.txt"), "a");
13881454
vi.spyOn(fs, "lstat").mockRejectedValueOnce(new Error("EACCES lstat"));

‎src/filesystem/lib.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import { isPathWithinAllowedDirectories } from "./path-validation.js";
99
import {
1010
createDirectoryInPlace,
1111
createFileInDirectory,
12+
moveFileAcrossDevices,
1213
overwriteFileInDirectory,
1314
renameIntoDirectory,
1415
} from "./pinned-directory.js";
@@ -633,7 +634,15 @@ export async function moveFile(
633634
} catch (error) {
634635
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
635636
// The destination's directory is pinned (see pinned-directory.ts).
636-
renameIntoDirectory(sourcePath, destinationPath);
637+
try {
638+
renameIntoDirectory(sourcePath, destinationPath);
639+
} catch (renameError) {
640+
// rename cannot cross a device boundary: copy, then remove (#5188).
641+
if ((renameError as NodeJS.ErrnoException).code !== "EXDEV") {
642+
throw renameError;
643+
}
644+
await moveFileAcrossDevices(sourcePath, destinationPath);
645+
}
637646
return;
638647
}
639648
throw error;

0 commit comments

Comments
 (0)