Repository navigation
fix(cli): save config and credentials atomically so parallel bgagent runs never read a partial file (#1080) - #1081
abhiramshaji-cyber wants to merge 3 commits into
Conversation
…er read a partial file (aws-samples#1080)
isadeks
left a comment
There was a problem hiding this comment.
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.
…-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.
|
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
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. |
|
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! |
Hey @isadeks, hope you're doing well! Your write up on #1080 made this really easy to follow, the parallel
microvm-acceptance.shrun plus the pointer towriteSecretFiletook me straight to it. Thank you.When several
bgagentruns 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, constructsagent— Python runtime / Docker imagecli—bgagentclientdocs— guides or design sources (docs/guides/,docs/design/)tooling— rootmise.toml, scripts, CI workflowsRelated
Closes #1080
Changes
What this code is for
cli/src/config.tsreads and saves the files under~/.bgagent(orBGAGENT_CONFIG_DIR).saveCredentialsstores the Cognito tokens throughwriteSecretFile,saveConfigstoresconfig.json, andloadCredentials/loadConfigread them back at the start of almost every command.writeSecretFileis also used bybgagent replay --output, the invite file inadmin.tsandsavePendingConsent.writeSecretFileand the four places that save through it, Functions view in ArchitectBefore this PR
Two
bgagentruns start at the same time fromscripts/microvm-acceptance.sh, sharing onecredentials.json.saveCredentials, which callswriteSecretFile.fs.writeFileSync(file, content, { mode: SECRET_FILE_MODE })openscredentials.json, empties it, then writes the new JSON.loadCredentialsbetween the empty and the write, and reads an empty or half written file.JSON.parsethrows, and run 2 stops withCredentials file is corrupt. Run bgagent login to re-authenticate.saveConfigwritesconfig.jsonthe same way, soloadConfigandtryLoadConfigcan 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.
saveCredentials, thenwriteSecretFile, as before.replaceFileincli/src/replace-file.tsopens a new.credentials.json.<uuid>.tmpin the same folder withopenSync(temp, 'wx', 0o600), so the file is 600 from the moment it exists.fchownSync, sets the mode withfchmodSync, and callsfsyncSyncbefore closing.renameSyncmoves that file overcredentials.jsonin one step.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:
credentials.jsonis bind mounted into a container with-v host/credentials.json:/root/.bgagent/credentials.json.renameSyncthrowsEBUSY, which is inRENAME_REFUSED(EACCES,EPERM,EROFS,EBUSY,EXDEV,ENOTSUP)..tmpfile is removed andwriteInPlacedoes whatmaindoes:writeFileSyncthenchmodSyncto 600.node:22-alpinecontainer: the earlier head of this PR failed withEBUSY, 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:#111827The change
replaceFile(file, content, createMode, setMode?)in the newcli/src/replace-file.tswrites a temporary file next to the target andrenameSyncs it over.writeSecretFileandsaveConfiginconfig.tsboth go through it.regularFileTargetdecides where the rename lands. A symlink is followed withrealpathSync, so the linked file is updated and the link stays. A path that is not a regular file, such as/dev/nullforreplay --output, is written in place like before.RENAME_REFUSED,writeInPlacesaves the waymaindoes. 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.EACCES, as onmain:accessSync(target, W_OK)runs before the swap.config.jsontightened to 600 is never 644 on disk, even briefly.saveConfigkeeps an existing file's mode, and a new one is still created with 644.cli/test/replace-file.test.tscovers the creation mode, owner and group, the fallback onEBUSY,EXDEV,EPERMandEACCES, a refusedfchownSync, 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.tskeeps 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 fulljest --cirun (86 suites, 1,654 tests, coverage floors) all pass locally.What changes for a user
bgagentruns no longer fail with "Credentials file is corrupt" on a valid login.credentials.jsonbind mounted into a container still saves, as it did onmain.replay --outputto a folder you cannot write to, or to/dev/null, behaves exactly as before.main. That is taken on purpose: saving matters more than the swap in those setups.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.