Skip to content

fix(cli): save config and credentials atomically so parallel bgagent runs never read a partial file (#1080) - #1081

Closed
abhiramshaji-cyber wants to merge 3 commits into
aws-samples:mainfrom
abhiramshaji-cyber:fix/atomic-config-writes
Closed

abhiramshaji-cyber wants to merge 3 commits into
aws-samples:mainfrom
abhiramshaji-cyber:fix/atomic-config-writes

Conversation

@abhiramshaji-cyber

@abhiramshaji-cyber abhiramshaji-cyber commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Hey @isadeks, hope you're doing well! Your write up on #1080 made this really easy to follow, the parallel microvm-acceptance.sh run plus the pointer to writeSecretFile took me straight to it. Thank you.

When several bgagent runs share one config folder, one could call a perfectly good login corrupt, and this PR swaps each save in whole, writing in place only where a swap cannot work.

Area

  • cdk — infrastructure, handlers, constructs
  • agent — Python runtime / Docker image
  • cli — bgagent client
  • docs — guides or design sources (docs/guides/, docs/design/)
  • tooling — root mise.toml, scripts, CI workflows

Related

Closes #1080

Changes

What this code is for

cli/src/config.ts reads and saves the files under ~/.bgagent (or BGAGENT_CONFIG_DIR). saveCredentials stores the Cognito tokens through writeSecretFile, saveConfig stores config.json, and loadCredentials / loadConfig read them back at the start of almost every command. writeSecretFile is also used by bgagent replay --output, the invite file in admin.ts and savePendingConsent.

writeSecretFile and its four callers
writeSecretFile and the four places that save through it, Functions view in Architect

Before this PR

Two bgagent runs start at the same time from scripts/microvm-acceptance.sh, sharing one credentials.json.

  1. Run 1 refreshes its token and calls saveCredentials, which calls writeSecretFile.
  2. fs.writeFileSync(file, content, { mode: SECRET_FILE_MODE }) opens credentials.json, empties it, then writes the new JSON.
  3. Run 2 calls loadCredentials between the empty and the write, and reads an empty or half written file.
  4. JSON.parse throws, and run 2 stops with Credentials file is corrupt. Run bgagent login to re-authenticate.
  5. saveConfig writes config.json the same way, so loadConfig and tryLoadConfig can hit the same thing.

With one process saving in a loop and another reading in a loop against the built lib/, 12,714 of 42,000 reads came back corrupt.

After this PR

Same two runs, same start.

  1. Run 1 calls saveCredentials, then writeSecretFile, as before.
  2. replaceFile in cli/src/replace-file.ts opens a new .credentials.json.<uuid>.tmp in the same folder with openSync(temp, 'wx', 0o600), so the file is 600 from the moment it exists.
  3. It writes the JSON, copies the uid and gid of the old file with fchownSync, sets the mode with fchmodSync, and calls fsyncSync before closing.
  4. renameSync moves that file over credentials.json in one step.
  5. Run 2 reads either the old complete file or the new complete file, and carries on.

The same loop: 0 of 188,500 reads came back corrupt.

Where the rename cannot be used, the save falls back to the old write in place instead of failing:

  1. credentials.json is bind mounted into a container with -v host/credentials.json:/root/.bgagent/credentials.json.
  2. renameSync throws EBUSY, which is in RENAME_REFUSED (EACCES, EPERM, EROFS, EBUSY, EXDEV, ENOTSUP).
  3. The .tmp file is removed and writeInPlace does what main does: writeFileSync then chmodSync to 600.
  4. The login is saved. Checked in a node:22-alpine container: the earlier head of this PR failed with EBUSY, this one saves at 600.

The diagram

flowchart LR

classDef box fill:#eef1ff,stroke:#4c5bd4,color:#111827
classDef bad fill:#ffd6d6,stroke:#cc0000,color:#111827,stroke-width:3px
classDef good fill:#c8f0c8,stroke:#008800,color:#111827,stroke-width:3px

subgraph BEFORE["BEFORE: 12,714 of 42,000 reads corrupt"]
direction TB
  B1["two bgagent runs share credentials.json"] --> B2["run 1: saveCredentials"]
  B2 --> B3["writeFileSync empties then writes credentials.json"]
  B3 --> B4{"run 2: loadCredentials reads"}
  B4 -->|"empty or half file"| B5["Credentials file is corrupt"]
  B4 -->|"write already done"| B6["parses fine"]
end

subgraph AFTER["AFTER: 0 of 188,500 reads corrupt"]
direction TB
  A1["two bgagent runs share credentials.json"] --> A2["run 1: saveCredentials"]
  A2 --> A3["write .tmp at 600, fchown, fsync"]
  A3 --> A4{"THE CHANGE: renameSync over credentials.json"}
  A4 -->|"run 2 reads during the save"| A5["old complete file, parses"]
  A4 -->|"run 2 reads after the save"| A6["new complete file, mode 600"]
  A4 -->|"rename refused, e.g. EBUSY"| A7["writeInPlace, same as main"]
end

B1 ~~~ A1

class B1,B2,B3,B6 box
class A1,A2,A3,A6,A7 box
class B4,B5 bad
class A4,A5 good

linkStyle 3 stroke:#cc0000,stroke-width:5px
linkStyle 8 stroke:#008800,stroke-width:5px

style BEFORE fill:#fff5f5,stroke:#cc0000,color:#111827
style AFTER fill:#f3fff3,stroke:#008800,color:#111827
Loading

The change

  • The fix: replaceFile(file, content, createMode, setMode?) in the new cli/src/replace-file.ts writes a temporary file next to the target and renameSyncs it over. writeSecretFile and saveConfig in config.ts both go through it.
  • regularFileTarget decides where the rename lands. A symlink is followed with realpathSync, so the linked file is updated and the link stays. A path that is not a regular file, such as /dev/null for replay --output, is written in place like before.
  • The fallback, from @isadeks's review: when creating the temporary file, taking the old owner, or the rename fails with one of RENAME_REFUSED, writeInPlace saves the way main does. That covers a bind mounted file, a writable file in a folder that is not writable, a file owned by another user, and a rename across devices. Any other error (ENOSPC, EIO) keeps the old file and rethrows.
  • A file with more than one hard link is written in place, so every name sees the new content.
  • A read only file is refused with EACCES, as on main: accessSync(target, W_OK) runs before the swap.
  • The temporary file is opened with its final mode, so a config.json tightened to 600 is never 644 on disk, even briefly. saveConfig keeps an existing file's mode, and a new one is still created with 644.
  • If removing the temporary file fails too, the original error is the one thrown.
  • Tests: cli/test/replace-file.test.ts covers the creation mode, owner and group, the fallback on EBUSY, EXDEV, EPERM and EACCES, a refused fchownSync, a folder that is not writable, a read only file (compared with what a plain write does, so it holds as root too), hard links, and a failing cleanup. cli/test/config.test.ts keeps the reader during a save, the symlink, and the mode tests.

yarn compile, yarn typecheck, eslint --max-warnings 0 src test, knip, the masking scan and the full jest --ci run (86 suites, 1,654 tests, coverage floors) all pass locally.

What changes for a user

  • Parallel bgagent runs no longer fail with "Credentials file is corrupt" on a valid login.
  • A credentials.json bind mounted into a container still saves, as it did on main.
  • Credentials, invite files, pending consent files and replay bundles are still saved owner only, 600, whether the file is new or already there.
  • replay --output to a folder you cannot write to, or to /dev/null, behaves exactly as before.
  • A config folder symlinked from a dotfiles repo keeps its symlinks, and a hard linked file keeps its links.
  • When the save falls back to the write in place, a reader can see a half written file there, same as on main. That is taken on purpose: saving matters more than the swap in those setups.
  • ACLs and extended attributes are not copied onto the temporary file; owner, group and mode are. I asked about this inline.

Any feedback or tips are very welcome!

Acknowledgment

By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of the project license.

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

Temp file plus rename is the right fix for the partial-read bug, and the PR's tests pass locally (13 in config.test.ts). The points below are about cases where the old in-place write worked and rename does not. I ran writeSecretFile from main and from this head side by side on real files:

Case main This PR
Writable file in a directory that is not writable saved EACCES, nothing saved
File that is itself a bind mount saved EBUSY, nothing saved
Read-only (0444) file EACCES replaced without error, mode reset to 0600
Inode and hard link kept new inode, the hard link keeps the old content
config.json tightened to 0600 n/a temp file is 0644 until the chmod

The bind mount row is the one I would fix before merge: a credentials.json mounted into a container can no longer be saved. The rest are for your judgement. Details inline.

Comment thread cli/src/config.ts Resolved
Comment thread cli/src/config.ts Resolved
Comment thread cli/src/config.ts Resolved
Comment thread cli/test/config.test.ts Resolved
…-samples#1080)

A bind mounted file (EBUSY), a cross device rename (EXDEV), a directory
that is not writable, or an owner the temporary file cannot take now
falls back to the in place write. A hard linked file is written in
place, a read only file is refused as before, the temporary file is
created with its final mode, keeps the owner and group, and is synced
before the rename. A failed cleanup no longer hides the original error.
@abhiramshaji-cyber

Copy link
Copy Markdown
Contributor Author

Hope you're doing well, and thank you for such a careful review. Running both heads on real files caught things I had completely missed. I pushed 7defc2b. The swap now lives in cli/src/replace-file.ts, and every row of your table behaves like main again. In the normal case a reader still never sees a half written file, and the in place fallbacks behave exactly like main:

  • bind mounted file: saves (I reproduced the EBUSY on the old head in a node:22 container and confirmed the fix there)
  • writable file in a directory that isn't writable: saves
  • 0444 file: EACCES, as on main
  • hard link: written in place, so both names see the new content
  • temp file: created with the final mode, owner and group copied, synced before the rename

Other errors like ENOSPC or EIO still keep the old file and report the original error. The full CLI suite, typecheck, eslint, knip and the masking scan all pass locally. I left one question inline about ACLs and would love your take on it.

@krokoko

krokoko commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

Hi @abhiramshaji-cyber , thank you for this ! It was closed by #1084 , if you want to assign an issue to yourself please let us know on a ticket to avoid duplicated work on our end!

@krokoko krokoko closed this Nov 26, 2026
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.

bgagent reports a valid login as corrupt when several CLI processes run at once

3 participants