Skip to content

Commit 5a44875

Browse files
0ywfeayushbunny11
andcommitted
fix(filesystem): write in place to preserve birthtime and file identity (modelcontextprotocol#4512)
writeFileContent and applyFileEdits replaced existing files via a temp-file + fs.rename pattern. While this provided crash-atomicity and symlink safety, every write created a new inode, destroying the file's creation timestamp (birthtime) and severing hard links. The server's own get_file_info reports birthtime as a first-class field, making this internally inconsistent. Implements the fix set out in modelcontextprotocol#4512: 1. fs.open(filePath, O_RDWR | O_NOFOLLOW) — rejects symlinks with ELOOP, matching the security guarantee of the rename pattern. 2. fstat the handle and refuse anything that is not a regular file, so a FIFO or device swapped in after validation is not written through. 3. truncate(0) + write through the handle → same inode, birthtime, hard links and permission bits. New files still use the wx flag (exclusive create), unchanged. Windows keeps the temp+rename path. fs.constants.O_NOFOLLOW does not exist there, so `O_RDWR | O_NOFOLLOW` would collapse to a plain O_RDWR open and silently drop the symlink protection rather than enforce it. Creating a symlink on Windows already requires elevation, so the existing strategy remains the right default on that platform. Ayush Padhy caught the Windows problem: he raised it on modelcontextprotocol#4512 and implemented the same fix independently in modelcontextprotocol#4515. An earlier revision of this PR had the unconditional O_NOFOLLOW open and would have removed the protection on win32 while appearing to enforce it. modelcontextprotocol#4515 was closed in favour of this one with his agreement. This also subsumes modelcontextprotocol#4115. That fix restored permission bits with a stat + chmod round-trip *after* the rename, because the rename had already replaced the inode and the temp file carried default 0644 permissions. Writing in place never replaces the inode, so mode bits survive by construction. The modelcontextprotocol#4115 tests are retained and retargeted to assert no rename and no chmod occur on POSIX; its chmod path is kept and still covered on the win32 branch. Adds __tests__/write-preserves-identity.test.ts, which exercises the real filesystem rather than mocks — the inode surviving a write is precisely what a mocked fs cannot demonstrate. All four cases fail on current main and pass here: inode/birthtime/mode preserved across write_file and edit_file, hard links intact, and a symlinked target rejected rather than silently replaced with a regular file. Trade-off: in-place writes lose crash-atomicity (a crash mid-write can leave a partially written file). The rename pattern avoided this. If crash-atomicity is considered essential, a follow-up could add an opt-in flag to select the rename strategy. Co-Authored-By: Ayush Padhy <[email protected]>
1 parent d73f99e commit 5a44875

3 files changed

Lines changed: 291 additions & 155 deletions

File tree

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

Lines changed: 146 additions & 113 deletions
Original file line numberDiff line numberDiff line change
@@ -343,39 +343,95 @@ describe('Lib Functions', () => {
343343
});
344344

345345
describe('writeFileContent', () => {
346-
it('writes file content', async () => {
346+
it('creates new file with wx flag', async () => {
347347
mockFs.writeFile.mockResolvedValueOnce(undefined);
348-
348+
349349
await writeFileContent('/test/file.txt', 'new content');
350-
350+
351351
expect(mockFs.writeFile).toHaveBeenCalledWith('/test/file.txt', 'new content', { encoding: "utf-8", flag: 'wx' });
352352
});
353353

354+
it('writes in place when file exists (preserves inode / birthtime)', async () => {
355+
const eexist = Object.assign(new Error('EEXIST'), { code: 'EEXIST' });
356+
mockFs.writeFile.mockRejectedValueOnce(eexist);
357+
const mockFh = {
358+
stat: vi.fn().mockResolvedValue({ isFile: () => true }),
359+
truncate: vi.fn().mockResolvedValue(undefined),
360+
write: vi.fn().mockResolvedValue(undefined),
361+
close: vi.fn().mockResolvedValue(undefined),
362+
};
363+
mockFs.open.mockResolvedValueOnce(mockFh);
364+
365+
await writeFileContent('/test/file.txt', 'updated');
366+
367+
expect(mockFs.open).toHaveBeenCalledWith('/test/file.txt', expect.any(Number));
368+
expect(mockFh.truncate).toHaveBeenCalledWith(0);
369+
expect(mockFh.write).toHaveBeenCalledWith('updated', 0, 'utf-8');
370+
expect(mockFh.close).toHaveBeenCalled();
371+
});
372+
354373
it('preserves file permissions when overwriting existing file', async () => {
355-
// First writeFile call with 'wx' flag fails because file exists
356-
mockFs.writeFile.mockRejectedValueOnce(Object.assign(new Error('EEXIST'), { code: 'EEXIST' }));
357-
// stat returns executable permissions
358-
mockFs.stat.mockResolvedValueOnce({ mode: 0o100755 });
359-
// Second writeFile (to temp) succeeds
360-
mockFs.writeFile.mockResolvedValueOnce(undefined);
361-
mockFs.rename.mockResolvedValueOnce(undefined);
362-
mockFs.chmod.mockResolvedValueOnce(undefined);
374+
// Regression guard for #4115. Writing in place never replaces the
375+
// inode, so the original mode bits survive by construction and no
376+
// stat/chmod round-trip is needed to put them back.
377+
const eexist = Object.assign(new Error('EEXIST'), { code: 'EEXIST' });
378+
mockFs.writeFile.mockRejectedValueOnce(eexist);
379+
const mockFh = {
380+
stat: vi.fn().mockResolvedValue({ isFile: () => true }),
381+
truncate: vi.fn().mockResolvedValue(undefined),
382+
write: vi.fn().mockResolvedValue(undefined),
383+
close: vi.fn().mockResolvedValue(undefined),
384+
};
385+
mockFs.open.mockResolvedValueOnce(mockFh);
363386

364387
await writeFileContent('/test/script.sh', 'new content');
365388

366-
expect(mockFs.stat).toHaveBeenCalledWith('/test/script.sh');
367-
expect(mockFs.chmod).toHaveBeenCalledWith('/test/script.sh', 0o755);
389+
expect(mockFs.rename).not.toHaveBeenCalled();
390+
expect(mockFs.chmod).not.toHaveBeenCalled();
391+
expect(mockFh.write).toHaveBeenCalledWith('new content', 0, 'utf-8');
368392
});
369393

370-
it('does not fail the write when chmod fails', async () => {
371-
mockFs.writeFile.mockRejectedValueOnce(Object.assign(new Error('EEXIST'), { code: 'EEXIST' }));
372-
mockFs.stat.mockResolvedValueOnce({ mode: 0o100755 });
373-
mockFs.writeFile.mockResolvedValueOnce(undefined);
374-
mockFs.rename.mockResolvedValueOnce(undefined);
375-
mockFs.chmod.mockRejectedValueOnce(Object.assign(new Error('EPERM'), { code: 'EPERM' }));
394+
it('refuses to write when the target is not a regular file', async () => {
395+
const eexist = Object.assign(new Error('EEXIST'), { code: 'EEXIST' });
396+
mockFs.writeFile.mockRejectedValueOnce(eexist);
397+
const mockFh = {
398+
stat: vi.fn().mockResolvedValue({ isFile: () => false }),
399+
truncate: vi.fn().mockResolvedValue(undefined),
400+
write: vi.fn().mockResolvedValue(undefined),
401+
close: vi.fn().mockResolvedValue(undefined),
402+
};
403+
mockFs.open.mockResolvedValueOnce(mockFh);
376404

377-
await expect(writeFileContent('/test/script.sh', 'new content')).resolves.toBeUndefined();
378-
expect(mockFs.unlink).not.toHaveBeenCalled();
405+
await expect(writeFileContent('/test/fifo', 'payload')).rejects.toThrow(
406+
'not a regular file'
407+
);
408+
409+
expect(mockFh.truncate).not.toHaveBeenCalled();
410+
expect(mockFh.write).not.toHaveBeenCalled();
411+
expect(mockFh.close).toHaveBeenCalled();
412+
});
413+
414+
it('falls back to temp+rename on win32, where O_NOFOLLOW does not exist', async () => {
415+
const original = process.platform;
416+
Object.defineProperty(process, 'platform', { value: 'win32' });
417+
try {
418+
const eexist = Object.assign(new Error('EEXIST'), { code: 'EEXIST' });
419+
mockFs.writeFile.mockRejectedValueOnce(eexist);
420+
mockFs.stat.mockResolvedValueOnce({ mode: 0o100755 });
421+
mockFs.writeFile.mockResolvedValueOnce(undefined);
422+
mockFs.rename.mockResolvedValueOnce(undefined);
423+
mockFs.chmod.mockResolvedValueOnce(undefined);
424+
425+
await writeFileContent('/test/script.sh', 'new content');
426+
427+
// An O_NOFOLLOW open would silently degrade to a plain O_RDWR open
428+
// on Windows, so the rename strategy is kept there instead.
429+
expect(mockFs.open).not.toHaveBeenCalled();
430+
expect(mockFs.rename).toHaveBeenCalled();
431+
expect(mockFs.chmod).toHaveBeenCalledWith('/test/script.sh', 0o755);
432+
} finally {
433+
Object.defineProperty(process, 'platform', { value: original });
434+
}
379435
});
380436
});
381437

@@ -505,47 +561,47 @@ describe('Lib Functions', () => {
505561

506562
describe('File Editing Functions', () => {
507563
describe('applyFileEdits', () => {
564+
let mockFileHandle: any;
565+
508566
beforeEach(() => {
509567
mockFs.readFile.mockResolvedValue('line1\nline2\nline3\n');
510-
mockFs.writeFile.mockResolvedValue(undefined);
511-
mockFs.stat.mockResolvedValue({ mode: 0o100644 });
512-
mockFs.chmod.mockResolvedValue(undefined);
568+
mockFileHandle = {
569+
stat: vi.fn().mockResolvedValue({ isFile: () => true }),
570+
truncate: vi.fn().mockResolvedValue(undefined),
571+
write: vi.fn().mockResolvedValue(undefined),
572+
close: vi.fn().mockResolvedValue(undefined),
573+
};
574+
mockFs.open.mockResolvedValue(mockFileHandle);
513575
});
514576

515577
it('applies simple text replacement', async () => {
516578
const edits = [
517579
{ oldText: 'line2', newText: 'modified line2' }
518580
];
519-
520-
mockFs.rename.mockResolvedValueOnce(undefined);
521-
581+
522582
const result = await applyFileEdits('/test/file.txt', edits, false);
523-
583+
524584
expect(result).toContain('modified line2');
525-
// Should write to temporary file then rename
526-
expect(mockFs.writeFile).toHaveBeenCalledWith(
527-
expect.stringMatching(/\/test\/file\.txt\.[a-f0-9]+\.tmp$/),
585+
expect(mockFs.open).toHaveBeenCalledWith('/test/file.txt', expect.any(Number));
586+
expect(mockFileHandle.truncate).toHaveBeenCalledWith(0);
587+
expect(mockFileHandle.write).toHaveBeenCalledWith(
528588
'line1\nmodified line2\nline3\n',
589+
0,
529590
'utf-8'
530591
);
531-
expect(mockFs.rename).toHaveBeenCalledWith(
532-
expect.stringMatching(/\/test\/file\.txt\.[a-f0-9]+\.tmp$/),
533-
'/test/file.txt'
534-
);
592+
expect(mockFileHandle.close).toHaveBeenCalled();
535593
});
536594

537595
it('treats dollar signs in replacement text literally', async () => {
538596
const edits = [
539597
{ oldText: 'line2', newText: "price=$$; match=$&; before=$`; after=$'" }
540598
];
541599

542-
mockFs.rename.mockResolvedValueOnce(undefined);
543-
544600
await applyFileEdits('/test/file.txt', edits, false);
545601

546-
expect(mockFs.writeFile).toHaveBeenCalledWith(
547-
expect.stringMatching(/\/test\/file\.txt\.[a-f0-9]+\.tmp$/),
602+
expect(mockFileHandle.write).toHaveBeenCalledWith(
548603
"line1\nprice=$$; match=$&; before=$`; after=$'\nline3\n",
604+
0,
549605
'utf-8'
550606
);
551607
});
@@ -554,159 +610,136 @@ describe('Lib Functions', () => {
554610
const edits = [
555611
{ oldText: 'line2', newText: 'modified line2' }
556612
];
557-
613+
558614
const result = await applyFileEdits('/test/file.txt', edits, true);
559-
615+
560616
expect(result).toContain('modified line2');
561-
expect(mockFs.writeFile).not.toHaveBeenCalled();
617+
expect(mockFs.open).not.toHaveBeenCalled();
562618
});
563619

564620
it('applies multiple edits sequentially', async () => {
565621
const edits = [
566622
{ oldText: 'line1', newText: 'first line' },
567623
{ oldText: 'line3', newText: 'third line' }
568624
];
569-
570-
mockFs.rename.mockResolvedValueOnce(undefined);
571-
625+
572626
await applyFileEdits('/test/file.txt', edits, false);
573-
574-
expect(mockFs.writeFile).toHaveBeenCalledWith(
575-
expect.stringMatching(/\/test\/file\.txt\.[a-f0-9]+\.tmp$/),
627+
628+
expect(mockFileHandle.write).toHaveBeenCalledWith(
576629
'first line\nline2\nthird line\n',
630+
0,
577631
'utf-8'
578632
);
579-
expect(mockFs.rename).toHaveBeenCalledWith(
580-
expect.stringMatching(/\/test\/file\.txt\.[a-f0-9]+\.tmp$/),
581-
'/test/file.txt'
582-
);
583633
});
584634

585635
it('handles whitespace-flexible matching', async () => {
586636
mockFs.readFile.mockResolvedValue(' line1\n line2\n line3\n');
587-
637+
588638
const edits = [
589639
{ oldText: 'line2', newText: 'modified line2' }
590640
];
591-
592-
mockFs.rename.mockResolvedValueOnce(undefined);
593-
641+
594642
await applyFileEdits('/test/file.txt', edits, false);
595-
596-
expect(mockFs.writeFile).toHaveBeenCalledWith(
597-
expect.stringMatching(/\/test\/file\.txt\.[a-f0-9]+\.tmp$/),
643+
644+
expect(mockFileHandle.write).toHaveBeenCalledWith(
598645
' line1\n modified line2\n line3\n',
646+
0,
599647
'utf-8'
600648
);
601-
expect(mockFs.rename).toHaveBeenCalledWith(
602-
expect.stringMatching(/\/test\/file\.txt\.[a-f0-9]+\.tmp$/),
603-
'/test/file.txt'
604-
);
605649
});
606650

607651
it('preserves file permissions after applying edits', async () => {
608-
mockFs.stat.mockResolvedValue({ mode: 0o100755 });
652+
// Regression guard for #4115. The edit is written through the existing
653+
// file handle, so the inode - and with it the mode bits - is never
654+
// replaced. No rename means no permissions to restore afterwards.
609655
const edits = [
610656
{ oldText: 'line2', newText: 'modified line2' }
611657
];
612-
613-
mockFs.rename.mockResolvedValueOnce(undefined);
614-
658+
615659
await applyFileEdits('/test/script.sh', edits, false);
616-
617-
expect(mockFs.stat).toHaveBeenCalledWith('/test/script.sh');
618-
expect(mockFs.chmod).toHaveBeenCalledWith('/test/script.sh', 0o755);
660+
661+
expect(mockFs.rename).not.toHaveBeenCalled();
662+
expect(mockFs.chmod).not.toHaveBeenCalled();
663+
expect(mockFileHandle.write).toHaveBeenCalledWith(
664+
'line1\nmodified line2\nline3\n',
665+
0,
666+
'utf-8'
667+
);
619668
});
620669

621-
it('does not restore permissions in dry run mode', async () => {
670+
it('does not touch the file at all in dry run mode', async () => {
622671
const edits = [
623672
{ oldText: 'line2', newText: 'modified line2' }
624673
];
625-
674+
626675
await applyFileEdits('/test/file.txt', edits, true);
627-
676+
677+
expect(mockFs.open).not.toHaveBeenCalled();
678+
expect(mockFs.rename).not.toHaveBeenCalled();
628679
expect(mockFs.chmod).not.toHaveBeenCalled();
629680
});
630681

631682
it('throws error for non-matching edits', async () => {
632683
const edits = [
633684
{ oldText: 'nonexistent line', newText: 'replacement' }
634685
];
635-
686+
636687
await expect(applyFileEdits('/test/file.txt', edits, false))
637688
.rejects.toThrow('Could not find exact match for edit');
638689
});
639690

640691
it('handles complex multi-line edits with indentation', async () => {
641692
mockFs.readFile.mockResolvedValue('function test() {\n console.log("hello");\n return true;\n}');
642-
693+
643694
const edits = [
644-
{
645-
oldText: ' console.log("hello");\n return true;',
646-
newText: ' console.log("world");\n console.log("test");\n return false;'
695+
{
696+
oldText: ' console.log("hello");\n return true;',
697+
newText: ' console.log("world");\n console.log("test");\n return false;'
647698
}
648699
];
649-
650-
mockFs.rename.mockResolvedValueOnce(undefined);
651-
700+
652701
await applyFileEdits('/test/file.js', edits, false);
653-
654-
expect(mockFs.writeFile).toHaveBeenCalledWith(
655-
expect.stringMatching(/\/test\/file\.js\.[a-f0-9]+\.tmp$/),
702+
703+
expect(mockFileHandle.write).toHaveBeenCalledWith(
656704
'function test() {\n console.log("world");\n console.log("test");\n return false;\n}',
705+
0,
657706
'utf-8'
658707
);
659-
expect(mockFs.rename).toHaveBeenCalledWith(
660-
expect.stringMatching(/\/test\/file\.js\.[a-f0-9]+\.tmp$/),
661-
'/test/file.js'
662-
);
663708
});
664709

665710
it('handles edits with different indentation patterns', async () => {
666711
mockFs.readFile.mockResolvedValue(' if (condition) {\n doSomething();\n }');
667-
712+
668713
const edits = [
669-
{
670-
oldText: 'doSomething();',
671-
newText: 'doSomethingElse();\n doAnotherThing();'
714+
{
715+
oldText: 'doSomething();',
716+
newText: 'doSomethingElse();\n doAnotherThing();'
672717
}
673718
];
674-
675-
mockFs.rename.mockResolvedValueOnce(undefined);
676-
719+
677720
await applyFileEdits('/test/file.js', edits, false);
678-
679-
expect(mockFs.writeFile).toHaveBeenCalledWith(
680-
expect.stringMatching(/\/test\/file\.js\.[a-f0-9]+\.tmp$/),
721+
722+
expect(mockFileHandle.write).toHaveBeenCalledWith(
681723
' if (condition) {\n doSomethingElse();\n doAnotherThing();\n }',
724+
0,
682725
'utf-8'
683726
);
684-
expect(mockFs.rename).toHaveBeenCalledWith(
685-
expect.stringMatching(/\/test\/file\.js\.[a-f0-9]+\.tmp$/),
686-
'/test/file.js'
687-
);
688727
});
689728

690729
it('handles CRLF line endings in file content', async () => {
691730
mockFs.readFile.mockResolvedValue('line1\r\nline2\r\nline3\r\n');
692-
731+
693732
const edits = [
694733
{ oldText: 'line2', newText: 'modified line2' }
695734
];
696-
697-
mockFs.rename.mockResolvedValueOnce(undefined);
698-
735+
699736
await applyFileEdits('/test/file.txt', edits, false);
700-
701-
expect(mockFs.writeFile).toHaveBeenCalledWith(
702-
expect.stringMatching(/\/test\/file\.txt\.[a-f0-9]+\.tmp$/),
737+
738+
expect(mockFileHandle.write).toHaveBeenCalledWith(
703739
'line1\nmodified line2\nline3\n',
740+
0,
704741
'utf-8'
705742
);
706-
expect(mockFs.rename).toHaveBeenCalledWith(
707-
expect.stringMatching(/\/test\/file\.txt\.[a-f0-9]+\.tmp$/),
708-
'/test/file.txt'
709-
);
710743
});
711744
});
712745

0 commit comments

Comments
 (0)