// Path validation as a client sees it (#4854): traversal, symlinks, relative // and home paths, missing ancestors and Unicode normalization, each driven // through a tool call over the in-memory transport. Absorbs the former // nested-parents.test.ts (#4629) and unicode-paths.test.ts, which called // validatePath directly. A test that pins a known bug cites its issue. import fs from "fs/promises"; import os from "os"; import path from "path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import type { Client } from "@modelcontextprotocol/client"; import { call, connect, makeTempDir, quietStderr, textOf, type Connected, } from "./helpers.js"; /** True when this file system stores "café" composed and decomposed as two entries. */ async function holdsBothNormalizationForms(): Promise { const probe = await makeTempDir("mcp-unicode-probe-"); try { await fs.mkdir(path.join(probe, "caf\u00e9")); await fs.mkdir(path.join(probe, "cafe\u0301")); return true; } catch (error) { if ((error as NodeJS.ErrnoException).code === "EEXIST") return false; throw error; } finally { await fs.rm(probe, { recursive: true, force: true }); } } const distinctForms = await holdsBothNormalizationForms(); /** True when this file system finds "name" when asked for "NAME" (macOS and Windows by default). */ async function foldsCase(): Promise { const probe = await makeTempDir("mcp-case-probe-"); try { await fs.mkdir(path.join(probe, "name")); await fs.lstat(path.join(probe, "NAME")); return true; } catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return false; throw error; } finally { await fs.rm(probe, { recursive: true, force: true }); } } const caseInsensitive = await foldsCase(); let dir: string; let outside: string; let conn: Connected; let client: Client; async function read(p: string) { return call(client, "read_text_file", { path: p }); } beforeEach(async () => { quietStderr(); dir = await makeTempDir("mcp-fs-paths-"); outside = await makeTempDir("mcp-fs-outside-"); await fs.writeFile(path.join(outside, "secret.txt"), "secret"); conn = await connect([dir]); client = conn.client; }); afterEach(async () => { vi.restoreAllMocks(); await conn.close(); await fs.rm(dir, { recursive: true, force: true }); await fs.rm(outside, { recursive: true, force: true }); }); describe("the allow-list boundary", () => { it("refuses an absolute path outside, naming the allowed directories", async () => { const target = path.join(outside, "secret.txt"); const result = await read(target); expect(result.isError).toBe(true); expect(textOf(result)).toBe( `Access denied - path outside allowed directories: ${target} not in ${dir}`, ); }); it("refuses .. traversal out of the allowed directory", async () => { const result = await read( path.join(dir, "..", path.basename(outside), "secret.txt"), ); expect(textOf(result)).toMatch(/^Access denied - path outside/); }); it("refuses a sibling that merely shares the allowed directory's prefix", async () => { const sibling = `${dir}-evil`; await fs.mkdir(sibling); try { await fs.writeFile(path.join(sibling, "f"), "x"); const result = await read(path.join(sibling, "f")); expect(textOf(result)).toMatch(/^Access denied - path outside/); } finally { await fs.rm(sibling, { recursive: true, force: true }); } }); // A trailing quote or space is a legal filename character, so a sibling // named `'` is a different entry and must be checked as itself. // Windows refuses or strips these characters in names, so POSIX only. describe.skipIf(process.platform === "win32").each([ ["a single quote", "'"], ["a double quote", '"'], ["a space", " "], ])("a sibling whose name is the allowed directory plus %s", (_, suffix) => { let sibling: string; beforeEach(() => { sibling = `${dir}${suffix}`; }); afterEach(async () => { await fs.rm(sibling, { recursive: true, force: true }); }); it("refuses to read it as a file", async () => { await fs.writeFile(sibling, "secret"); const result = await read(sibling); expect(textOf(result)).toMatch(/^Access denied - path outside/); }); it("refuses to list it", async () => { await fs.mkdir(sibling); const result = await call(client, "list_directory", { path: sibling }); expect(textOf(result)).toMatch(/^Access denied - path outside/); }); it("refuses to create it", async () => { const result = await call(client, "create_directory", { path: sibling }); expect(textOf(result)).toMatch(/^Access denied - path outside/); await expect(fs.stat(sibling)).rejects.toThrow(); }); it("refuses to write it as a file", async () => { const result = await call(client, "write_file", { path: sibling, content: "x", }); expect(textOf(result)).toMatch(/^Access denied - path outside/); await expect(fs.stat(sibling)).rejects.toThrow(); }); }); it("allows the allowed directory itself", async () => { const result = await call(client, "list_directory", { path: dir }); expect(result.isError).toBeFalsy(); }); it("refuses a path containing a NUL byte", async () => { const result = await read(`${dir}/a\u0000b`); expect(textOf(result)).toMatch(/^Access denied - path outside/); }); it("refuses a ~ path outside the allowed directories, after expanding it", async () => { const result = await read("~/x.txt"); expect(textOf(result)).toBe( `Access denied - path outside allowed directories: ${path.join(os.homedir(), "x.txt")} not in ${dir}`, ); }); it.skipIf(process.platform === "win32")( "refuses a Windows drive path on a POSIX host rather than writing a literal file", async () => { const result = await call(client, "write_file", { path: "C:\\Users\\me\\notes.md", content: "x", }); expect(textOf(result)).toBe( "Access denied - Windows-style path received on a POSIX host: C:\\Users\\me\\notes.md", ); expect(await fs.readdir(dir)).toEqual([]); }, ); }); describe("relative paths", () => { it("resolves against the first allowed directory, not the process cwd", async () => { await fs.writeFile(path.join(dir, "rel.txt"), "relative"); const result = await read("rel.txt"); expect(textOf(result)).toBe("relative"); }); it("resolves against a later allowed directory when the first would escape", async () => { const second = await makeTempDir("mcp-fs-second-"); const multi = await connect([dir, second]); try { await fs.mkdir(path.join(second, "inner")); await fs.writeFile(path.join(second, "inner", "f.txt"), "second"); const relative = path.join("..", path.basename(second), "inner", "f.txt"); const result = await call(multi.client, "read_text_file", { path: relative, }); expect(textOf(result)).toBe("second"); } finally { await multi.close(); await fs.rm(second, { recursive: true, force: true }); } }); it("falls back to the first allowed directory and refuses an escaping relative path", async () => { const result = await read("../escape.txt"); expect(textOf(result)).toBe( `Access denied - path outside allowed directories: ${path.resolve(dir, "../escape.txt")} not in ${dir}`, ); }); it("resolves against the process cwd when there are no allowed directories, and refuses it", async () => { // A Roots client that offers no roots: with no directories and no Roots // at all the server closes the connection instead (#4992). const empty = await connect([], { capabilities: { roots: {} }, listRoots: () => [], }); try { const result = await call(empty.client, "read_text_file", { path: "anything.txt", }); expect(textOf(result)).toBe( `Access denied - no allowed directories: the client exposes no valid roots (${path.resolve(process.cwd(), "anything.txt")})`, ); } finally { await empty.close(); } }); }); describe("symlinks", () => { it("follows a symlink that stays inside", async () => { await fs.writeFile(path.join(dir, "real.txt"), "real"); await fs.symlink(path.join(dir, "real.txt"), path.join(dir, "alias.txt")); expect(textOf(await read(path.join(dir, "alias.txt")))).toBe("real"); }); it("refuses a symlink whose target is outside", async () => { const link = path.join(dir, "escape.txt"); await fs.symlink(path.join(outside, "secret.txt"), link); const result = await read(link); expect(textOf(result)).toBe( `Access denied - symlink target outside allowed directories: ${path.join(outside, "secret.txt")} not in ${dir}`, ); }); it("refuses a new path under a symlinked directory that leaves (#4629)", async () => { await fs.symlink(outside, path.join(dir, "link"), "junction"); const result = await call(client, "create_directory", { path: path.join(dir, "link", "a", "b"), }); expect(textOf(result)).toBe( `Access denied - symlink target outside allowed directories: ${outside} not in ${dir}`, ); expect(await fs.readdir(outside)).toEqual(["secret.txt"]); }); describe.skipIf(!caseInsensitive)( "spelled with other letter case on a case-insensitive file system", () => { const refusal = () => `Access denied - symlink target outside allowed directories: ${outside} not in ${dir}`; it("refuses create_directory under a symlink that leaves", async () => { await fs.symlink(outside, path.join(dir, "link"), "junction"); const result = await call(client, "create_directory", { path: path.join(dir, "LINK", "a"), }); expect(textOf(result)).toBe(refusal()); expect(await fs.readdir(outside)).toEqual(["secret.txt"]); }); it("refuses write_file when only an ancestor of the symlink is respelled", async () => { await fs.mkdir(path.join(dir, "sub")); await fs.symlink(outside, path.join(dir, "sub", "ln2"), "junction"); const result = await call(client, "write_file", { path: path.join(dir, "SUB", "ln2", "nested.txt"), content: "x", }); expect(textOf(result)).toBe(refusal()); expect(await fs.readdir(outside)).toEqual(["secret.txt"]); }); it("refuses a move_file destination under a symlink that leaves", async () => { await fs.symlink(outside, path.join(dir, "link"), "junction"); await fs.writeFile(path.join(dir, "note.txt"), "note"); const result = await call(client, "move_file", { source: path.join(dir, "note.txt"), destination: path.join(dir, "lInK", "moved.txt"), }); expect(textOf(result)).toBe(refusal()); expect(await fs.readdir(outside)).toEqual(["secret.txt"]); expect(await fs.readFile(path.join(dir, "note.txt"), "utf8")).toBe( "note", ); }); it("still writes a new file under a respelled directory that stays inside", async () => { await fs.mkdir(path.join(dir, "sub")); const result = await call(client, "write_file", { path: path.join(dir, "SUB", "new.txt"), content: "x", }); expect(result.isError).toBeFalsy(); expect( await fs.readFile(path.join(dir, "sub", "new.txt"), "utf8"), ).toBe("x"); }); it("refuses to write under a respelled dangling symlink, naming it as broken (#5191)", async () => { await fs.symlink( path.join(outside, "not-yet"), path.join(dir, "dangling"), ); const result = await call(client, "write_file", { path: path.join(dir, "DANGLING", "f.txt"), content: "x", }); expect(textOf(result)).toBe( `Broken symlink: ${path.join(dir, "DANGLING")} points to a target that does not exist`, ); await expect(fs.stat(path.join(outside, "not-yet"))).rejects.toThrow(); }); }, ); // #5191: the refusal is right, and the message names the symlink rather // than reporting its parent, which exists, as missing. it("refuses to write through a dangling symlink, naming it as broken (#5191)", async () => { const link = path.join(dir, "dangling"); await fs.symlink(path.join(outside, "not-yet"), link); const result = await call(client, "write_file", { path: link, content: "x", }); expect(textOf(result)).toBe( `Broken symlink: ${link} points to a target that does not exist`, ); await expect(fs.stat(path.join(outside, "not-yet"))).rejects.toThrow(); }); it("refuses to read a dangling symlink, naming it as broken (#5191)", async () => { const link = path.join(dir, "dangling"); await fs.symlink(path.join(dir, "gone.txt"), link); const result = await read(link); expect(result.isError).toBe(true); expect(textOf(result)).toBe( `Broken symlink: ${link} points to a target that does not exist`, ); }); it("names a dangling symlink in the middle of a path as broken (#5191)", async () => { const link = path.join(dir, "dangling-dir"); await fs.symlink(path.join(dir, "gone"), link); const result = await call(client, "write_file", { path: path.join(link, "f.txt"), content: "x", }); expect(textOf(result)).toBe( `Broken symlink: ${link} points to a target that does not exist`, ); await expect(fs.stat(path.join(dir, "gone"))).rejects.toThrow(); }); it("reports a realpath failure other than ENOENT as is", async () => { await fs.writeFile(path.join(dir, "file.txt"), ""); const result = await read(path.join(dir, "file.txt", "child")); // Windows reports the failing syscall as scandir rather than realpath. expect(textOf(result)).toMatch( process.platform === "win32" ? /^ENOTDIR: not a directory/ : /^ENOTDIR: not a directory, realpath/, ); }); }); describe("missing ancestors", () => { it("accepts a path several levels below the last existing directory (#4629)", async () => { const target = path.join(dir, "a", "b", "c"); const result = await call(client, "create_directory", { path: target }); expect(result.isError).toBeFalsy(); }); it('reports "Parent directory does not exist" when the allowed directory itself is gone', async () => { await fs.rm(dir, { recursive: true, force: true }); const result = await call(client, "write_file", { path: path.join(dir, "f.txt"), content: "x", }); expect(textOf(result)).toBe(`Parent directory does not exist: ${dir}`); }); }); describe("Unicode normalization", () => { it("resolves a composed (NFC) request to the decomposed (NFD) names on disk", async () => { const onDiskDir = "de\u0301marche"; const onDiskFile = "re\u0301sume\u0301.txt"; await fs.mkdir(path.join(dir, onDiskDir)); await fs.writeFile(path.join(dir, onDiskDir, onDiskFile), "content"); const result = await read( path.join(dir, "d\u00e9marche", "r\u00e9sum\u00e9.txt"), ); expect(textOf(result)).toBe("content"); }); it("keeps a new basename when the parent resolves through Unicode equivalence", async () => { await fs.mkdir(path.join(dir, "de\u0301marche")); await call(client, "write_file", { path: path.join(dir, "d\u00e9marche", "new.txt"), content: "x", }); expect( await fs.readFile(path.join(dir, "de\u0301marche", "new.txt"), "utf-8"), ).toBe("x"); }); // Normalization-insensitive file systems (APFS, HFS+) treat both spellings // as one name, so the ambiguous state cannot be created there. it.skipIf(!distinctForms)( "refuses a component that matches two canonically equivalent entries", async () => { await fs.mkdir(path.join(dir, "caf\u00e9")); await fs.mkdir(path.join(dir, "cafe\u0301")); const result = await call(client, "write_file", { path: path.join(dir, "cafe\u0341", "file.txt"), content: "x", }); expect(textOf(result)).toBe( "Ambiguous Unicode path component: cafe\u0341", ); }, ); // #1970: when the allowed directory's own name is NFD, an NFC spelling of // it used to fail the allow-list prefix check (a string comparison) before // the Unicode walk started, on any file system. it("accepts an NFC spelling of an NFD allowed directory (#1970)", async () => { const nfdRoot = path.join(dir, "Capture d\u2019e\u0301cran"); await fs.mkdir(nfdRoot); await fs.writeFile(path.join(nfdRoot, "shot.png"), "png"); const scoped = await connect([nfdRoot]); try { const requested = path.join(dir, "Capture d\u2019\u00e9cran", "shot.png"); const result = await call(scoped.client, "read_text_file", { path: requested, }); expect(textOf(result)).toBe("png"); } finally { await scoped.close(); } }); // #1970: a respelled allowed directory must not open a path into a // different directory that merely shares its name up to normalization. it.skipIf(!distinctForms)( "maps an NFD spelling of an NFC allowed directory onto it, never onto an NFD sibling (#1970)", async () => { const nfcRoot = path.join(dir, "caf\u00e9"); const nfdSibling = path.join(dir, "cafe\u0301"); await fs.mkdir(nfcRoot); await fs.mkdir(nfdSibling); await fs.writeFile(path.join(nfcRoot, "f.txt"), "allowed"); await fs.writeFile(path.join(nfdSibling, "f.txt"), "secret"); const scoped = await connect([nfcRoot]); try { const result = await call(scoped.client, "read_text_file", { path: path.join(nfdSibling, "f.txt"), }); expect(textOf(result)).toBe("allowed"); } finally { await scoped.close(); } }, ); it("refuses a path that only shares a normalized prefix with the allowed directory's name", async () => { const result = await read(`${dir}\u00a0x/f.txt`); expect(textOf(result)).toMatch(/^Access denied - path outside/); }); }); // #1970: macOS names screenshots "Screenshot ... at 2.40.40\u202fPM.png"; // a client lists the file, then sends the name back with a plain space. describe("Unicode space separators (#1970)", () => { const onDisk = "Screenshot 2025-04-23 at 2.40.40\u202fPM.png"; const typed = "Screenshot 2025-04-23 at 2.40.40 PM.png"; it("reads a file whose U+202F the request spells as U+0020", async () => { await fs.writeFile(path.join(dir, onDisk), "shot"); expect(textOf(await read(path.join(dir, typed)))).toBe("shot"); }); it("moves a file whose U+00A0 the request spells as U+0020", async () => { await fs.mkdir(path.join(dir, "Images")); await fs.writeFile(path.join(dir, "a\u00a0b.png"), "x"); const result = await call(client, "move_file", { source: path.join(dir, "a b.png"), destination: path.join(dir, "Images", "a b.png"), }); expect(result.isError).toBeFalsy(); expect(await fs.readdir(path.join(dir, "Images"))).toEqual(["a b.png"]); expect(await fs.readdir(dir)).toEqual(["Images"]); }); it("prefers the exact spelling when both are on disk", async () => { await fs.writeFile(path.join(dir, onDisk), "nnbsp"); await fs.writeFile(path.join(dir, typed), "space"); expect(textOf(await read(path.join(dir, typed)))).toBe("space"); expect(textOf(await read(path.join(dir, onDisk)))).toBe("nnbsp"); }); it("refuses a name that matches two entries differing only in their spaces", async () => { await fs.writeFile(path.join(dir, "a\u00a0b"), "1"); await fs.writeFile(path.join(dir, "a\u202fb"), "2"); const result = await read(path.join(dir, "a b")); expect(textOf(result)).toBe("Ambiguous Unicode path component: a b"); }); }); // #470: an allowed directory spelled in a letter case that matches neither // the configured nor the on-disk spelling failed the allow-list prefix check, // a string comparison, before the path was resolved. A case-folded compare // would admit a sibling on a case-sensitive directory, so the request is // respelled only where the file system says both spellings name one entry. describe("letter case of the allowed directory's own name (#470)", () => { let root: string; let scoped: Connected; beforeEach(async () => { root = path.join(dir, "CaseTest"); await fs.mkdir(path.join(root, "Sub"), { recursive: true }); await fs.writeFile(path.join(root, "Sub", "File.txt"), "inside"); scoped = await connect([root]); }); afterEach(async () => { await scoped.close(); }); const requested = () => path.join(dir, "CASETEST", "SUB", "FILE.TXT"); it.skipIf(!caseInsensitive)( "reads through a respelled allowed directory on a case-insensitive file system", async () => { const result = await call(scoped.client, "read_text_file", { path: requested(), }); expect(textOf(result)).toBe("inside"); }, ); it.skipIf(!caseInsensitive)( "creates a new file under a respelled allowed directory, inside it", async () => { const result = await call(scoped.client, "write_file", { path: path.join(dir, "casetest", "sub", "New.txt"), content: "new", }); expect(result.isError).toBeFalsy(); expect(await fs.readdir(path.join(root, "Sub"))).toContain("New.txt"); }, ); it.skipIf(caseInsensitive)( "refuses the respelling on a case-sensitive file system", async () => { const result = await call(scoped.client, "read_text_file", { path: requested(), }); expect(textOf(result)).toMatch(/^Access denied - path outside/); }, ); it.skipIf(caseInsensitive)( "never admits a sibling that differs from the allowed directory only in case", async () => { const sibling = path.join(dir, "casetest"); await fs.mkdir(sibling); await fs.writeFile(path.join(sibling, "secret.txt"), "secret"); const result = await call(scoped.client, "read_text_file", { path: path.join(sibling, "secret.txt"), }); expect(textOf(result)).toMatch(/^Access denied - path outside/); }, ); it("refuses a .. escape through a respelled allowed directory", async () => { const result = await call(scoped.client, "read_text_file", { path: path.join( dir, "CASETEST", "..", "..", path.basename(outside), "secret.txt", ), }); expect(textOf(result)).toMatch(/^Access denied - path outside/); }); });