Skip to content

fix(storage): atomic saves keep file modes and sync the credential bytes - #2458

Merged
arul28 merged 2 commits into
mainfrom
fix/atomic-file-durability
Nov 23, 2026
Merged

arul28 merged 2 commits into
mainfrom
fix/atomic-file-durability

Conversation

@arul28

@arul28 arul28 commented Nov 23, 2026 •

Copy link
Copy Markdown
Owner

Why

Four atomic writers had drifted from ADE's shared helper:

  • writeGlobalState replaced ade-state.json through a temp at the umask default, so an existing 0600 file became group/world-readable.
  • The credential store renamed a 0600 temp without syncing it; a crash right after the rename can leave an empty file, and the refresh token it held is already spent.
  • writeFileAtomic skipped its post-open chmod when the caller passed a mode, so a narrowing umask could still strip bits.
  • secureWriteAtomicWithinRoot (Files tab and lane-diff saves) replaced the target inode at the umask default: editing a 0755 script dropped its executable bit and a 0600 .env became readable.

Same defect class as pingdotgg/t3code#24310 and issue #14967, verified against ADE's writers.

What changed

  • Global state now uses the shared writeFileAtomic(..., { fsync: true }).
  • The credential writer fsyncs the temp file and its directory.
  • The post-open chmod runs for an explicit mode too.
  • The user-file writer carries the target's existing mode onto the temp before any bytes land; new files keep today's default.

Evidence

  • The credential store suite passes (71 passed, 1 skipped) and the desktop state suite passes.
  • New POSIX-only tests cover the umask case and 0755/0600 user-file preservation. This Windows host skips them, as do the existing mode tests; they run in CI.
  • Typecheck passes for both packages.

Not checked

The POSIX mode assertions were not run on this Windows host. Full CI matrix not run locally.

🤖 Generated with Claude Code


Devin Review

ADE   Open in ADE  ·  fix/atomic-file-durability branch  ·  PR #2458

RetriggerView in GreptileConfidence Score: 4/5

The PR should not merge until the previously reported saved-state truncation risk is fixed.

Fix All in Claude CodeFindings

  1. P1 Saved state can be truncated ▶
Fix with agent prompt
### Issue 1
apps/desktop/src/main/services/state/globalState.ts:undefined-226
`writeGlobalState` now reaches a fallback that copies directly over the saved file when both rename attempts are refused. On Windows, another program holding the file open can trigger this path. Readers can see incomplete JSON, and a failed copy can destroy the previous state. The old writer left the saved file untouched when rename failed. Keep this caller on a rename-only path, even if that means skipping the update.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Summary

The PR keeps file permissions during atomic saves and adds sync calls to credential writes.

  • Credential saves sync their bytes before replacing the stored file.
  • Workspace and lane edits keep the permission bits of existing files.
  • Desktop state saves keep existing file modes and sync replacements.
  • The shared durable writer honors explicitly requested file modes.

No new actionable issues were found in the follow-up changes.

Reviews (2) · Last reviewed commit: "fix(storage): keep the temp private at c..." · Reviewed by Greptile

Four writers had drifted from ADE's own atomic-save helper:
- writeGlobalState hand-rolled a temp+rename that replaced an existing
  ade-state.json's permission bits with the umask default.
- The credential store's atomic writer renamed a 0600 temp without syncing
  it, so a crash right after the rename could leave an empty credential file
  and sign the machine out.
- writeFileAtomic skipped the post-open chmod when the caller passed an
  explicit mode, so a narrowing umask could still strip bits.
- secureWriteAtomicWithinRoot, used by every Files-tab and lane-diff save,
  replaced the target inode with a temp at the umask default: editing a 0755
  script dropped its executable bit and a 0600 .env became readable.

Use the shared writer for global state, fsync the credential temp and its
directory, always apply the mode to the open descriptor, and carry the
target's existing bits onto the user-file temp before any bytes land. The
new mode tests are POSIX-only and skipped on this Windows host.

Co-Authored-By: Claude Code <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 22 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used all 2 included reviews currently available.

Learn how review limits work.

Review configuration:

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 3daa933 and 03eacec.

Files selected for processing: 7

  • apps/ade-cli/src/services/credentials/credentialFileIo.ts
  • apps/desktop/src/main/services/files/fileService.test.ts
  • apps/desktop/src/main/services/shared/utils.ts
  • apps/desktop/src/main/services/state/durableFile.test.ts
  • apps/desktop/src/main/services/state/durableFile.ts
  • apps/desktop/src/main/services/state/globalState.test.ts
  • apps/desktop/src/main/services/state/globalState.ts
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@devin-ai-integration devin-ai-integration Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Devin Review found 2 potential issues.

2 flags not posted on this PR by your GitHub settings — view them in Devin Review. (Configure)

Devin Review

// One atomic writer for the whole app: it keeps the replaced file's
// permission bits (this hand-rolled save widened a 0o600 state file under
// the process umask) and syncs the temp file and its directory.
writeFileAtomic(filePath, serialized, { fsync: true });

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Settings replaced after failed disk flush

When the temp file’s disk flush fails, writeGlobalState can still replace the last good settings file. bestEffortFsync suppresses writeback errors, so the rename can publish incomplete settings.

Learn more

Desktop settings, recent projects, and pending update records share one JSON file. Desktop startup reads it as a unit. The previous writer abandoned the temporary file when flushing its contents failed. The shared atomic writer now proceeds to replacement after its flush helper catches the error. If a real writeback error leaves incomplete bytes, readGlobalState falls back to empty state on the next launch.

Example: A recent-project update fits in the filesystem cache, but delayed allocation returns ENOSPC on flush. The temporary file can still be renamed over the valid state, losing previously stored settings along with the attempted update.

Recommended fix: Use a strict regular-file flush for global state and propagate its failure before replacing the destination. Directory flush can remain best effort. Exercise this path with an injected temp-file fsyncSync failure and verify that the old JSON survives.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

fs.fsyncSync(fd);
fs.closeSync(fd);
fd = null;
fs.renameSync(tempPath, filePath);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Non-atomic overwrite of desktop settings

When Windows blocks replacement but allows writes, writeGlobalState can overwrite the live settings file in place. replaceViaRename falls back to a direct copy, so an interrupted copy can destroy the previous settings.

Learn more

The desktop keeps preferences, recent projects, and update recovery data in one JSON file. The previous save used only a rename to publish new bytes, so a refused rename left the previous bytes untouched. The shared replacement helper first retries the rename, then tries a staged rename, and finally copies directly to the destination for certain repeated rename errors. The last operation is not atomic and does not flush the copied destination file. readGlobalState treats malformed JSON as empty state.

Example: While the user changes a preference, a Windows reader holds the settings file open with write sharing but without delete sharing. Both renames fail, so the save copies directly onto the settings file. If that copy is interrupted, the next launch can find incomplete JSON instead of the previous settings.

Recommended fix: Give global-state writes a rename-only replacement policy. Keep transient rename retries, but never let this caller fall back to copying over the live file. Verify that a persistent rename refusal leaves the original bytes untouched.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

// One atomic writer for the whole app: it keeps the replaced file's
// permission bits (this hand-rolled save widened a 0o600 state file under
// the process umask) and syncs the temp file and its directory.
writeFileAtomic(filePath, serialized, { fsync: true });

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Saved state can be truncated

writeGlobalState now reaches a fallback that copies directly over the saved file when both rename attempts are refused. On Windows, another program holding the file open can trigger this path. Readers can see incomplete JSON, and a failed copy can destroy the previous state. The old writer left the saved file untouched when rename failed. Keep this caller on a rename-only path, even if that means skipping the update.

Prompt To Fix With AI
This is a comment left during a code review.
Path: apps/desktop/src/main/services/state/globalState.ts
Line: 226

Comment:
**Saved state can be truncated**

`writeGlobalState` now reaches a fallback that copies directly over the saved file when both rename attempts are refused. On Windows, another program holding the file open can trigger this path. Readers can see incomplete JSON, and a failed copy can destroy the previous state. The old writer left the saved file untouched when rename failed. Keep this caller on a rename-only path, even if that means skipping the update.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Fix in Claude Code

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Comment @cursor review or bugbot run to trigger another review on this PR

Reviewed by Cursor Bugbot for commit 2d57067. Configure here.

} catch {
// Filesystems without POSIX bits keep the open's mode.
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Temp created before mode is applied

Medium Severity

writeFileByDescriptor still opens the sibling temp with 0o666 (umask-filtered, typically 0644) and only then fchmods the preserved mode. A local observer can open that temp in the create-to-chmod window and keep the fd after the mode is narrowed, so a 0600 .env is readable while its bytes land. writeFileAtomic already passes the intended mode into open so the file is never born wider.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 2d57067. Configure here.

Review follow-ups:
- writeFileByDescriptor passes the kept mode to open as well, so a 0600
  user-file temp is never briefly readable between create and fchmod.
- The umask test skips in Vitest worker threads, where process.umask()'s
  setter throws (ERR_WORKER_UNSUPPORTED_OPERATION) on Linux CI.
- globalState's leftover-temp assertion follows the shared writer's
  `.tmp-<pid>-<hex>` shape instead of a `.tmp` suffix.

Co-Authored-By: Claude Code <noreply@anthropic.com>
@arul28
arul28 merged commit 6612cb1 into main Nov 23, 2026
28 checks passed
@arul28
arul28 deleted the fix/atomic-file-durability branch November 23, 2026 08:11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant