Skip to content
Merged
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/ghsa-48j5-hj63-c82c.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@modelcontextprotocol/server-memory": patch
---

fix(memory): GHSA-48j5-hj63-c82c
2 changes: 1 addition & 1 deletion src/memory/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
15 changes: 12 additions & 3 deletions src/memory/__tests__/atomic-save.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<typeof fs.open>
) => {
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([
Expand Down
145 changes: 138 additions & 7 deletions src/memory/__tests__/persistence.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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<typeof fs.open>
) => {
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],
});
Expand Down Expand Up @@ -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({
Expand Down Expand Up @@ -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>,
): void {
const realOpen = fs.open;
const realWriteFile = fs.writeFile;
vi.spyOn(fs, "open").mockImplementation((async (
...args: Parameters<typeof fs.open>
) => {
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<typeof fs.writeFile>
) => {
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<void> {
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
Expand Down
34 changes: 27 additions & 7 deletions src/memory/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down