Skip to content

Commit 8ed2f4c

Browse files
fix(persistence): keep the teardown when the failure-path confinement check cannot run
The confinement re-check inside the catch block of safeWriteJson re-resolved the publish target and the scope root outside the try, so a realpath failure there bypassed the backup rollback and the staged cleanup and replaced the failure the caller was told about. The two resolutions now sit inside the guard, an escape is undone and reported as before, and a scope that cannot be canonicalized is reported and lets the rollback and cleanup below run. The row that fails without it: src/utils/__tests__/safeWriteJson.test.ts, restores the committed file and drops the staged file when the failure-path confinement check cannot run. Requested-by: #2357
1 parent d7baa2c commit 8ed2f4c

2 files changed

Lines changed: 86 additions & 5 deletions

File tree

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

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1316,6 +1316,71 @@ describe("safeWriteJson", () => {
13161316
await undoEscapedPublish(path.join(outside, "absent.json"), undefined)
13171317
})
13181318

1319+
// The confinement re-check inside the failure path at lines 481 to 490 of safeWriteJson.ts runs
1320+
// while the write is already failing, and the review says a rejection there must not decide
1321+
// what the teardown does: the backup rollback at lines 496 to 511 and the staged cleanup at
1322+
// lines 514 to 529 are what keep the committed copy and the staged bytes from being left
1323+
// behind. This row drives the same EPERM fallback the row at line 192 drives, so a backup
1324+
// exists and the canonical path is absent when the catch block runs, and it breaks fs.realpath
1325+
// only from the moment that backup rename lands, which is the state the catch block then reads.
1326+
test("restores the committed file and drops the staged file when the failure-path confinement check cannot run", async () => {
1327+
const initialData = { message: "Initial content, must survive a broken teardown check" }
1328+
const newData = { message: "New content" }
1329+
await fsPromisesActuals.writeFile!(currentTestFilePath, JSON.stringify(initialData))
1330+
1331+
const consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => {})
1332+
let teardownCheckBroken = false
1333+
const realpathSpy = vi.spyOn(fs, "realpath").mockImplementation(async (target) => {
1334+
if (teardownCheckBroken) {
1335+
throw Object.assign(new Error("EPERM: operation not permitted, realpath"), { code: "EPERM" })
1336+
}
1337+
return String(target)
1338+
})
1339+
let renameCallCount = 0
1340+
vi.mocked(fs.rename).mockImplementation(async (oldPath, newPath) => {
1341+
renameCallCount++
1342+
if (renameCallCount === 1) {
1343+
// The single-rename commit fails with EPERM, which starts the two-step fallback.
1344+
throw Object.assign(new Error("EPERM: operation not permitted"), { code: "EPERM" })
1345+
}
1346+
if (renameCallCount === 2) {
1347+
// The backup lands here. From this point the failing write is what the catch block
1348+
// sees, and the confinement re-check inside it is the thing under test.
1349+
teardownCheckBroken = true
1350+
return fsPromisesActuals.rename!(oldPath, newPath)
1351+
}
1352+
if (renameCallCount === 3) {
1353+
throw new Error("Fallback replacement rename failed")
1354+
}
1355+
// The rollback rename, which is what this row is about.
1356+
return fsPromisesActuals.rename!(oldPath, newPath)
1357+
})
1358+
1359+
try {
1360+
// The write rejects with the failure that started the teardown, not with the realpath
1361+
// rejection of a scope root that could not be canonicalized.
1362+
await expect(safeWriteJson(currentTestFilePath, newData, { confineTo: tempDir })).rejects.toThrow(
1363+
"Fallback replacement rename failed",
1364+
)
1365+
// The rollback ran: the committed copy is back at the canonical path.
1366+
expect(await fileExists(currentTestFilePath)).toBe(true)
1367+
expect(await readFileContent(currentTestFilePath)).toEqual(initialData)
1368+
// Neither a backup nor a staged file outlives the failed write.
1369+
const leftovers = (await fs.readdir(tempDir)).filter(
1370+
(entry) => entry.includes(".bak_") || entry.includes(".new_"),
1371+
)
1372+
expect(leftovers).toEqual([])
1373+
// A re-check that could not run is reported rather than silently skipped.
1374+
expect(consoleErrorSpy).toHaveBeenCalledWith(
1375+
expect.stringContaining("could not run during the teardown"),
1376+
expect.objectContaining({ code: "EPERM" }),
1377+
)
1378+
} finally {
1379+
realpathSpy.mockRestore()
1380+
consoleErrorSpy.mockRestore()
1381+
}
1382+
})
1383+
13191384
// Line 343 is the recovery call, and this pull changed its argument from the caller's
13201385
// spelling to the resolved publish target. The two spellings only differ when the
13211386
// orphaned replacement files sit beside the referent rather than beside the alias, which

‎src/utils/safeWriteJson.ts‎

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -479,13 +479,29 @@ async function safeWriteJson(filePath: string, data: unknown, options?: SafeWrit
479479
// peer's file at the same name - including a backup this rollback just restored -
480480
// is left alone. Errors that are not an escape keep their own type.
481481
if (confinementRoot !== undefined && resolvedTargetPath !== undefined) {
482-
const publishedPath = await _resolveScopeRoot(resolvedTargetPath)
483-
const scopeRoot = await _resolveScopeRoot(confinementRoot)
482+
// This re-check runs while the write is already failing, so it must not decide what the
483+
// teardown does. Both locals stay undefined until their resolution lands, which is what
484+
// separates a scope that cannot be canonicalized from a target that escaped the scope.
485+
let publishedPath: string | undefined
486+
let scopeRoot: string | undefined
484487
try {
488+
publishedPath = await _resolveScopeRoot(resolvedTargetPath)
489+
scopeRoot = await _resolveScopeRoot(confinementRoot)
485490
_assertWithinScope(absoluteFilePath, publishedPath, scopeRoot)
486-
} catch (escapeError) {
487-
await undoEscapedPublish(publishedPath, stagedBytes)
488-
throw escapeError
491+
} catch (checkError) {
492+
if (publishedPath !== undefined && scopeRoot !== undefined) {
493+
// The check ran and said escape: undo exactly this write's bytes and report the
494+
// escape, as before.
495+
await undoEscapedPublish(publishedPath, stagedBytes)
496+
throw checkError
497+
}
498+
// The scope could not be canonicalized at all. Report it and keep going, so the
499+
// rollback and the staged cleanup below still run and the failure the caller sees
500+
// stays the one this catch block was entered with.
501+
console.error(
502+
`Confinement re-check for ${absoluteFilePath} could not run during the teardown:`,
503+
checkError,
504+
)
489505
}
490506
}
491507

0 commit comments

Comments
 (0)