Skip to content

fix(atomic): bind replacement modes to descriptors - #91

Merged
steipete merged 2 commits into
mainfrom
fix/atomic-fchmod
Aug 2, 2026
Merged

steipete merged 2 commits into
mainfrom
fix/atomic-fchmod

Conversation

@steipete

@steipete steipete commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

Fixes #86.

What was wrong

replaceFileAtomic() and replaceFileAtomicSync() reached the caller-requested mode by calling chmod on the destination path, after the rename had already completed. A local user able to write the parent directory could unlink the destination in that window and drop a symlink in its place; chmod followed it and the mode change landed on an unrelated file.

The temp file could not carry the mode on its own, because it was created with writeFile(tempPath, content, { mode, flag: "wx" }) and so had its mode reduced by the process umask. The post-rename chmod was the only thing that reached the exact requested mode, and no option disabled it.

Reported with a complete reproduction by @yetval.

What changed

The exclusive temp descriptor is now held open across write, mode application, optional fsync, and close, before the rename. The copy fallback applies modes through its pinned destination descriptor. No post-publication destination chmod remains anywhere in the replacement path.

The async interface needs no new member: it applies the mode through the FileHandle returned by the already-required open. The synchronous path does add an optional fchmodSync, because openSync returns a bare descriptor with no equivalent method; typeof fs satisfies it, and adapters that pass neither mode nor preserveExistingMode are unaffected. A sync adapter that requests a mode without providing fchmodSync fails before any mutation rather than silently falling back.

Proof

Real syscalls, real on-disk directories, umask 077, with the destination swap staged at the rename boundary. Before, on both entry points, the recorded chmod path list contained the destination and an unrelated 644 file silently became 600. After:

async victim before: 644
async chmod paths: <parent>
async published mode before swap: 600
async victim after: 644
sync victim before: 644
sync chmod paths: <parent>
sync published mode before swap: 600
sync victim after: 644
node:fs injected async mode under umask 077: 666

The unrelated file keeps 644, only the parent directory is chmodded, and the requested mode is still reached exactly despite the umask. The final line covers the compatibility shape that matters most in practice — a plain node:fs injected as fileSystem together with an explicit mode — which is now pinned by a regression test.

pnpm check 651 passed / 25 skipped, pnpm test:security 62 passed, git diff --check clean, Codex autoreview clean. Regressions fail on main and pass here.

Follow-ups, deliberately not in this PR

Two adjacent by-path chmod calls deserve their own review and are untouched here. dirMode is applied via chmod(dir, dirMode) after a recursive mkdir that may return a pre-existing directory, so an attacker controlling the destination's parent could redirect it — a stronger prerequisite than this issue. And movePathWithCopyFallback chmods randomized staging paths before publication; the names are unpredictable but visible to anyone who can list the writable target directory.

@steipete
steipete requested a review from a team as a code owner August 2, 2026 21:09
@clawsweeper clawsweeper Bot added proof: sufficient Contributor real behavior proof is sufficient. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. P1 Urgent regression or broken agent/channel workflow affecting real users now. merge-risk: 🚨 compatibility 🚨 Merging this PR could break existing users, config, migrations, defaults, or upgrades. labels Aug 2, 2026
@clawsweeper

clawsweeper Bot commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 2, 2026, 5:18 PM ET / 21:18 UTC.

ClawSweeper review

What this changes

The branch removes post-rename destination-path mode changes from atomic replacement, applies modes through open descriptors, and documents the conditional fchmodSync requirement for custom synchronous filesystem adapters.

Merge readiness

⚠️ Ready for maintainer review - 2 items remain

Keep this PR open for normal merge review. It is a focused security repair: current main still applies the requested file mode through the published destination pathname after rename, while this branch applies it through the open replacement descriptor before publication and covers the reported swap scenario.

Priority: P1
Reviewed head: cb44a1d8453dffaca4f7845c9df3416386bc1e1b

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) This is a focused, documented security repair with concrete live behavior evidence, targeted regressions, and no discrete correctness finding.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The PR body provides after-fix real-filesystem output for both entry points under umask 077, including the staged swap result, exact published mode, unaffected victim mode, and injected node:fs behavior.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The PR body provides after-fix real-filesystem output for both entry points under umask 077, including the staged swap result, exact published mode, unaffected victim mode, and injected node:fs behavior.
Evidence reviewed 6 items Current-main vulnerable ordering: Current main writes and renames the temp file, then performs best-effort chmod on the caller-supplied destination pathname; the reported swapped-symlink window therefore remains present on main.
Descriptor-bound replacement mode: The proposed helper opens the exclusive temp file, writes content, applies the requested mode through the open handle, optionally syncs it, obtains its identity, and closes it before rename.
Copy-fallback mode remains pinned: The branch applies the source mode through the already-open destination descriptor in both asynchronous and synchronous copy fallback paths, preserving exact modes despite umask without a later pathname chmod.
Findings None None.
Security None None.

How this fits together

The atomic-write subsystem creates a sibling temporary file, optionally synchronizes it, then publishes it by rename or a guarded copy fallback. Its permission handling must remain bound to the intended file rather than resolving the caller-controlled destination path after publication.

flowchart LR
  A[Caller content and mode] --> B[Sibling temporary file]
  B --> C[Write and descriptor-bound mode]
  C --> D{Publish method}
  D --> E[Atomic rename]
  D --> F[Guarded copy fallback]
  E --> G[Published replacement]
  F --> G
  G --> H[Optional parent sync]
Loading

Before merge

  • Resolve merge risk (P1) - Custom synchronous fileSystem adapters that explicitly pass mode or preserveExistingMode must supply fchmodSync; otherwise this branch intentionally fails before mutation rather than falling back to an unsafe pathname chmod.
  • Complete next step (P2) - No discrete repair finding remains; this PR needs ordinary maintainer merge review rather than an automated follow-up patch.
Agent review details

Security

None.

Review metrics

Metric Value Why it matters
Security regression coverage 5 focused scenarios added in 1 new test file The added coverage exercises both entry points, umask behavior, fallback publication, injection compatibility, and missing descriptor-mode support.
Patch surface 10 files affected; 356 added, 61 removed The change updates implementation, public contract documentation, changelog, and targeted regressions together.

Merge-risk options

Maintainer options:

  1. Accept the documented sync-adapter contract (recommended)
    Land the change with the existing fail-closed behavior: custom synchronous adapters that request explicit or preserved modes must provide descriptor-bound fchmodSync.

Technical review

Best possible solution:

Merge the descriptor-bound mode implementation with its documented conditional sync-adapter contract, then release it as the fix for the atomic replacement permission race.

Do we have a high-confidence way to reproduce the issue?

Yes. Current main’s source shows a destination-path chmod after rename, and the branch contains a focused real-filesystem regression that stages the destination swap at that boundary; this review did not execute tests because the checkout is read-only.

Is this the best way to solve the issue?

Yes. Binding the requested mode to the already-open temp or pinned fallback descriptor is the narrowest maintainable fix and preserves exact modes under umask without dereferencing the published destination path.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 2477f5681f68.

Labels

Label changes:

  • add P1: This PR fixes a confirmed local arbitrary-file permission-change window in a public atomic-write primitive.
  • add merge-risk: 🚨 compatibility: Custom synchronous injected filesystem adapters now need fchmodSync when they request explicit or preserved replacement modes.
  • add proof: sufficient: Contributor real behavior proof is sufficient. The PR body provides after-fix real-filesystem output for both entry points under umask 077, including the staged swap result, exact published mode, unaffected victim mode, and injected node:fs behavior.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The PR body provides after-fix real-filesystem output for both entry points under umask 077, including the staged swap result, exact published mode, unaffected victim mode, and injected node:fs behavior.

Label justifications:

  • P1: This PR fixes a confirmed local arbitrary-file permission-change window in a public atomic-write primitive.
  • merge-risk: 🚨 compatibility: Custom synchronous injected filesystem adapters now need fchmodSync when they request explicit or preserved replacement modes.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The PR body provides after-fix real-filesystem output for both entry points under umask 077, including the staged swap result, exact published mode, unaffected victim mode, and injected node:fs behavior.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body provides after-fix real-filesystem output for both entry points under umask 077, including the staged swap result, exact published mode, unaffected victim mode, and injected node:fs behavior.

Evidence

What I checked:

  • Current-main vulnerable ordering: Current main writes and renames the temp file, then performs best-effort chmod on the caller-supplied destination pathname; the reported swapped-symlink window therefore remains present on main. (src/replace-file.ts:371, 2477f5681f68)
  • Descriptor-bound replacement mode: The proposed helper opens the exclusive temp file, writes content, applies the requested mode through the open handle, optionally syncs it, obtains its identity, and closes it before rename. (src/replace-file-descriptor.ts:19, cb44a1d8453d)
  • Copy-fallback mode remains pinned: The branch applies the source mode through the already-open destination descriptor in both asynchronous and synchronous copy fallback paths, preserving exact modes despite umask without a later pathname chmod. (src/replace-file-copy-fallback.ts:350, cb44a1d8453d)
  • Focused real-filesystem regressions: The branch adds real on-disk tests for async and sync rename-boundary swaps, exact modes under umask, copy fallback, plain node:fs async injection, and fail-closed custom sync adapters lacking fchmodSync. (test/atomic-fchmod-regression.test.ts:23, cb44a1d8453d)
  • Feature-history ownership: The current atomic-replacement code traces to the 0.5.1 release and earlier hardened atomic-replacement work by Peter Steinberger; the reviewed branch adds two follow-up commits for descriptor modes and injected async filesystems. (src/replace-file.ts:414, 1d037a2d70ee)
  • Patch cleanliness: The proposed range has no whitespace errors, and the checkout remained clean throughout read-only inspection. (cb44a1d8453d)

Likely related people:

  • steipete: Peter Steinberger authored the original hardened atomic-replacement history visible in the repository and both commits on this descriptor-mode repair branch. (role: historic and recent atomic-write contributor; confidence: high; commits: 66e59e0ce95e, 1d037a2d70ee, cb44a1d8453d; files: src/replace-file.ts, src/replace-file-copy-fallback.ts, src/replace-file-descriptor.ts)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

@steipete
steipete merged commit da387a7 into main Aug 2, 2026
27 checks passed
@steipete
steipete deleted the fix/atomic-fchmod branch August 2, 2026 21:42
steipete added a commit that referenced this pull request Aug 2, 2026
PR #91 bound replacement file modes to descriptors but left the directory mode
applied by pathname after the recursive mkdir. mkdir({recursive: true}) may
return a directory that already existed, and a freshly created one can be
renamed by whoever controls its parent, so an attacker with mutation rights on
the destination's parent could swap in a symlink and redirect the mode change.

On POSIX the directory mode now goes through a verified O_DIRECTORY|O_NOFOLLOW
descriptor and fchmod; no pathname chmod remains. Windows keeps mkdir(mode)
only, since POSIX directory modes are not enforceable there.

Plain node:fs injection keeps working on both the async and sync paths. An
explicit sync dirMode without the existing optional fchmodSync fails before
mutating anything.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

merge-risk: 🚨 compatibility 🚨 Merging this PR could break existing users, config, migrations, defaults, or upgrades. P1 Urgent regression or broken agent/channel workflow affecting real users now. proof: sufficient Contributor real behavior proof is sufficient. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: atomic replacement chmods the caller-supplied path after rename, following a swapped symlink

1 participant