Skip to content

Commit 647964e

Browse files
cliffhallclaude
andcommitted
fix(filesystem): create the copy owner-only, and keep the source unless the copy is in place
Review round 1 on #5322: - the copy is created 0600 and takes the source's mode only once it is complete (openInDirectory gains an optional creation mode, default unchanged), so a private file is never readable at the destination - before removing the source, the copy must still be at the destination (anchored lstat identity); if it was removed or replaced, the source stays and the move fails - a failure closing the source after a complete copy now removes the copy too, so a retry is not blocked by a leftover destination Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: cliffhall <[email protected]>
1 parent 271f2ef commit 647964e

2 files changed

Lines changed: 140 additions & 8 deletions

File tree

‎src/filesystem/__tests__/pinned-directory.test.ts‎

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -435,6 +435,100 @@ describe("moveFileAcrossDevices", () => {
435435
},
436436
);
437437

438+
it.skipIf(process.platform === "win32")(
439+
"creates the copy owner-only while it is being written",
440+
async () => {
441+
const source = path.join(dir, "a.txt");
442+
const destination = path.join(outside, "b.txt");
443+
fs.writeFileSync(source, "a");
444+
fs.chmodSync(source, 0o644);
445+
const modes: number[] = [];
446+
const realWriteFile = fs.writeFile;
447+
vi.spyOn(fs, "writeFile").mockImplementationOnce(((
448+
...args: unknown[]
449+
) => {
450+
modes.push(fs.statSync(destination).mode & 0o777);
451+
return (realWriteFile as (...a: unknown[]) => void)(...args);
452+
}) as typeof fs.writeFile);
453+
await moveFileAcrossDevices(source, destination);
454+
expect(modes).toEqual([0o600]);
455+
expect(fs.statSync(destination).mode & 0o777).toBe(0o644);
456+
},
457+
);
458+
459+
it.each([
460+
["removed", (destination: string) => fs.unlinkSync(destination)],
461+
[
462+
"replaced",
463+
(destination: string) => {
464+
fs.unlinkSync(destination);
465+
fs.writeFileSync(destination, "someone else's");
466+
},
467+
],
468+
])(
469+
"keeps the source when the copy was %s during the move",
470+
async (_, interfere) => {
471+
const source = path.join(dir, "a.txt");
472+
const destination = path.join(outside, "b.txt");
473+
fs.writeFileSync(source, "a");
474+
const realFchmod = fs.fchmod;
475+
vi.spyOn(fs, "fchmod").mockImplementationOnce(((
476+
fd: number,
477+
mode: number,
478+
callback: (error: NodeJS.ErrnoException | null) => void,
479+
) => {
480+
interfere(destination);
481+
realFchmod(fd, mode, callback);
482+
}) as typeof fs.fchmod);
483+
await expect(moveFileAcrossDevices(source, destination)).rejects.toThrow(
484+
`Refusing to remove the source: ${destination} was removed or replaced during the move`,
485+
);
486+
expect(fs.readFileSync(source, "utf-8")).toBe("a");
487+
},
488+
);
489+
490+
it("reports a failure to check the copy, and keeps the source", async () => {
491+
const source = path.join(dir, "a.txt");
492+
const destination = path.join(outside, "b.txt");
493+
fs.writeFileSync(source, "a");
494+
const realLstat = fs.lstatSync;
495+
// The first lstat of the copy is the create's own check; fail the second.
496+
let checks = 0;
497+
vi.spyOn(fs, "lstatSync").mockImplementation(((p: fs.PathLike) => {
498+
if (process.cwd() === outside && p === "b.txt" && ++checks === 2) {
499+
throw errno("EIO");
500+
}
501+
return realLstat(p);
502+
}) as typeof fs.lstatSync);
503+
await expect(moveFileAcrossDevices(source, destination)).rejects.toThrow(
504+
"EIO",
505+
);
506+
// The third is discarding the copy, which goes ahead.
507+
expect(checks).toBe(3);
508+
expect(fs.readdirSync(outside)).toEqual([]);
509+
expect(fs.readFileSync(source, "utf-8")).toBe("a");
510+
});
511+
512+
it("removes the copy, and keeps the source, when closing the source fails", async () => {
513+
const source = path.join(dir, "a.txt");
514+
fs.writeFileSync(source, "a");
515+
const realClose = fs.close;
516+
let closes = 0;
517+
vi.spyOn(fs, "close").mockImplementation(((
518+
fd: number,
519+
callback: (error: NodeJS.ErrnoException | null) => void,
520+
) => {
521+
// The copy's descriptor closes first, then the source's.
522+
closes += 1;
523+
realClose(fd, (error) => callback(closes === 2 ? errno("EIO") : error));
524+
}) as typeof fs.close);
525+
await expect(
526+
moveFileAcrossDevices(source, path.join(outside, "b.txt")),
527+
).rejects.toThrow("EIO");
528+
expect(fs.readdirSync(outside)).toEqual([]);
529+
expect(fs.readFileSync(source, "utf-8")).toBe("a");
530+
});
531+
438532
it("reports the copy's failure when removing the copy fails too", async () => {
439533
const source = path.join(dir, "a.txt");
440534
fs.writeFileSync(source, "a");

‎src/filesystem/pinned-directory.ts‎

Lines changed: 46 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -180,13 +180,14 @@ function openInDirectory(
180180
filePath: string,
181181
flags: number,
182182
refuseLink: boolean,
183+
mode: number = 0o666,
183184
): { fd: number; opened: fs.Stats } {
184185
const name = path.basename(filePath);
185186
return inDirectory(path.dirname(filePath), () => {
186187
if (refuseLink && fs.lstatSync(name).isSymbolicLink()) {
187188
throw new Error(`Refusing to write: not a regular file: ${filePath}`);
188189
}
189-
const fd = fs.openSync(name, flags, 0o666);
190+
const fd = fs.openSync(name, flags, mode);
190191
try {
191192
const opened = fs.fstatSync(fd);
192193
if (!isSameEntry(fs.lstatSync(name), opened)) {
@@ -343,6 +344,31 @@ function openSourceInDirectory(sourcePath: string): {
343344
});
344345
}
345346

347+
/**
348+
* Check that `filePath`, relative to its anchored directory, is still the
349+
* entry `expected` describes, and fail with `message` if it is not.
350+
*/
351+
function confirmInDirectory(
352+
filePath: string,
353+
expected: { dev: number; ino: number },
354+
message: string,
355+
): void {
356+
const name = path.basename(filePath);
357+
inDirectory(path.dirname(filePath), () => {
358+
let found: fs.Stats | undefined;
359+
try {
360+
found = fs.lstatSync(name);
361+
} catch (error) {
362+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
363+
throw error;
364+
}
365+
}
366+
if (!found || !isSameEntry(found, expected)) {
367+
throw new Error(message);
368+
}
369+
});
370+
}
371+
346372
/**
347373
* Remove `filePath`, relative to its anchored directory, only while it is
348374
* still the entry `expected` describes.
@@ -391,6 +417,9 @@ async function copyIntoNewFile(
391417
fs.constants.O_EXCL |
392418
noFollow(),
393419
false,
420+
// Owner-only until the copy is complete and takes the source's mode, so
421+
// a private file is never readable at the destination in between.
422+
0o600,
394423
);
395424
try {
396425
try {
@@ -424,16 +453,25 @@ export async function moveFileAcrossDevices(
424453
destinationPath: string,
425454
): Promise<void> {
426455
const { fd, opened: source } = openSourceInDirectory(sourcePath);
427-
let created: fs.Stats;
428-
try {
429-
created = await copyIntoNewFile(fd, source, destinationPath);
430-
} finally {
431-
await close(fd);
432-
}
456+
// Set once the copy is complete; until then copyIntoNewFile cleans up.
457+
let created: fs.Stats | undefined;
433458
try {
459+
try {
460+
created = await copyIntoNewFile(fd, source, destinationPath);
461+
} finally {
462+
await close(fd);
463+
}
464+
// The source goes only while the copy is still where the move put it.
465+
confirmInDirectory(
466+
destinationPath,
467+
created,
468+
`Refusing to remove the source: ${destinationPath} was removed or replaced during the move`,
469+
);
434470
removeFromDirectory(sourcePath, source);
435471
} catch (error) {
436-
discardCopy(destinationPath, created);
472+
if (created) {
473+
discardCopy(destinationPath, created);
474+
}
437475
throw error;
438476
}
439477
}

0 commit comments

Comments
 (0)