Skip to content

Commit 15563b3

Browse files
authored
Merge pull request #5013 from modelcontextprotocol/v2/fix/4827-memory-preserve-file-mode
fix(memory): keep the memory file's mode across saves and refuse a read-only file (#4827)
2 parents 786fd24 + 382aff5 commit 15563b3

3 files changed

Lines changed: 76 additions & 27 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-memory": patch
3+
---
4+
5+
Saving the knowledge graph keeps the memory file's permission bits (an operator's `0600` no longer comes back `0644`), and a write to a read-only memory file now fails with `EACCES` instead of silently replacing it (#4827).

‎src/memory/__tests__/persistence.test.ts‎

Lines changed: 37 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,7 @@
22
// through an SDK Client over an in-memory transport (#4854): the JSONL file
33
// format, how unreadable lines are loaded and then kept on write, read and write
44
// failures as tool errors, the atomic temp-file save, and two servers sharing
5-
// one file. Tests that pin a known bug cite its issue (#4827),
6-
// so the PR that fixes it has a test to change.
5+
// one file.
76
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
87
import { promises as fs } from "fs";
98
import path from "path";
@@ -268,11 +267,10 @@ describe("memory persistence over the protocol", () => {
268267
});
269268
});
270269

271-
// KNOWN BUG #4827: pins current (wrong) behavior; the fix changes this assertion.
272-
// Characterizes #4827: saveGraph writes a new temp file and renames it over
273-
// the graph file, so the graph file takes a new file's mode. An operator's
274-
// 0600 is lost, and a read-only file is silently replaced. The fix for #4827
275-
// changes this test. POSIX only: Windows has no mode bits to lose.
270+
// #4827: saveGraph writes a new temp file and renames it over the graph
271+
// file, which replaces the file's inode. The save keeps the graph file's
272+
// own mode rather than a new file's, and refuses a read-only graph file as
273+
// a plain write would. POSIX only: Windows has no mode bits to lose.
276274
describe.skipIf(process.platform === "win32")("file mode (#4827)", () => {
277275
// The mode a file created now gets, which is what the temp file gets.
278276
async function newFileMode(): Promise<number> {
@@ -287,37 +285,50 @@ describe("memory persistence over the protocol", () => {
287285
return (await fs.stat(file)).mode & 0o777;
288286
}
289287

290-
it("replaces a hardened graph file's mode with a new file's mode", async () => {
288+
it("keeps a hardened graph file's mode across a save", async () => {
291289
const { client } = await open();
292290
await call(client, "create_entities", { entities: [alice] });
293291
// 0600 as in the issue, unless the umask already makes new files 0600;
294-
// the original mode must differ from a new file's for the loss to show.
295-
const expected = await newFileMode();
296-
const original = expected === 0o600 ? 0o640 : 0o600;
292+
// the original mode must differ from a new file's for a loss to show.
293+
const original = (await newFileMode()) === 0o600 ? 0o640 : 0o600;
297294
await fs.chmod(filePath, original);
295+
const writeFile = vi.spyOn(fs, "writeFile");
298296

299297
await call(client, "create_entities", { entities: [bob] });
300298

301-
expect(await modeOf(filePath)).toBe(expected);
302-
});
303-
304-
it("silently overwrites a read-only graph file", async () => {
305-
const { client } = await open();
306-
await call(client, "create_entities", { entities: [alice] });
307-
await fs.chmod(filePath, 0o444);
308-
const expected = await newFileMode();
309-
310-
const result = await call(client, "create_entities", {
311-
entities: [bob],
312-
});
313-
314-
expect(result.isError).toBeUndefined();
315-
expect(await modeOf(filePath)).toBe(expected);
299+
// The temp file is created with that mode, never a wider one first.
300+
expect(writeFile).toHaveBeenCalledWith(
301+
expect.stringMatching(/\.tmp$/),
302+
expect.any(String),
303+
{ mode: original },
304+
);
305+
expect(await modeOf(filePath)).toBe(original);
316306
expect((await call(client, "read_graph")).structuredContent).toEqual({
317307
entities: [alice, bob],
318308
relations: [],
319309
});
320310
});
311+
312+
// root may write a read-only file, so the refusal shows only without it.
313+
it.skipIf(process.getuid?.() === 0)(
314+
"refuses to overwrite a read-only graph file",
315+
async () => {
316+
const { client } = await open();
317+
await call(client, "create_entities", { entities: [alice] });
318+
await fs.chmod(filePath, 0o444);
319+
const before = await readFileText(filePath);
320+
321+
const result = await call(client, "create_entities", {
322+
entities: [bob],
323+
});
324+
325+
expect(result.isError).toBe(true);
326+
expect(textOf(result)).toMatch(/EACCES/);
327+
expect(await modeOf(filePath)).toBe(0o444);
328+
expect(await readFileText(filePath)).toBe(before);
329+
expect(await fs.readdir(dir)).toEqual(["memory.jsonl"]);
330+
},
331+
);
321332
});
322333

323334
// #4797: two servers on one file (two client processes in practice) used to

‎src/memory/index.ts‎

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -465,14 +465,47 @@ export class KnowledgeGraphManager {
465465
// complete old file or the complete new one, never a partial state.
466466
// The temp file is kept in the same directory so the rename stays on one
467467
// filesystem — renaming across mount points fails with EXDEV.
468+
//
469+
// The rename also replaces the graph file's inode, and a new file takes
470+
// the process umask, so the file's own mode would be lost (#4827): an
471+
// operator's 0600 would come back 0644, and a read-only file would be
472+
// silently replaced, since rename(2) needs only a writable directory.
473+
// So refuse a graph file this process may not write, as fs.writeFile
474+
// would (EACCES), and give the temp file the existing file's permission
475+
// bits before the rename, as src/filesystem/lib.ts preserves them for
476+
// the same write pattern. A graph file that does not exist yet has
477+
// nothing to preserve.
478+
let mode: number | undefined;
479+
try {
480+
await fs.access(this.memoryFilePath, fs.constants.W_OK);
481+
mode = (await fs.stat(this.memoryFilePath)).mode & 0o777;
482+
} catch (error) {
483+
if (
484+
!(error instanceof Error && "code" in error && error.code === "ENOENT")
485+
) {
486+
throw error;
487+
}
488+
}
489+
468490
const directory = path.dirname(this.memoryFilePath);
469491
const tempFilePath = path.join(
470492
directory,
471493
`${path.basename(this.memoryFilePath)}.${randomBytes(16).toString("hex")}.tmp`,
472494
);
473495

474496
try {
475-
await fs.writeFile(tempFilePath, lines.join("\n") + "\n");
497+
// Create the temp file with the existing mode, so the graph is never
498+
// readable through it more widely than through the file it replaces;
499+
// the umask can only narrow that. The chmod then restores any bits the
500+
// umask removed.
501+
await fs.writeFile(
502+
tempFilePath,
503+
lines.join("\n") + "\n",
504+
mode === undefined ? undefined : { mode },
505+
);
506+
if (mode !== undefined) {
507+
await fs.chmod(tempFilePath, mode);
508+
}
476509
await fs.rename(tempFilePath, this.memoryFilePath);
477510
} catch (error) {
478511
// Never leave a stray temp file behind on failure.

0 commit comments

Comments
 (0)