Skip to content

Commit 3901239

Browse files
fix(utils): fail closed when the staged file's mode copy fails
_copyTargetMode logged a failed chmod and let the publish proceed at the staged file's own mode, so a 0o600 credential file could be published widened. The mode copy runs before the commit rename, so this failure is the reversible one: nothing is published yet, the teardown unlinks the staged file and the target keeps its previous content. The sibling writer in services/file-safety/safeWriteText.ts already rethrows for the same property, and its comment explains why the mode has to be applied rather than inherited. The doc block no longer defends proceeding on atomicity grounds - the rename makes the publish atomic whatever the mode is - and the row that pinned the old behaviour now asserts the teardown instead: the target still holds its previous content and no .new_ staged file is left beside it. Refs: Zoo-Code-Org#2359 (discussion_r4509387063)
1 parent 2c3f744 commit 3901239

2 files changed

Lines changed: 41 additions & 13 deletions

File tree

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

Lines changed: 21 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1071,12 +1071,15 @@ describe("safeWriteJson", () => {
10711071
expect(await readFileContent(currentTestFilePath)).toEqual({ after: true })
10721072
},
10731073
)
1074-
// The two failure paths of _copyTargetMode: a target whose mode cannot be read, and a staged
1075-
// file whose mode cannot be set. Both have to log and let the write finish, because the
1076-
// replacement protocol - not the mode - is what makes the publish atomic. They are driven
1077-
// through the fs/promises mocks rather than a real EACCES/EPERM, because forcing either one
1078-
// for real needs privileges a developer box and a CI runner neither have. That is also why
1079-
// these two run on every platform while the symlink and mode rows above skip windows.
1074+
// The two failure paths of _copyTargetMode are not one decision, and the two rows below are
1075+
// not interchangeable. A target whose mode cannot be read is not evidence about that target's
1076+
// confidentiality, so the writer logs and publishes on the staged file's own mode. A staged
1077+
// file whose mode cannot be set is a publish that would land the wrong mode on a file the
1078+
// caller had restricted, so it aborts before the commit rename and the row asserts the whole
1079+
// teardown: the target keeps its previous content and no staged file is left beside it. Both
1080+
// are driven through the fs/promises mocks rather than a real EACCES/EPERM, because forcing
1081+
// either one for real needs privileges a developer box and a CI runner neither have. That is
1082+
// also why these two run on every platform while the symlink and mode rows above skip windows.
10801083
test("logs and still publishes when the target's mode cannot be read", async () => {
10811084
await fsPromisesActuals.writeFile!(currentTestFilePath, JSON.stringify({ before: true }))
10821085
const consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => {})
@@ -1108,7 +1111,7 @@ describe("safeWriteJson", () => {
11081111
consoleErrorSpy.mockRestore()
11091112
}, 20_000)
11101113

1111-
test("logs and still publishes when the staged file's mode cannot be set", async () => {
1114+
test("aborts before the publish when the staged file's mode cannot be set", async () => {
11121115
await fsPromisesActuals.writeFile!(currentTestFilePath, JSON.stringify({ before: true }))
11131116
const consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => {})
11141117
// chmod is a vi.fn() in the factory above for the same reason.
@@ -1120,9 +1123,18 @@ describe("safeWriteJson", () => {
11201123
throw error
11211124
})
11221125

1123-
await safeWriteJson(currentTestFilePath, { after: true })
1126+
await expect(safeWriteJson(currentTestFilePath, { after: true })).rejects.toThrow("EPERM")
11241127

1125-
expect(await readFileContent(currentTestFilePath)).toEqual({ after: true })
1128+
// The abort is only worth having if it leaves nothing behind. The target still holds
1129+
// the content it had before the write, and the staged file - which carries the new
1130+
// bytes at the umask-derived mode - is gone rather than sitting beside it. The mode
1131+
// copy runs before the commit rename, so this is a teardown and not a rollback: the
1132+
// target was never replaced.
1133+
expect(await readFileContent(currentTestFilePath)).toEqual({ before: true })
1134+
const stagedLeftovers = (await fs.readdir(path.dirname(currentTestFilePath))).filter((entry) =>
1135+
entry.startsWith(`.${path.basename(currentTestFilePath)}.new_`),
1136+
)
1137+
expect(stagedLeftovers).toEqual([])
11261138
expect(consoleErrorSpy).toHaveBeenCalledWith(expect.stringContaining("Failed to copy mode"), expect.anything())
11271139
consoleErrorSpy.mockRestore()
11281140
}, 20_000)

‎src/utils/safeWriteJson.ts‎

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -574,10 +574,21 @@ async function _streamDataToFile(targetPath: string, data: unknown, prettyPrint
574574

575575
/**
576576
* Copies the existing target's permission mode onto the staged file so the publish
577-
* does not silently widen it. A missing target has no mode to copy; a stat or chmod
578-
* that fails for another reason is logged and the write proceeds with the staged
579-
* file's own mode, because the replacement protocol - not the mode - is what makes the
580-
* write atomic.
577+
* does not silently widen it. Two of the three outcomes below are deliberately not
578+
* fatal and one is, and the difference is what each failure leaves behind, not how
579+
* atomic the publish is: the commit rename makes the publish atomic whatever the mode
580+
* ends up being, so atomicity is not a property a mode copy can supply or withhold.
581+
* A missing target has no mode to copy, and a mode that cannot be read says nothing
582+
* about the target's confidentiality - both proceed on the staged file's own mode and
583+
* say so in the log. A mode that was read and could not be set aborts the write,
584+
* because this step runs before the commit rename: aborting here publishes nothing,
585+
* the teardown unlinks the staged file and the target still holds its previous
586+
* content, whereas publishing at the staged mode has already made a 0o600 credential
587+
* file readable by anyone who can read the directory, and it stays that way until the
588+
* next write. The sibling writer in services/file-safety/safeWriteText.ts takes the
589+
* same position for the same property: it rethrows a mode it could not read unless the
590+
* target is simply absent, and applies the mode to the descriptor because openSync's
591+
* creation mode is narrowed by the process umask.
581592
*/
582593
async function _copyTargetMode(targetPath: string, stagedPath: string): Promise<void> {
583594
let mode: number
@@ -595,6 +606,11 @@ async function _copyTargetMode(targetPath: string, stagedPath: string): Promise<
595606
await fs.chmod(stagedPath, mode)
596607
} catch (chmodError: unknown) {
597608
console.error(`Failed to copy mode ${mode.toString(8)} from ${targetPath} onto ${stagedPath}:`, chmodError)
609+
// Fail closed. The commit rename is the next step and has not run, so the target
610+
// still holds its previous content and the outer teardown unlinks the staged file;
611+
// publishing instead would land the staged mode on a file that was 0o600 and would
612+
// keep it widened until some later write happened to copy the mode again.
613+
throw chmodError
598614
}
599615
}
600616

0 commit comments

Comments
 (0)