Skip to content

credstore: atomic write to prevent torn credentials - #37

Merged
minarc merged 1 commit into
mainfrom
fix/credstore-atomic-write
Apr 21, 2026
Merged

minarc merged 1 commit into
mainfrom
fix/credstore-atomic-write

Conversation

@minarc

@minarc minarc commented Apr 21, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Multiple plugin hooks (`UserPromptSubmit`, `PreToolUse`, `PostToolUse`, …) are marked `async: true` in `hooks.json` and routinely run concurrently. `writeStore` used `fs.writeFileSync` directly, which has two concrete failure modes:

  1. Torn writes — a process killed mid-write leaves a truncated JSON file. Next `readStore` catches the parse error, returns `{}`, and the next `writeStore` silently overwrites the file with a near-empty object. `device_id`, `hash_salt`, and `license_jwt` all vanish together.
  2. Lost updates — concurrent writers partially clobber each other.

This PR replaces `writeStore` with a temp-file + fsync + rename pattern. POSIX rename within the same filesystem is atomic, so readers see either the old file or the new file — never a partial write.

Change

Single function in `skillmeter/scripts/credstore.js` (`writeStore`). No API change, no new deps, no other files touched.

Key design points:

  • Temp file sits next to `CRED_FILE` (same dir → same fs → atomic `rename`).
  • Tempfile name includes `process.pid` + `Date.now()` so concurrent writers don't collide on the tempfile itself.
  • `0o600` from creation, so cleartext credentials never exist with broader permissions.
  • `fsyncSync` before `rename` prevents a host crash from landing a renamed-but-empty file.
  • Error path closes the fd and unlinks the tempfile so `~/.skillbench/` doesn't accumulate `credentials.json.tmp.*` garbage.

What this does NOT fix

Lost updates across concurrent `read → mutate → write` cycles are still possible (a smaller window now, bounded by the in-memory mutation). Full fix requires a file lock (`proper-lockfile` or similar) — tracked as a separate follow-up.

Verified

  • `node -c skillmeter/scripts/credstore.js` — syntax clean
  • Round-trip: `setLicenseToken("smoke-jwt")` → `getLicenseToken()` → `jq .license_jwt credentials.json` all match
  • Concurrent stress: 2 processes, 100 writes each targeting different fields → file remains valid JSON, zero tempfile leftover
  • Mid-flight crash simulation: `setImmediate(() => process.exit(1))` racing a 10MB write → file remains valid JSON, zero tempfile leftover

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Improved credential file write operations to provide enhanced data integrity during storage operations.

Multiple plugin hooks (UserPromptSubmit, PreToolUse, PostToolUse, …)
run async and can write ~/.skillbench/credentials.json concurrently.
writeStore used fs.writeFileSync directly, so:

- A process killed mid-write leaves a truncated JSON file. The next
  readStore catches the parse error, returns {}, and the next
  writeStore silently overwrites the file with a near-empty object —
  device_id, hash_salt, and license_jwt all vanish together.
- Concurrent writers partially clobber each other.

Replace writeStore with a temp-file + fsync + rename pattern:

- Write payload to a sibling tempfile (same directory → same fs, so
  rename is an atomic inode swap).
- fsync before rename so a host crash can't land a renamed-but-empty
  file.
- Unique tempfile name (pid + timestamp) prevents concurrent writers
  from colliding on the tempfile itself.
- On error, close fd + unlink tempfile so the dir doesn't accrete
  credentials.json.tmp.* garbage.

This kills the torn-write class completely and shrinks the
lost-update window from the whole I/O operation to just the
in-memory mutation. Fully eliminating lost updates still needs a
file lock (separate follow-up).

Verified:
- node -c syntax passes
- round-trip: setLicenseToken → getLicenseToken → file on disk
- concurrent-writer stress: 2 procs × 100 writes each, file stays
  valid JSON, zero tempfile leftover
- mid-flight crash simulation: file remains valid JSON, zero
  tempfile leftover

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Apr 21, 2026 •

Copy link
Copy Markdown
Contributor

Walkthrough

The writeStore() function in credstore.js is refactored to perform atomic credential writes using a temporary file with restrictive permissions, followed by fsync and atomic rename instead of direct in-place writes. This prevents partial reads during writes and improves data durability.

Changes

Cohort / File(s) Summary
Credential Storage Atomicity
skillmeter/scripts/credstore.js
Modified writeStore() to write credentials atomically via temporary file with restrictive permissions, fsync durability guarantee, and atomic rename. Includes error handling with best-effort cleanup of temporary file and descriptor on failure.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Poem

🐰 A temp file appears with permissions so tight,
Data flows in, then fsync locks it tight,
Atomic rename—now the swap is complete,
No partial reads can leave us in defeat,
Credentials are safe, the workflow's neat! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically describes the main change: implementing atomic writes to prevent torn credentials in the credstore module.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/credstore-atomic-write

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai 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.

Actionable comments posted: 1

🧹 Nitpick comments (1)
skillmeter/scripts/credstore.js (1)

36-40: Use exclusive creation flag and stronger UUID for tempfile to prevent collision overwrites.

The code uses Date.now() with the "w" flag, which silently overwrites any existing tempfile at the same path. In rare concurrent-write scenarios, this could clobber writes from another process. Replace with crypto.randomUUID() (already imported) and the "wx" flag, which atomically creates the file and fails with EEXIST if it already exists—a standard best practice for tempfile collision avoidance.

Proposed hardening
-  const tempPath = `${CRED_FILE}.tmp.${process.pid}.${Date.now()}`;
+  const tempPath = `${CRED_FILE}.tmp.${process.pid}.${crypto.randomUUID()}`;
   let fd;
   try {
-    fd = fs.openSync(tempPath, "w", 0o600);
+    fd = fs.openSync(tempPath, "wx", 0o600);
     fs.writeSync(fd, JSON.stringify(data, null, 2) + "\n");
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@skillmeter/scripts/credstore.js` around lines 36 - 40, The tempfile creation
uses Date.now() and fs.openSync with the "w" flag which can overwrite an
existing temp file; change tempPath to include crypto.randomUUID() instead of
Date.now() and call fs.openSync(tempPath, "wx", 0o600) so the creation is
exclusive and fails with EEXIST on collision; update the error handling around
fs.openSync (in the block referencing tempPath, CRED_FILE, process.pid and
fs.openSync) to retry or generate a new UUID on EEXIST instead of silently
overwriting.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@skillmeter/scripts/credstore.js`:
- Line 44: After the atomic rename using fs.renameSync(tempPath, CRED_FILE) you
must fsync the parent directory to ensure the rename metadata is persisted;
modify the code after the fs.renameSync call to open the directory containing
CRED_FILE (use path.dirname(CRED_FILE)), call fs.fsyncSync on the directory file
descriptor, then close the descriptor (fs.closeSync); keep the operations
synchronous to match the existing fs.renameSync usage and surface any errors
from fs.openSync/fs.fsyncSync/fs.closeSync so failures can be handled or logged.

---

Nitpick comments:
In `@skillmeter/scripts/credstore.js`:
- Around line 36-40: The tempfile creation uses Date.now() and fs.openSync with
the "w" flag which can overwrite an existing temp file; change tempPath to
include crypto.randomUUID() instead of Date.now() and call fs.openSync(tempPath,
"wx", 0o600) so the creation is exclusive and fails with EEXIST on collision;
update the error handling around fs.openSync (in the block referencing tempPath,
CRED_FILE, process.pid and fs.openSync) to retry or generate a new UUID on
EEXIST instead of silently overwriting.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 971336a8-d19b-4de4-b5bf-26efce2f55bf

📥 Commits

Reviewing files that changed from the base of the PR and between b8fc9e6 and 58cc9c3.

📒 Files selected for processing (1)
  • skillmeter/scripts/credstore.js

fs.fsyncSync(fd);
fs.closeSync(fd);
fd = undefined;
fs.renameSync(tempPath, CRED_FILE);

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.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🌐 Web query:

On POSIX filesystems, after fsyncing a temp file and renaming it over the target, is fsync on the parent directory required to guarantee the rename survives power loss? Please cite Node.js and filesystem documentation.

💡 Result:

Yes, on POSIX filesystems, after fsyncing a temp file and renaming it over the target, an fsync on the parent directory is required to guarantee the rename survives power loss. POSIX requires fsync (or fdatasync) on the parent directory after rename to ensure directory modifications (like renames) are durable against crashes. Rename is atomic but not necessarily durable without it; the directory entry update may not reach disk. Linux man fsync(2) explicitly states: "Calling fsync does not necessarily ensure that the entry in the directory containing the file has also reached disk. For that an explicit fsync on a file descriptor for the directory is also needed." Node.js fs module exposes fs.fsync(fd) and fs.fsyncSync(fd), where fd can be from fs.open(parentDir, O_RDONLY) or fs.opendir(parentDir). After fs.fsyncSync(dirFd), the rename to target (in same parent) is durable. Node.js docs model POSIX fs functions but do not explicitly cover durability; rely on underlying syscalls. Some filesystems (ext4 with auto_da_alloc) mitigate file data issues but not directory metadata without parent fsync. For full guarantee across POSIX/Linux filesystems, parent fsync is needed.

Citations:


Persist the rename with a parent-directory fsync to guarantee crash durability of credential file writes.

Line 44 renames atomically, but without fsyncing the parent directory, a host crash can still lose the rename metadata on POSIX filesystems. According to POSIX standards, fsyncing the parent directory after rename is required to ensure directory entry modifications reach disk. Without this step, a power loss immediately after renameSync() can leave the old credential file in place.

Proposed durability fix
     fs.fsyncSync(fd);
     fs.closeSync(fd);
     fd = undefined;
     fs.renameSync(tempPath, CRED_FILE);
+    const dirFd = fs.openSync(dir, "r");
+    try {
+      fs.fsyncSync(dirFd);
+    } finally {
+      fs.closeSync(dirFd);
+    }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@skillmeter/scripts/credstore.js` at line 44, After the atomic rename using
fs.renameSync(tempPath, CRED_FILE) you must fsync the parent directory to ensure
the rename metadata is persisted; modify the code after the fs.renameSync call
to open the directory containing CRED_FILE (use path.dirname(CRED_FILE)), call
fs.fsyncSync on the directory file descriptor, then close the descriptor
(fs.closeSync); keep the operations synchronous to match the existing
fs.renameSync usage and surface any errors from
fs.openSync/fs.fsyncSync/fs.closeSync so failures can be handled or logged.

@minarc
minarc requested a review from jhunlee-dev April 21, 2026 18:02
@minarc
minarc merged commit 3b11f1f into main Apr 21, 2026
1 check passed
@TheStarkor
TheStarkor deleted the fix/credstore-atomic-write branch September 21, 2026 18:40
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.

2 participants