magpie icon indicating copy to clipboard operation
magpie copied to clipboard

provider: a Codex token refresh writes the user's own ~/.codex/auth.json with a truncating write — a machine going down mid-write, or a file held for a moment on Windows, leaves Codex signed out

Open JasonBuildAI opened this issue 1 month ago • 3 comments

magpie's Codex token refresh replaces the user's own Codex sign-in — ~/.codex/auth.json ($CODEX_HOME/auth.json when set), the file Codex CLI and the Codex app-server (codex-rs) read — with a bare os.WriteFile, which truncates it and then writes. Every other write of a sign-in in this tree puts the new contents in a temp file, flushes it and renames it in (steady.WriteFile, the #1505 rule in docs/subsystems/providers-accounts.md), the same auth.json included: writePrivate (internal/provider/logins.go:296) writes it when the sign-in is switched, and kiro.go:476 writes a user's IDE credential file with the comment "(#1505)". The refresh path is the write of a sign-in left on the old shape — and writeClaudeCredential's file write, for Claude Code's .credentials.json, is the other one. Everything else magpie writes under Codex's own folder (config.toml, the model catalog) already goes through edit.WriteAtomic.

Impact

The file this write replaces is not magpie's state: it is the user's own sign-in, read by Codex CLI, the Codex app (its app-server reloads auth.json, internal/provider/codex_daemon.go) and the IDE extensions. magpie rewrites it on every rotation of the account's tokens, from the gateway's request signing (codexAccount's acct.sign), the allowance read (login_usage.go:400), the reset reader (codex_resets.go:250), the keep-alive (codex_warmup.go:374) and the Usage page (subscription_usage.go) — a file magpie writes throughout a session, not once at setup.

Two ways the current write loses it, both reproduced below:

  • It is truncated first. os.WriteFile opens auth.json O_TRUNC and then writes, so a machine that goes down between the two leaves it empty or half a sign-in. That is #1505's failure mode — a real user's Windows machine went down mid-write and left logins.json and plugin-auth.json at their full length with every byte zero — and it is why internal/steady exists. Here it lands on the user's vendor sign-in rather than on magpie's own files, and it leaves no account to sign back in to: the identity in the file, and everything magpie reads from it, are gone.
  • A refused write loses the rotation silently. On Windows a file another program holds open for a moment refuses to be opened for writing ("Access is denied", the opening of internal/steady/steady.go), and the error is dropped (os.WriteFile(path, …) with no check). The rotated tokens then never reach the disk while the refresh token on it has been spent, and OpenAI refuses a spent one (refresh_token_reused, the comment on codexRefresh, from a real report — 88b4c00e): the user is signed out on the next refresh of either magpie or Codex CLI, and magpie's own message is "Codex is signed out; run codex login".

This is the family the review has already fixed three times (#1505, #1569, #2017 — "同族规则漏网"). The rule is written down; this file's refresh, and Claude Code's credential file, are what it misses.

Reproduction

Windows 11, Go 1.26.8, upstream main 27a0458d. Three tests are added with the fix (internal/provider/credentials_write_test.go, credentials_write_windows_test.go); against main's code they fail:

$ go test -tags nogui -count=1 -run "TestCodexRefreshFlushesAuthJSONBeforeReplacingIt|TestClaudeCredentialFlushesBeforeReplacing|TestCodexRefreshOutlastsAHeldAuthJSON" -v ./internal/provider/
=== RUN   TestCodexRefreshFlushesAuthJSONBeforeReplacingIt
    credentials_write_test.go:83: auth.json was written without the new sign-in being flushed to the disk first
    credentials_write_test.go:86: a flush that failed left auth.json "{...\"refresh_token\": \"r-work-2\"...}" (<nil>), want the sign-in as it was
--- FAIL: TestCodexRefreshFlushesAuthJSONBeforeReplacingIt (0.05s)
=== RUN   TestClaudeCredentialFlushesBeforeReplacing
    credentials_write_test.go:122: a write whose flush failed reported as saved
    credentials_write_test.go:125: the credentials file was written without the new sign-in being flushed to the disk first
--- FAIL: TestClaudeCredentialFlushesBeforeReplacing (0.06s)
=== RUN   TestCodexRefreshOutlastsAHeldAuthJSON
    credentials_write_windows_test.go:46: the rotated tokens are not on the disk, only the spent one's: {...\"refresh_token\":\"r-work\"}}
--- FAIL: TestCodexRefreshOutlastsAHeldAuthJSON (0.22s)
FAIL
  • The first makes the flush fail, the way internal/steady/write_test.go does. main replaces auth.json anyway: the rotated sign-in sits on the disk without ever having been flushed, which is the #1505 shape — the rename can reach the disk and the data behind it not.
  • The second is the same for Claude Code's own .credentials.json, written when magpie switches the sign-in Claude Code is on (saveClaudeCredential).
  • The third holds auth.json open for 100 ms the way another program does (no write sharing, syscall.CreateFile, as steady_windows_test.go does). On main the write is refused, the error is dropped, and the file still holds the spent r-work: the rotation is gone with nothing said.

With the fix the three pass:

--- PASS: TestCodexRefreshFlushesAuthJSONBeforeReplacingIt (0.14s)
--- PASS: TestClaudeCredentialFlushesBeforeReplacing (0.06s)
--- PASS: TestCodexRefreshOutlastsAHeldAuthJSON (0.28s)
ok  	github.com/yetone/magpie/internal/provider	0.881s

Expected

A rotation is written the way every other write of a sign-in is: into a temp file beside it, flushed to the disk, renamed over it. The old file is never opened for writing, so an interruption or a refused write leaves it whole rather than empty, and a file held for a moment is waited out (steady.Rename) so the rotation lands instead of being dropped.

Fix

codexToken and writeClaudeCredential write through the package's writeFileAtomic (edit.Target + steady.WriteFile, kiro.go:476), the helper the rest of internal/provider uses for its files. codexToken's error stays dropped, as kiro.go's is: the fresh access token is in hand and the request can still be served.

JasonBuildAI avatar Oct 14 '26 17:10 JasonBuildAI

A fix for this is committed on a branch in a public fork, and gh pr create against this repository is refused for this account, so the branch is named here instead of in a PR.

branch  JasonBuildAI:fix/agent-credential-write-whole-c4f81e
commit  f447630b  (one commit, based on main 27a0458d)
fetch   git fetch https://github.com/JasonBuildAI/magpie.git fix/agent-credential-write-whole-c4f81e
diff    4 files changed, 188 insertions(+), 3 deletions(-)
          internal/provider/account.go                     +9  -2
          internal/provider/credentials_write_test.go      +130 new
          internal/provider/credentials_write_windows_test.go +48 new
          docs/subsystems/providers-accounts.md            +1  -1

The refusal is not a broken remote or a missing scope: this repository's pullRequestCreationPolicy is COLLABORATORS_ONLY (GraphQL repository(owner:"yetone",name:"magpie"){pullRequestCreationPolicy} returns COLLABORATORS_ONLY, viewerPermission: READ), and the API answers JasonBuildAI does not have the correct permissions to execute CreatePullRequest for both the GraphQL and REST paths. The newest pull request on this repository is #1355, opened 2026-10-08, so no one outside the collaborator list has been able to open one since. Nothing makes this defect less real; a maintainer can open the PR from the branch above, or the description below can be pasted as-is.

What the branch does: codexToken (internal/provider/account.go) and the sibling writeClaudeCredential write the rotated auth.json / .credentials.json through writeFileAtomic (temp file beside the target, flushed, renamed in — the internal/provider/kiro.go:476 helper), instead of the bare truncating os.WriteFile. The two new test files pin both halves of the defect: the file is never replaced before the new contents are flushed, and a write refused for a moment (a file another program holds on Windows) is waited out so the rotated tokens reach the disk.

Raw evidence at head f447630b, without the source change (old account.go, new tests):

=== RUN   TestCodexRefreshFlushesAuthJSONBeforeReplacingIt
    credentials_write_test.go:83: auth.json was written without the new sign-in being flushed to the disk first
    credentials_write_test.go:86: a flush that failed left auth.json "{\n  \"auth_mode\": \"chatgpt\", ... \"refresh_token\": \"r-work-2\"\n}\n" (<nil>), want the sign-in as it was
--- FAIL: TestCodexRefreshFlushesAuthJSONBeforeReplacingIt (0.05s)
=== RUN   TestClaudeCredentialFlushesBeforeReplacing
    credentials_write_test.go:122: a write whose flush failed reported as saved
    credentials_write_test.go:125: the credentials file was written without the new sign-in being flushed to the disk first
--- FAIL: TestClaudeCredentialFlushesBeforeReplacing (0.06s)
=== RUN   TestCodexRefreshOutlastsAHeldAuthJSON
    credentials_write_windows_test.go:46: the rotated tokens are not on the disk, only the spent one's: {"auth_mode":"chatgpt",...,"refresh_token":"r-work"}}
--- FAIL: TestCodexRefreshOutlastsAHeldAuthJSON (0.22s)
FAIL	github.com/yetone/magpie/internal/provider	0.962s

with it:

=== RUN   TestCodexRefreshFlushesAuthJSONBeforeReplacingIt
--- PASS: TestCodexRefreshFlushesAuthJSONBeforeReplacingIt (0.14s)
=== RUN   TestClaudeCredentialFlushesBeforeReplacing
--- PASS: TestClaudeCredentialFlushesBeforeReplacing (0.06s)
=== RUN   TestCodexRefreshOutlastsAHeldAuthJSON
--- PASS: TestCodexRefreshOutlastsAHeldAuthJSON (0.28s)
PASS
ok  	github.com/yetone/magpie/internal/provider	0.881s

Checks at f447630b: gofmt -l on the changed files prints nothing; go vet -tags nogui ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./... exit 0; go build, GOOS=linux go build -tags nogui, GOOS=windows go build exit 0.

The PR description that would be used, in full

A Codex token refresh no longer writes the user's own Codex sign-in in place. That file is ~/.codex/auth.json ($CODEX_HOME/auth.json when set) — the sign-in Codex CLI, the Codex app's app-server and the IDE extensions read — and magpie rewrites it on every rotation of the account's tokens: the gateway's request signing, the allowance read, the reset reader, the keep-alive and the Usage page all reach codexToken. os.WriteFile truncated it first, so a machine going down mid-write left Codex signed out with the account's identity gone — #1505's exact failure mode (a real Windows machine that went down mid-write left magpie's files at their full length, every byte zero), landing on the user's own credential rather than on magpie's state. On Windows a file another program holds for a moment refused the write, and the error was dropped: the rotation never reached the disk while the spent refresh token stayed on it, refused by OpenAI on the next refresh (refresh_token_reused, the comment on codexRefresh), with magpie itself then saying "Codex is signed out; run codex login". Claude Code's .credentials.json, written when the sign-in it is on is switched, was the other write left on the old shape — Kiro's credential file and every write of magpie's own state already flush-then-rename (steady.WriteFile, the rule at docs/subsystems/providers-accounts.md). Fixes #2239.

What it changes

  • codexToken (internal/provider/account.go) writes the rotated auth.json through writeFileAtomic (edit.Target + steady.WriteFile, the helper at internal/provider/kiro.go:476) instead of os.WriteFile: the new sign-in goes into a temp file beside it, is flushed to the disk, and is renamed in. The old file is never opened for writing, and a file held for a moment is waited out (steady.Rename).
  • writeClaudeCredential's file write does the same, the sibling of the same shape.
  • codexToken's error stays dropped, as kiro.go's is: the fresh access token is in hand and the request can still be served.

Semantic change for the subsystem page (providers-accounts, updated in this PR): the trigger is unchanged (a refresh within five minutes of expiry, and the switch that writes Claude Code's credentials). Before: the file was opened O_TRUNC and rewritten in place, so an interruption between the two, or a write refused by another program holding the file, destroyed it or dropped the rotation unnoticed. After: it is replaced by a rename of a flushed temp file, and a momentary lock is waited out; an interruption leaves the previous contents whole. No interface, state or compatibility change.

Evidence

Without the change (upstream main 27a0458d), the three new tests fail:

=== RUN   TestCodexRefreshFlushesAuthJSONBeforeReplacingIt
    credentials_write_test.go:83: auth.json was written without the new sign-in being flushed to the disk first
    credentials_write_test.go:86: a flush that failed left auth.json "{\n  \"auth_mode\": \"chatgpt\",\n  \"last_refresh\": \"2026-10-14T17:22:29.9546112Z\",\n  \"tokens\": {\n    \"access_token\": \"h.eyJleHAiOjE3OTIwMDIxNDl9.sig\",\n    \"account_id\": \"[email protected]\",\n    \"id_token\": \"h.eyJlbWFpbCI6IndvcmtAZXhhbXBsZS5jb20iLCJodHRwczovL2FwaS5vcGVuYWkuY29tL2F1dGgiOnsiY2hhdGdwdF9wbGFuX3R5cGUiOiJwbHVzIn19.sig\",\n    \"refresh_token\": \"r-work-2\"\n  }\n}\n" (<nil>), want the sign-in as it was
--- FAIL: TestCodexRefreshFlushesAuthJSONBeforeReplacingIt (0.05s)
=== RUN   TestClaudeCredentialFlushesBeforeReplacing
    credentials_write_test.go:122: a write whose flush failed reported as saved
    credentials_write_test.go:125: the credentials file was written without the new sign-in being flushed to the disk first
    credentials_write_test.go:128: a flush that failed left the credentials file "{\n  \"claudeAiOauth\": {\n    \"accessToken\": \"new-access\",\n    \"expiresAt\": 1,\n    \"refreshToken\": \"new-refresh\"\n  }\n}\n" (<nil>), want it as it was
--- FAIL: TestClaudeCredentialFlushesBeforeReplacing (0.06s)
=== RUN   TestCodexRefreshOutlastsAHeldAuthJSON
    credentials_write_windows_test.go:46: the rotated tokens are not on the disk, only the spent one's: {"auth_mode":"chatgpt","tokens":{"access_token":"h.eyJleHAiOjE3OTE5OTg3OTB9.sig","account_id":"[email protected]","id_token":"h.eyJlbWFpbCI6IndvcmtAZXhhbXBsZS5jb20iLCJodHRwczovL2FwaS5vcGVuYWkuY29tL2F1dGgiOnsiY2hhdGdwdF9wbGFuX3R5cGUiOiJwbHVzIn19.sig","refresh_token":"r-work"}}
--- FAIL: TestCodexRefreshOutlastsAHeldAuthJSON (0.22s)
FAIL	github.com/yetone/magpie/internal/provider	0.962s

With it:

=== RUN   TestCodexRefreshFlushesAuthJSONBeforeReplacingIt
--- PASS: TestCodexRefreshFlushesAuthJSONBeforeReplacingIt (0.14s)
=== RUN   TestClaudeCredentialFlushesBeforeReplacing
--- PASS: TestClaudeCredentialFlushesBeforeReplacing (0.06s)
=== RUN   TestCodexRefreshOutlastsAHeldAuthJSON
--- PASS: TestCodexRefreshOutlastsAHeldAuthJSON (0.28s)
PASS
ok  	github.com/yetone/magpie/internal/provider	0.881s

The two halves are separate claims: the first two fail because main replaces the file without ever flushing the new contents (the #1505 shape — the rename can reach the disk with the data behind it not); the Windows one fails because the write was refused and the error dropped, leaving the spent r-work on the disk.

Residual risk, so the fix is not sold as more than it is: it removes the destroyed or half-written file and the rotation silently dropped on a momentary lock, which is the part a local writer can control. It cannot remove the window a remote rotation has by nature: a crash between OpenAI rotating the pair and the rename landing still leaves a spent refresh token on the disk, and the next refresh is refused, refresh_token_reused, with the user signing in again. steady.WriteFile flushes the temp file but not the directory. A persistent refusal (a read-only file, a full disk) is still dropped silently by codexToken, as before.

An independent review re-ran the three tests at this head (three PASS) and with internal/provider/account.go restored from 27a0458d while keeping the new tests (three FAIL, the messages above), and re-ran the gofmt, vet and build commands below: all as stated. Checks at head f447630b: gofmt -l on the changed files prints nothing; go vet -tags nogui ./..., GOOS=linux go vet -tags nogui ./... and GOOS=windows go vet ./... exit 0; go build, GOOS=linux go build -tags nogui and GOOS=windows go build exit 0; go test -tags nogui ./internal/provider/ result follows in a comment.

Not run: macOS (no machine here), and the GUI tests (nothing under internal/gui/assets is touched). Pre-existing red on this Windows box, untouched by this change: TestPluginsCarried in internal/provider, which is #2229 (claimed in a separate change).

AI disclosure: this change was drafted with AI assistance at my request, under my direction and review.

An independent review reproduced this end to end on this machine: with internal/provider/account.go restored from 27a0458d and the new tests kept, all three fail with exactly the messages above; at f447630b all three pass; the gofmt, go vet and go build commands exit 0 again. It found no code problem that must be fixed before this could be merged.

JasonBuildAI avatar Oct 14 '26 18:10 JasonBuildAI

Thanks, confirmed and fixed in d5847f198.

The claim holds. Before the fix, codexToken (internal/provider/account.go) wrote the rotated tokens back with os.WriteFile(path, …, 0o600) and threw away the error. The file branch of writeClaudeCredential did the same to Claude Code's .credentials.json.

What changed

  • Both now go through writePrivate: edit.Target, then steady.WriteFile. That writes a temp file next to the target, fsyncs it, and renames it over the target with steady.Rename, which on Windows retries for up to about 0.5s while another program holds the file. The mode stays 0600. A failure partway through leaves the old file as it was.
  • codexToken still serves the request with the fresh access token if the write fails, but the failure is now logged instead of dropped. writeClaudeCredential now returns a failed flush as an error, not "saved".
  • Sibling sweep: I checked every os.WriteFile, O_TRUNC and os.Create outside tests. Saved accounts' refreshes already go through writeLogins, the Kiro IDE file through writeFileAtomic, Codex/Claude switches through writePrivate, and mcpauth and plugin-auth through steady. Gemini's, Cursor's, Grok's, Command Code's and ZCode's credential files are only read. These two were the only truncating writes of a live agent sign-in. docs/subsystems/providers-accounts.md (the #1505 entry) now says so.

What was run

  • New tests: TestCodexRefreshFlushesAuthJSONBeforeReplacingIt, TestClaudeCredentialFlushesBeforeReplacing and the Windows-only TestCodexRefreshOutlastsAHeldAuthJSON, which holds auth.json through CreateFile(GENERIC_READ, FILE_SHARE_READ) for 100ms during the refresh.
  • With both writes put back to os.WriteFile: the first two FAIL on macOS, and all three FAIL 3/3 on a Windows 11 x64 box ("the rotated tokens are not on the disk, only the spent one's"). With the fix, all three PASS 3/3 there and the two PASS on macOS.
  • gofmt -l; go vet for darwin, linux (nogui) and windows; the three builds; go test -tags nogui ./... in a sandbox HOME. All green. internal/agent and internal/gateway needed a longer -timeout on a heavily loaded machine.

Not tried: a real refresh against OpenAI (the request itself is unchanged) and a real power cut.

This ships in the next release after v0.1.1231. I'll leave the issue open until you confirm it on your side.

yetone avatar Oct 14 '26 18:10 yetone

Confirmed on main (82f48f09), Windows box, Go 1.26.8 - all three, the Windows-only one included:

> go test -tags nogui -count=1 -run "TestCodexRefreshFlushesAuthJSONBeforeReplacingIt|TestClaudeCredentialFlushesBeforeReplacing|TestCodexRefreshOutlastsAHeldAuthJSON" ./internal/provider/
ok  github.com/yetone/magpie/internal/provider  0.453s

The two writes going through writePrivate (edit.Target, then steady.WriteFile) is what the report asked for, and the sibling sweep is the answer to the family question - the two truncating writes of a live agent sign-in were the whole remainder. Closing. d5847f198 is on main but not in v0.1.1242, so it ships in the next release; my branch fix/agent-credential-write-whole-c4f81e (f447630b) is a duplicate of it and stays unmerged.

For the record, the residual risk the report named still stands and is not something a local writer can remove: a crash between OpenAI rotating the pair and the rename landing leaves the spent refresh token on the disk, and the next refresh is refused with refresh_token_reused.

AI disclosure: this verification was produced with AI assistance at my request, under my direction and review.

JasonBuildAI avatar Oct 14 '26 21:10 JasonBuildAI