Skip to content

Commit 7bf2654

Browse files
Copy the target's mode onto the staged file so the publish cannot widen it
CWE-732: the commit rename lands the staged file onto the target, so the file that survives carries the staged file's mode. A 0o600 target was being published 0o644 from the umask-derived default, which is the third ubuntu failure at e3d6327 - "preserves a restrictive 0o600 target mode through the atomic publish", AssertionError: expected 420 to be 384 at safeWriteJson.test.ts:1047. The helper is grafted verbatim from the Zoo-Code-Org#1912 head 085fbf8: stat the target, chmod the staged file, log and continue on a stat or chmod failure, nothing to copy for a target that is not there yet. Call site and ordering match 085fbf8 - after the staging write, before the flush - and the call names the same resolved string the staging, the commit rename, the escape re-checks and the rollback rename name, which is the seam rule for this file. That head is not an ancestor of 73931fe (git merge-base --is-ancestor, exit 1), so this does not claim main accepted and dropped it - only that the two resolutions differ on a permission property, which is the leftover recorded on the PR rather than a thing to resolve silently inside one unit. Two variants of this helper now exist on the series, both in src/utils/safeWriteJson.ts and nowhere in src/services/file-safety/safeWriteText.ts: log-and-continue here (impl blob 1e4031a 92f6547955ebca26c9f5, same as 8fa7d85) and at 085fbf8 (blob eebd1ff 30d2bf), and fail-closed at the Zoo-Code-Org#1917 head c4bd9a2 (blob fbe8b07). Whichever merge lands first supplies the canonical text: merge order, not merit. Zoo-Code-Org#2350 plus merge order is the arbiter, and this copy is not being converged onto the fail-closed text. Both failure branches carry rows, because a helper grafted for a permission property with two unexercised error paths is a changed-line coverage hole whatever the mutation gate decides: "logs and still publishes when the target's mode cannot be read" and "logs and still publishes when the staged file's mode cannot be set". They drive fs.stat and fs.chmod through the file's existing fs/promises mock factory (chmod is newly a vi.fn() delegating to the real implementation) rather than a real EACCES/EPERM, which needs privileges neither this box nor a CI runner has, so - unlike the symlink and mode rows above - these two run on every platform. A name-filtered run of this spec selects exactly those two rows and both pass. Gates on this commit's tree, pinned node v22.23.4 (box node 25.9.0): misc exit 0 at 2118 passed / 17 skipped (2135 total, +2 rows); tsc -p src/tsconfig.json exit 0; prettier --check clean; eslint --max-warnings=0 exit 0 on both touched files, run without --prune-suppressions so src/eslint-suppressions.json is untouched; knip --production exit 0 run from the repo root, where knip.json lives. git diff --name-only 8fa7d85 HEAD lists only this spec file, so the implementation is byte-identical to the head whose CI is running and only test rows were added on top of it. The three ubuntu rows themselves remain answered by CI's ubuntu leg, not by this box. Refs: Zoo-Code-Org#1375, Zoo-Code-Org#1991, Zoo-Code-Org#2019.
1 parent 1871993 commit 7bf2654

2 files changed

Lines changed: 77 additions & 0 deletions

File tree

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

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ vi.mock("fs/promises", async () => {
2828
unlink: vi.fn(actual.unlink),
2929
access: vi.fn(actual.access),
3030
stat: vi.fn(actual.stat),
31+
chmod: vi.fn(actual.chmod),
3132
open: vi.fn(actual.open),
3233
mkdtemp: vi.fn(actual.mkdtemp),
3334
rm: vi.fn(actual.rm),
@@ -1048,6 +1049,48 @@ describe("safeWriteJson", () => {
10481049
expect(await readFileContent(currentTestFilePath)).toEqual({ after: true })
10491050
},
10501051
)
1052+
// The two failure paths of _copyTargetMode: a target whose mode cannot be read, and a staged
1053+
// file whose mode cannot be set. Both have to log and let the write finish, because the
1054+
// replacement protocol - not the mode - is what makes the publish atomic. They are driven
1055+
// through the fs/promises mocks rather than a real EACCES/EPERM, because forcing either one
1056+
// for real needs privileges a developer box and a CI runner neither have. That is also why
1057+
// these two run on every platform while the symlink and mode rows above skip windows.
1058+
test("logs and still publishes when the target's mode cannot be read", async () => {
1059+
await fsPromisesActuals.writeFile!(currentTestFilePath, JSON.stringify({ before: true }))
1060+
const consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => {})
1061+
// fs.stat is already vi.fn() in the factory above - vi.mocked keeps the real
1062+
// implementation reachable once this single call is done.
1063+
await vi.mocked(fs.stat).mockImplementationOnce(async () => {
1064+
const error: NodeJS.ErrnoException = new Error(`EACCES: permission denied, stat '${currentTestFilePath}'`)
1065+
error.code = "EACCES"
1066+
throw error
1067+
})
1068+
1069+
await safeWriteJson(currentTestFilePath, { after: true })
1070+
1071+
expect(await readFileContent(currentTestFilePath)).toEqual({ after: true })
1072+
expect(consoleErrorSpy).toHaveBeenCalledWith(expect.stringContaining(currentTestFilePath), expect.anything())
1073+
consoleErrorSpy.mockRestore()
1074+
}, 20_000)
1075+
1076+
test("logs and still publishes when the staged file's mode cannot be set", async () => {
1077+
await fsPromisesActuals.writeFile!(currentTestFilePath, JSON.stringify({ before: true }))
1078+
const consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => {})
1079+
// chmod is a vi.fn() in the factory above for the same reason.
1080+
await vi.mocked(fs.chmod).mockImplementationOnce(async () => {
1081+
const error: NodeJS.ErrnoException = new Error(
1082+
`EPERM: operation not permitted, chmod '${currentTestFilePath}'`,
1083+
)
1084+
error.code = "EPERM"
1085+
throw error
1086+
})
1087+
1088+
await safeWriteJson(currentTestFilePath, { after: true })
1089+
1090+
expect(await readFileContent(currentTestFilePath)).toEqual({ after: true })
1091+
expect(consoleErrorSpy).toHaveBeenCalledWith(expect.stringContaining("Failed to copy mode"), expect.anything())
1092+
consoleErrorSpy.mockRestore()
1093+
}, 20_000)
10511094

10521095
// Ordering matters for the security guarantee: proper-lockfile creates
10531096
// ${lockKey}.lock beside the lock key, and the key is the symlink referent. If

‎src/utils/safeWriteJson.ts‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -394,6 +394,14 @@ async function safeWriteJson(filePath: string, data: unknown, options?: SafeWrit
394394
stagedBytes = await fs.readFile(actualTempNewFilePath)
395395
}
396396

397+
// CWE-732: the commit rename below lands the staged file onto the target, so the
398+
// file that survives carries the staged file's mode, not the target's. A 0o600
399+
// target would otherwise be published 0o644 from the umask-derived default. The
400+
// #1912 head (085fbf85e) carries this step for the same function; the blob main
401+
// brought in does not, and without it the two resolutions differ on a permission
402+
// property and the row that pins it can only pass on one platform.
403+
await _copyTargetMode(resolvedTargetPath, actualTempNewFilePath)
404+
397405
await _flushFileToDisk(actualTempNewFilePath)
398406

399407
// Step 2: Commit the replacement with a single atomic rename. The
@@ -570,6 +578,32 @@ async function _streamDataToFile(targetPath: string, data: unknown, prettyPrint
570578
})
571579
}
572580

581+
/**
582+
* Copies the existing target's permission mode onto the staged file so the publish
583+
* does not silently widen it. A missing target has no mode to copy; a stat or chmod
584+
* that fails for another reason is logged and the write proceeds with the staged
585+
* file's own mode, because the replacement protocol - not the mode - is what makes the
586+
* write atomic.
587+
*/
588+
async function _copyTargetMode(targetPath: string, stagedPath: string): Promise<void> {
589+
let mode: number
590+
try {
591+
const stats = await fs.stat(targetPath)
592+
mode = stats.mode & 0o777
593+
} catch (statError: unknown) {
594+
const code = getErrorCode(statError)
595+
if (code && code !== "ENOENT" && code !== "ENOTDIR") {
596+
console.error(`Could not read the mode of ${targetPath} before publishing onto it:`, statError)
597+
}
598+
return
599+
}
600+
try {
601+
await fs.chmod(stagedPath, mode)
602+
} catch (chmodError: unknown) {
603+
console.error(`Failed to copy mode ${mode.toString(8)} from ${targetPath} onto ${stagedPath}:`, chmodError)
604+
}
605+
}
606+
573607
/**
574608
* Syncs the directory that holds a freshly committed file.
575609
* Best effort: durability against power loss is a bonus here, process-crash

0 commit comments

Comments
 (0)