diff --git a/.changeset/ghsa-48j5-hj63-c82c.md b/.changeset/ghsa-48j5-hj63-c82c.md new file mode 100644 index 0000000000..253e2c5f74 --- /dev/null +++ b/.changeset/ghsa-48j5-hj63-c82c.md @@ -0,0 +1,5 @@ +--- +"@modelcontextprotocol/server-memory": patch +--- + +fix(memory): GHSA-48j5-hj63-c82c diff --git a/src/memory/README.md b/src/memory/README.md index f63366ea15..b119225f86 100644 --- a/src/memory/README.md +++ b/src/memory/README.md @@ -294,7 +294,7 @@ When `MEMORY_FILE_PATH` is not set and the server directory still holds a legacy - The directory must already exist: the server creates the memory file, not the directories above it. - The default stays where it is so that existing graphs keep loading. The [Docker](#docker) setup above keeps it in a named volume mounted over `/app/dist`, so the graph there survives restarts and draws no warning. -Saves are atomic. Every write tool writes the whole graph to a temporary file in the same directory and renames it over the memory file, so a server stopped or killed mid-save leaves the previous graph intact rather than a half-written file. The file's permission bits are kept across the rename. Writes from several processes are serialized by a lock, described next. +Saves are atomic. Every write tool writes the whole graph to a temporary file in the same directory and renames it over the memory file, so a server stopped or killed mid-save leaves the previous graph intact rather than a half-written file. The file's permission bits are kept across the rename. The temporary file is always newly created by the save. Writes from several processes are serialized by a lock, described next. #### Sharing one memory file between clients diff --git a/src/memory/__tests__/atomic-save.test.ts b/src/memory/__tests__/atomic-save.test.ts index 288ff9dd2a..4cd3fd7a1e 100644 --- a/src/memory/__tests__/atomic-save.test.ts +++ b/src/memory/__tests__/atomic-save.test.ts @@ -78,9 +78,18 @@ describe("KnowledgeGraphManager persistence durability", () => { expect(before).toContain("Alice"); // Simulate the process being interrupted while persisting the next write. - vi.spyOn(fs, "writeFile").mockImplementationOnce(async () => { - throw new Error("ENOSPC: simulated interruption"); - }); + const realOpen = fs.open; + vi.spyOn(fs, "open").mockImplementation((async ( + ...args: Parameters + ) => { + const handle = await realOpen(...args); + if (String(args[0]).endsWith(".tmp")) { + handle.writeFile = async () => { + throw new Error("ENOSPC: simulated interruption"); + }; + } + return handle; + }) as typeof fs.open); await expect( manager.createEntities([ diff --git a/src/memory/__tests__/persistence.test.ts b/src/memory/__tests__/persistence.test.ts index b1d0236a77..ffadf11287 100644 --- a/src/memory/__tests__/persistence.test.ts +++ b/src/memory/__tests__/persistence.test.ts @@ -6,6 +6,7 @@ import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; import { promises as fs } from "fs"; import path from "path"; +import os from "os"; import { call, connect, @@ -255,9 +256,20 @@ describe("memory persistence over the protocol", () => { it("keeps serving after a failed save", async () => { const { client } = await open(); - vi.spyOn(fs, "writeFile").mockRejectedValueOnce( - new Error("ENOSPC: simulated full disk"), - ); + const realOpen = fs.open; + let refused = false; + vi.spyOn(fs, "open").mockImplementation((async ( + ...args: Parameters + ) => { + const handle = await realOpen(...args); + if (!refused && String(args[0]).endsWith(".tmp")) { + refused = true; + handle.writeFile = async () => { + throw new Error("ENOSPC: simulated full disk"); + }; + } + return handle; + }) as typeof fs.open); const failed = await call(client, "create_entities", { entities: [alice], }); @@ -296,15 +308,15 @@ describe("memory persistence over the protocol", () => { // the original mode must differ from a new file's for a loss to show. const original = (await newFileMode()) === 0o600 ? 0o640 : 0o600; await fs.chmod(filePath, original); - const writeFile = vi.spyOn(fs, "writeFile"); + const openSpy = vi.spyOn(fs, "open"); await call(client, "create_entities", { entities: [bob] }); // The temp file is created with that mode, never a wider one first. - expect(writeFile).toHaveBeenCalledWith( + expect(openSpy).toHaveBeenCalledWith( expect.stringMatching(/\.tmp$/), - expect.any(String), - { mode: original }, + "wx", + original, ); expect(await modeOf(filePath)).toBe(original); expect((await call(client, "read_graph")).structuredContent).toEqual({ @@ -335,6 +347,125 @@ describe("memory persistence over the protocol", () => { ); }); + // The temp file's name is in a directory others may write, so anything can + // appear at it while a save runs. The save creates it exclusively and then + // works only through its own handle: whatever stands at the name (a symlink + // to another file, say) is never written, chmodded or renamed onto the + // graph path. POSIX only: creating a symlink on Windows needs privileges. + describe.skipIf(process.platform === "win32")("the temp file's name", () => { + let outsideDir: string; + let outside: string; + const outsideText = "not part of the graph\n"; + + beforeEach(async () => { + outsideDir = await fs.mkdtemp(path.join(os.tmpdir(), "memory-outside-")); + outside = path.join(outsideDir, "outside.txt"); + await fs.writeFile(outside, outsideText); + await fs.chmod(outside, 0o600); + }); + + afterEach(async () => { + await fs.rm(outsideDir, { recursive: true, force: true }); + }); + + function isTempPath(target: unknown): target is string { + return ( + typeof target === "string" && + path.dirname(target) === dir && + target.endsWith(".tmp") + ); + } + + // Runs hook on the temp path when the save creates its temp file, + // before the creating call (when: "before") or after it (when: "after"). + function onTempCreate( + when: "before" | "after", + hook: (tempPath: string) => Promise, + ): void { + const realOpen = fs.open; + const realWriteFile = fs.writeFile; + vi.spyOn(fs, "open").mockImplementation((async ( + ...args: Parameters + ) => { + if (!isTempPath(args[0])) return realOpen(...args); + if (when === "before") await hook(args[0]); + const handle = await realOpen(...args); + if (when === "after") await hook(args[0]); + return handle; + }) as typeof fs.open); + vi.spyOn(fs, "writeFile").mockImplementation((async ( + ...args: Parameters + ) => { + if (!isTempPath(args[0])) return realWriteFile(...args); + if (when === "before") await hook(args[0]); + await realWriteFile(...args); + if (when === "after") await hook(args[0]); + }) as typeof fs.writeFile); + } + + async function seed(): Promise<{ + client: Connection["client"]; + before: string; + }> { + const { client } = await open(); + await call(client, "create_entities", { entities: [alice] }); + await fs.chmod(filePath, 0o644); + return { client, before: await readFileText(filePath) }; + } + + async function expectOnlyTheGraphUntouched(before: string): Promise { + expect((await fs.stat(outside)).mode & 0o777).toBe(0o600); + expect(await readFileText(outside)).toBe(outsideText); + expect((await fs.lstat(filePath)).isFile()).toBe(true); + expect(await readFileText(filePath)).toBe(before); + expect(await fs.readdir(dir)).toEqual(["memory.jsonl"]); + } + + it("never writes through a link already at the temp name", async () => { + const { client, before } = await seed(); + onTempCreate("before", (tempPath) => fs.symlink(outside, tempPath)); + + const result = await call(client, "create_entities", { + entities: [bob], + }); + + expect(result.isError).toBe(true); + expect(textOf(result)).toMatch(/EEXIST/); + await expectOnlyTheGraphUntouched(before); + }); + + it("refuses the save when the temp name is replaced after it is created", async () => { + const { client, before } = await seed(); + onTempCreate("after", async (tempPath) => { + await fs.unlink(tempPath); + await fs.symlink(outside, tempPath); + }); + + const result = await call(client, "create_entities", { + entities: [bob], + }); + + expect(result.isError).toBe(true); + expect(textOf(result)).toMatch(/was replaced/); + await expectOnlyTheGraphUntouched(before); + }); + + it("saves normally when nothing else touches the temp name", async () => { + const { client } = await seed(); + onTempCreate("after", async () => {}); + + await call(client, "create_entities", { entities: [bob] }); + + expect((await fs.stat(outside)).mode & 0o777).toBe(0o600); + expect((await fs.lstat(filePath)).isFile()).toBe(true); + expect((await fs.stat(filePath)).mode & 0o777).toBe(0o644); + expect((await call(client, "read_graph")).structuredContent).toEqual({ + entities: [alice, bob], + relations: [], + }); + }); + }); + // #4797: two servers on one file (two client processes in practice) used to // both load the same graph, and the second save replaced the first, with // both calls reporting success. Each graph load here is held long enough for diff --git a/src/memory/index.ts b/src/memory/index.ts index cd94887230..6df277c4fb 100644 --- a/src/memory/index.ts +++ b/src/memory/index.ts @@ -1146,22 +1146,42 @@ export class KnowledgeGraphManager { `${path.basename(this.memoryFilePath)}.${randomBytes(16).toString("hex")}.tmp`, ); + // The directory may be writable by others, so anything can appear at + // the temp file's name while the save runs. Create it exclusively ("wx", + // O_CREAT | O_EXCL), which fails rather than open whatever is already + // there, a symlink included, and then write and chmod it only through + // the handle, which keeps reaching the file this call created whatever + // happens to the name. Only the rename has to go by name. + let handle: FileHandle | undefined; try { // Create the temp file with the existing mode, so the graph is never // readable through it more widely than through the file it replaces; // the umask can only narrow that. The chmod then restores any bits the // umask removed. - await fs.writeFile( - tempFilePath, - content, - mode === undefined ? undefined : { mode }, - ); + handle = await fs.open(tempFilePath, "wx", mode); + await handle.writeFile(content); if (mode !== undefined) { - await fs.chmod(tempFilePath, mode); + await handle.chmod(mode); + } + // The rename moves whatever the name holds now, onto the graph path, + // so refuse unless that is still the file written above. Compare while + // the handle is open: the open file's inode number cannot be reused by + // another file until it is closed. + const written = await handle.stat({ bigint: true }); + const named = await fs.lstat(tempFilePath, { bigint: true }); + if (named.ino !== written.ino || named.dev !== written.dev) { + throw new Error( + `Refused to save: ${tempFilePath} was replaced while the graph was ` + + "being written to it. Nothing was saved.", + ); } + await handle.close(); + handle = undefined; await fs.rename(tempFilePath, this.memoryFilePath); } catch (error) { - // Never leave a stray temp file behind on failure. + await handle?.close().catch(() => {}); + // Never leave a stray temp file behind on failure. When the name was + // replaced this removes the replacement, never what a link points at. await fs.unlink(tempFilePath).catch(() => {}); throw error; }