Skip to content

Commit 926d4b6

Browse files
committed
fix(filesystem): harden file replacement with EPERM fallback
Extract replaceFileFromTemp helper that falls back to fs.cp when fs.rename fails with EPERM (Windows locked files). Temp file cleanup is best-effort so a successful write is never masked by a cleanup failure (e.g. antivirus holding the temp file). Changes: - Extract replaceFileFromTemp from inline rename logic in writeFileContent and applyFileEdits - Add EPERM fallback: rename -> cp + best-effort unlink - Document FILE_SHARE_DELETE limitation and non-atomic fallback in JSDoc - Add tests for EPERM fallback through both writeFileContent and applyFileEdits - Add tests for successful writes despite temp cleanup failure Fixes modelcontextprotocol#3430
1 parent b60eca1 commit 926d4b6

2 files changed

Lines changed: 155 additions & 18 deletions

File tree

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

Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -308,6 +308,61 @@ describe('Lib Functions', () => {
308308

309309
expect(mockFs.writeFile).toHaveBeenCalledWith('/test/file.txt', 'new content', { encoding: "utf-8", flag: 'wx' });
310310
});
311+
312+
it('falls back to fs.cp when fs.rename fails with EPERM', async () => {
313+
const eexistError = new Error('EEXIST') as NodeJS.ErrnoException;
314+
eexistError.code = 'EEXIST';
315+
const epermError = new Error('EPERM') as NodeJS.ErrnoException;
316+
epermError.code = 'EPERM';
317+
318+
mockFs.writeFile
319+
.mockRejectedValueOnce(eexistError) // First write fails (file exists)
320+
.mockResolvedValueOnce(undefined); // Temp file write succeeds
321+
mockFs.rename.mockRejectedValueOnce(epermError); // Rename fails (locked)
322+
mockFs.cp.mockResolvedValueOnce(undefined); // cp succeeds
323+
mockFs.unlink.mockResolvedValueOnce(undefined); // Temp cleanup succeeds
324+
325+
await writeFileContent('/test/file.txt', 'new content');
326+
327+
expect(mockFs.rename).toHaveBeenCalledWith(
328+
expect.stringMatching(/\/test\/file\.txt\.[a-f0-9]+\.tmp$/),
329+
'/test/file.txt'
330+
);
331+
expect(mockFs.cp).toHaveBeenCalledWith(
332+
expect.stringMatching(/\/test\/file\.txt\.[a-f0-9]+\.tmp$/),
333+
'/test/file.txt',
334+
{ force: true }
335+
);
336+
expect(mockFs.unlink).toHaveBeenCalledWith(
337+
expect.stringMatching(/\/test\/file\.txt\.[a-f0-9]+\.tmp$/)
338+
);
339+
});
340+
341+
it('succeeds when fs.cp works but temp file unlink fails', async () => {
342+
const eexistError = new Error('EEXIST') as NodeJS.ErrnoException;
343+
eexistError.code = 'EEXIST';
344+
const epermError = new Error('EPERM') as NodeJS.ErrnoException;
345+
epermError.code = 'EPERM';
346+
const ebusyError = new Error('EBUSY') as NodeJS.ErrnoException;
347+
ebusyError.code = 'EBUSY';
348+
349+
mockFs.writeFile
350+
.mockRejectedValueOnce(eexistError)
351+
.mockResolvedValueOnce(undefined);
352+
mockFs.rename.mockRejectedValueOnce(epermError);
353+
mockFs.cp.mockResolvedValueOnce(undefined);
354+
mockFs.unlink.mockRejectedValueOnce(ebusyError); // Temp cleanup fails (e.g. antivirus)
355+
356+
// Should NOT throw — the target file was written successfully
357+
await expect(writeFileContent('/test/file.txt', 'new content'))
358+
.resolves.toBeUndefined();
359+
360+
expect(mockFs.cp).toHaveBeenCalledWith(
361+
expect.stringMatching(/\/test\/file\.txt\.[a-f0-9]+\.tmp$/),
362+
'/test/file.txt',
363+
{ force: true }
364+
);
365+
});
311366
});
312367

313368
});
@@ -553,6 +608,61 @@ describe('Lib Functions', () => {
553608
);
554609
});
555610

611+
it('falls back to fs.cp when fs.rename fails with EPERM during file edit', async () => {
612+
const epermError = new Error('EPERM') as NodeJS.ErrnoException;
613+
epermError.code = 'EPERM';
614+
615+
mockFs.readFile.mockResolvedValue('line1\nline2\nline3\n');
616+
mockFs.writeFile.mockResolvedValue(undefined);
617+
mockFs.rename.mockRejectedValueOnce(epermError);
618+
mockFs.cp.mockResolvedValueOnce(undefined);
619+
mockFs.unlink.mockResolvedValueOnce(undefined);
620+
621+
const edits = [{ oldText: 'line2', newText: 'modified line2' }];
622+
const result = await applyFileEdits('/test/file.txt', edits, false);
623+
624+
// Should have tried rename first, then fallen back to cp + unlink
625+
expect(mockFs.rename).toHaveBeenCalledWith(
626+
expect.stringMatching(/\/test\/file\.txt\.[a-f0-9]+\.tmp$/),
627+
'/test/file.txt'
628+
);
629+
expect(mockFs.cp).toHaveBeenCalledWith(
630+
expect.stringMatching(/\/test\/file\.txt\.[a-f0-9]+\.tmp$/),
631+
'/test/file.txt',
632+
{ force: true }
633+
);
634+
expect(mockFs.unlink).toHaveBeenCalledWith(
635+
expect.stringMatching(/\/test\/file\.txt\.[a-f0-9]+\.tmp$/)
636+
);
637+
// Edit should still produce a valid diff
638+
expect(result).toContain('modified line2');
639+
});
640+
641+
it('succeeds when fs.cp works but temp file unlink fails during file edit', async () => {
642+
const epermError = new Error('EPERM') as NodeJS.ErrnoException;
643+
epermError.code = 'EPERM';
644+
const ebusyError = new Error('EBUSY') as NodeJS.ErrnoException;
645+
ebusyError.code = 'EBUSY';
646+
647+
mockFs.readFile.mockResolvedValue('line1\nline2\nline3\n');
648+
mockFs.writeFile.mockResolvedValue(undefined);
649+
mockFs.rename.mockRejectedValueOnce(epermError);
650+
mockFs.cp.mockResolvedValueOnce(undefined);
651+
mockFs.unlink.mockRejectedValueOnce(ebusyError); // Temp cleanup fails
652+
653+
const edits = [{ oldText: 'line2', newText: 'modified line2' }];
654+
655+
// Should NOT throw — the target file was written successfully
656+
const result = await applyFileEdits('/test/file.txt', edits, false);
657+
658+
expect(result).toContain('modified line2');
659+
expect(mockFs.cp).toHaveBeenCalledWith(
660+
expect.stringMatching(/\/test\/file\.txt\.[a-f0-9]+\.tmp$/),
661+
'/test/file.txt',
662+
{ force: true }
663+
);
664+
});
665+
556666
it('handles CRLF line endings in file content', async () => {
557667
mockFs.readFile.mockResolvedValue('line1\r\nline2\r\nline3\r\n');
558668

‎src/filesystem/lib.ts‎

Lines changed: 45 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,47 @@ export async function validatePath(requestedPath: string): Promise<string> {
140140
}
141141

142142

143+
/**
144+
* Replace a target file with the contents of a temporary file.
145+
*
146+
* Uses `fs.rename` for an atomic swap when possible. On Windows, rename can
147+
* fail with `EPERM` when the target is held open by another process (e.g.
148+
* VS Code) *provided* that process opened the file with `FILE_SHARE_DELETE`.
149+
* In that case the function falls back to `fs.cp` + best-effort `fs.unlink`.
150+
*
151+
* **Limitations:**
152+
* - The `fs.cp` fallback is *not* atomic — there is a brief window between
153+
* the internal `unlink(dest)` and `copyFile(src, dest)` performed by
154+
* `fs.cp({ force: true })`.
155+
* - The fallback only succeeds when the locking process uses
156+
* `FILE_SHARE_DELETE`. Editors that lock without this flag will still
157+
* produce an `EPERM` error.
158+
*
159+
* @param tempPath Path to the temporary file that contains the new content.
160+
* @param targetPath Path to the destination file to be replaced.
161+
*/
162+
async function replaceFileFromTemp(tempPath: string, targetPath: string): Promise<void> {
163+
try {
164+
await fs.rename(tempPath, targetPath);
165+
} catch (renameError) {
166+
if ((renameError as NodeJS.ErrnoException).code === 'EPERM') {
167+
// Fallback: copy then best-effort cleanup
168+
await fs.cp(tempPath, targetPath, { force: true });
169+
try {
170+
await fs.unlink(tempPath);
171+
} catch {
172+
// Best-effort cleanup; target was already written successfully
173+
}
174+
} else {
175+
// For non-EPERM errors, clean up the temp file and re-throw
176+
try {
177+
await fs.unlink(tempPath);
178+
} catch {}
179+
throw renameError;
180+
}
181+
}
182+
}
183+
143184
// File Operations
144185
export async function getFileStats(filePath: string): Promise<FileInfo> {
145186
const stats = await fs.stat(filePath);
@@ -169,15 +210,8 @@ export async function writeFileContent(filePath: string, content: string): Promi
169210
// could be created between validation and write. Rename operations
170211
// replace the target file atomically and don't follow symlinks.
171212
const tempPath = `${filePath}.${randomBytes(16).toString('hex')}.tmp`;
172-
try {
173-
await fs.writeFile(tempPath, content, 'utf-8');
174-
await fs.rename(tempPath, filePath);
175-
} catch (renameError) {
176-
try {
177-
await fs.unlink(tempPath);
178-
} catch {}
179-
throw renameError;
180-
}
213+
await fs.writeFile(tempPath, content, 'utf-8');
214+
await replaceFileFromTemp(tempPath, filePath);
181215
} else {
182216
throw error;
183217
}
@@ -267,15 +301,8 @@ export async function applyFileEdits(
267301
// could be created between validation and write. Rename operations
268302
// replace the target file atomically and don't follow symlinks.
269303
const tempPath = `${filePath}.${randomBytes(16).toString('hex')}.tmp`;
270-
try {
271-
await fs.writeFile(tempPath, modifiedContent, 'utf-8');
272-
await fs.rename(tempPath, filePath);
273-
} catch (error) {
274-
try {
275-
await fs.unlink(tempPath);
276-
} catch {}
277-
throw error;
278-
}
304+
await fs.writeFile(tempPath, modifiedContent, 'utf-8');
305+
await replaceFileFromTemp(tempPath, filePath);
279306
}
280307

281308
return formattedDiff;

0 commit comments

Comments
 (0)