Skip to content

Commit 90bbdad

Browse files
fix(utils): keep the pre-commit ancestry assertion out of the EPERM rename fallback
assertAncestryUnchangedBeforeCommit() ran inside the try whose catch decides the fallback by error code alone, so an EPERM raised by the inspection was indistinguishable from a rename collision: the fallback renamed the committed destination to a backup and continued, while the refusal it came from promises that nothing moves. The assertion now runs immediately before the try, so only rename failures reach the fallback. The two-step fallback itself and the crash-recovery pass at the start of the next write are untouched, which is what #1405's seam ruling requires (its safeWriteText copy is one of the four that #2350 has to reconcile, so this file's merge order is on the record). New case arms an EPERM on the third destination look - the one the publication takes just before the commit rename - over a committed destination, and asserts the promise rejects with EPERM, targetLooks === 3, the destination still reads { committed: true } byte for byte, and no backup-rename stage was traced. Control on pinned node v22.23.4 (.tmp-node22; box shell v25.9.0): spec-only against the parent impl gives 1 failed / 61 passed - exactly this case, and the red is the fallback moving the committed file, not a harness artifact; with the assertion moved outside the try the file is 62/62, including the existing two-step-fallback cases, so the fallback and the recovery pass still work. Path-spelling probe (a windows-latest failure mode): async fs.realpath expands an NTFS 8.3 alias, so a publish target can come back spelled differently from the path handed in. Re-ran this spec with TEMP at C:\\work\\ZOO-CO~1\\WT-R20~3\\TMP-AL~1 (same inode as the long name, verified) and at the long name: 62/62 both ways on pinned v22.23.4, so this spec is not spelling-dependent and nothing here compares a resolved path as text. Logs 1405-fixed-at-8.3-alias-r203.log and 1405-row7-case-against-*.log. Gates: vitest.misc.config.ts (the shard src/package.json routes utils/** to) on pinned v22.23.4, tsc --noEmit clean on box v25.9.0, eslint --prune-suppressions --max-warnings=0 clean on both files with .eslintcache cleared after the last prettier write, prettier --check 0, src/eslint-suppressions.json byte-identical to the parent cb6575a. knip skipped: no new file and no new export. Co-Authored-By: Claude <[email protected]>
1 parent 65f8658 commit 90bbdad

2 files changed

Lines changed: 46 additions & 4 deletions

File tree

‎src/utils/__tests__/safeWriteJson.test.ts‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1319,6 +1319,43 @@ describe("safeWriteJson guarded-publish requirements carried by the guarded-writ
13191319
expect(await fileExists(target)).toBe(false)
13201320
})
13211321

1322+
test("does not take the EPERM two-step fallback when the pre-commit ancestry assertion rejects with EPERM", async () => {
1323+
const parent = path.join(tempDir, "ancestry-eperm-parent")
1324+
await fs.mkdir(parent, { recursive: true })
1325+
const target = path.join(parent, "ancestry-eperm.json")
1326+
// A committed destination is what makes the fallback observable: it renames the
1327+
// target to a backup before the second rename, so a mistaken fallback moves a file
1328+
// the inspection had just refused to publish over.
1329+
await fsPromisesActuals.writeFile!(target, JSON.stringify({ committed: true }))
1330+
const asDir = { isSymbolicLink: () => false, dev: 1n, ino: 1n } as unknown as fsSyncActual.BigIntStats
1331+
const asFile = { isSymbolicLink: () => false } as unknown as fsSyncActual.Stats
1332+
const failure = Object.assign(new Error("EPERM: operation not permitted"), { code: "EPERM" })
1333+
// The third destination look is the one the publication takes immediately before
1334+
// the commit rename, so this arms the ancestry assertion, not an earlier check.
1335+
let targetLooks = 0
1336+
vi.spyOn(fs, "lstat").mockImplementation(((p: unknown) => {
1337+
if (String(p) === target) {
1338+
targetLooks++
1339+
if (targetLooks >= 3) return Promise.reject(failure)
1340+
return Promise.resolve(asFile)
1341+
}
1342+
return Promise.resolve(asDir)
1343+
}) as unknown as typeof fs.lstat)
1344+
const trace = vi.fn()
1345+
1346+
await expect(safeWriteJson(target, { fresh: true }, { refuseSymlinkTarget: true, trace })).rejects.toThrow(
1347+
"EPERM",
1348+
)
1349+
1350+
vi.restoreAllMocks()
1351+
// The inspection ran and refused. The committed destination is still there, byte for
1352+
// byte, which is only true if the two-step replacement never started: an EPERM from an
1353+
// inspection is not a rename collision and must not move anything.
1354+
expect(targetLooks).toBe(3)
1355+
expect(await readFileContent(target)).toEqual({ committed: true })
1356+
expect(trace).not.toHaveBeenCalledWith(expect.objectContaining({ stage: "backup-rename" }))
1357+
})
1358+
13221359
test("fails closed when an ancestor vanishes during the authorizing walk", async () => {
13231360
const parent = path.join(tempDir, "vanish-parent")
13241361
await fs.mkdir(parent, { recursive: true })

‎src/utils/safeWriteJson.ts‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -350,11 +350,16 @@ async function safeWriteJson(filePath: string, data: unknown, options?: SafeWrit
350350
// committed target stays in place until this rename lands, so a
351351
// process exit before or during the commit can no longer leave the
352352
// canonical path absent.
353+
if (options?.refuseSymlinkTarget) {
354+
// Re-derive the refusal inside the publication, immediately before the commit rename, but
355+
// outside the rename-fallback try: that handler tests only the error code, so an EPERM
356+
// raised by this inspection would be mistaken for a rename collision and take the
357+
// two-step replacement, moving the committed destination to a backup even though the
358+
// refusal promises that nothing moves. Only rename failures reach the fallback now;
359+
// the fallback and the crash-recovery pass at the start of the next write are unchanged.
360+
await assertAncestryUnchangedBeforeCommit()
361+
}
353362
try {
354-
if (options?.refuseSymlinkTarget) {
355-
// Re-derive the refusal inside the publication, immediately before the commit rename: the authorizing walk and this call are separated by the whole staging sequence, and a path-based rename follows an ancestor swapped for a link during it. A rejection here moves nothing, so the target keeps its content.
356-
await assertAncestryUnchangedBeforeCommit()
357-
}
358363
options?.trace?.({ stage: "replacement-rename" })
359364
await fs.rename(actualTempNewFilePath, absoluteFilePath)
360365
} catch (renameError: unknown) {

0 commit comments

Comments
 (0)