provider: Codex keeping its sign-in in the macOS keychain is read and written there (#2367, Dony2050)

Codex 0.162 with cli_auth_credentials_store = "keyring" or "auto" saves
its ChatGPT sign-in to the keychain and deletes auth.json. magpie read
only auth.json, so it hid the Codex provider and every saved account.
Adapted from Dony2050's fcebfc322 (fix/codex-macos-keychain). The changes
from that branch are below.

What Codex does (codex-rs at rust-v0.162.1: login/src/auth/storage.rs,
config/src/types.rs, features/src/lib.rs). The item is service "Codex
Auth", account "cli|" plus the first 16 hex digits of the SHA-256 of the
canonicalised CODEX_HOME. Its value is auth.json's JSON on one line.
keyring reads only the item. auto reads the item, and falls back to
auth.json when there is no item or the item can't be loaded. Saves follow
the same order. With [features] secret_auth_storage on (the default on
Windows), keyring and auto use Codex's encrypted storage instead.

internal/provider/codex_store.go is now the one reader and writer:
- A keychain interface. The real one runs `security` the way Claude Code's
  item is read (keychainText, proc.CommandContext, 10s bound; errors carry
  no argv or output). Tests get a fake (isolate, CodexKeychainForTest).
- readCodexLogin follows Codex's rules on macOS. keyring with no item is
  signed out. keyring with a refused read is unknown (codexStoreError),
  never signed out. With the encrypted storage, on Linux and on Windows,
  keyring and ephemeral are unknown and auto is auth.json. A config.toml
  that doesn't parse reads auth.json as before.
- Reads are kept 10s, a refusal 10 minutes, and only one `security` ask
  runs at a time. Each read can be a Keychain prompt, and codexToken runs
  on every request.
- A refresh writes the rotated tokens back where they came from, with
  unknown fields kept, after re-reading the item.
- saveCodexLogin (switch, first sign-in) re-reads the store first. It
  refuses when the store couldn't be read, when config.toml doesn't parse,
  for ephemeral, and for a store magpie doesn't read. It never deletes
  auth.json; Codex cleans that up itself.
- deleteCodexLogin (signing the last account out) removes the item, then
  auth.json, as `codex logout` does.
- Routed through it: codexAccount, codexToken (it now takes the home dir),
  liveLogin, CodexAPIKeySignedIn, codexLoginAuth, the usage card's
  codexUntil, session identities, switchSavedLogin, addLogin, forgetLogin,
  and agent's codexChatGPT/Source (provider.CodexSignIn).
- savedButSignedOut now says what was found (codexSignedOutWhy): nothing
  in the item, an item macOS wouldn't give (allow it, or use file), or a
  store magpie doesn't read here (use file). This replaces ed6e27f5f's
  codexCredentialsStore and its single "magpie doesn't read the keychain"
  text.

Changed from fcebfc322: secret_auth_storage is honoured (the branch would
read and write the wrong item); there is no second keychain package; reads
are cached and a denial backs off (the branch spawned `security` on every
read); auth.json is not deleted after every keychain write; auto falls back
to the file only when there is no item; the tests use an interface fake on
every OS instead of a darwin-only PATH fake; codexChatGPT keeps its
meaning; a malformed config.toml doesn't hide a file sign-in.

Run (in the wt-2367 worktree, sandbox HOMEs only, no real keychain or
`security` run, nothing under ~/.codex):
- gofmt -l: clean. go vet -tags nogui ./... for darwin, linux and windows:
  clean.
- go test -p 1 -tags nogui ./internal/provider: ok (293s).
  ./internal/agent: ok (1291s). An earlier agent run hit the disk filling
  up (ENOSPC from other sessions' builds); it was rerun with room.
  ./internal/gateway -run 'Codex|Login|Account': ok (261s).
- Broken by hand. The keychain never read (keychainItem false):
  TestCodexSignedInInKeychain, TestCodexKeychainRefreshWritesItem,
  TestCodexKeychainSwitch, TestCodexKeychainAskedSeldom,
  TestCodexKeychainSignOut and TestSavedButSignedOut go red. saveCodexLogin
  ignoring a refused read: TestCodexKeychainSwitch red ("switched over a
  sign-in the keychain wouldn't give"). No cache:
  TestCodexKeychainAskedSeldom red (20 asks for 20 reads). agent's
  codexChatGPT reading auth.json only: TestCodexSignInInKeychain red.
- Not tried: an item Codex itself wrote. Codex writes it through
  keyring-rs, and its ACL may trust only codex, so macOS may prompt the
  first time magpie reads it, and Codex may prompt after magpie rewrites
  it (`add-generic-password -U`). An unanswered prompt is killed at 10s
  and reads as unknown. The reporter is asked to confirm on #2367, which
  stays open.

Landing: this goes on top of ed6e27f5f (in this worktree as its
cherry-pick 66cdde294) and replaces that commit's message.

Co-authored-by: Dony2050 <88673296+Dony2050@users.noreply.github.com>

Full suite: SUITE_LINE
This commit is contained in:
yetone
2026-10-15 23:08:04 +08:00
co-authored by Dony2050
parent e26d26ab5b
commit 7dc5cd8f08
20 changed files with 1071 additions and 95 deletions
+4 -3
View File
@@ -31,7 +31,8 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi
| Google Vertex AI | `google-vertex` (`VertexPreset`, `IsVertex`) is a provider of the user's own with no key. `Provider.Vertex` holds `project`, `location` (`global`, `us`, `eu` or a region; `global` when empty), `credentials` (a file; empty for Application Default Credentials) and `impersonate` (a service account's email). Save refuses a key given it, then normalizes them (`Normal`) and checks each (`check`); `normalize` clears the four URLs and any key put in `providers.json` by hand, which stands in for neither a token nor a project and leaves the provider as found savable, so the provider's one address is `vertexBase`, `https://<host>/v1/projects/<project>/locations/<location>`, its host following the location (`vertexHost`). It speaks Gemini alone (`Speaks`, `Base`). It is `Ready` once that address can be made, never from a key or an account; until then the app, `magpie providers` and the TUI say it needs a project, and `magpie provider <id>` says how to give it one. `hasEndpoint` counts it as a provider of the user's own, not a subscription's picks. An import link naming it is refused (`ParseImport`): its project and credentials are the user's own, which no link hands over. `Sign` refuses any other address and sets the bearer token before the user's `Headers`; `AuthHeaders` gives it no key header. Its models are its location's (`vertexModels`, in `planModels`): the preset has `NoList`, because Vertex AI has no list that says what a location serves. The lists are in the [reference](../reference.md#google-vertex-ai). | [`vertex.go`](../../internal/provider/vertex.go), [`provider.go`](../../internal/provider/provider.go), [`account.go`](../../internal/provider/account.go), [`rename.go`](../../internal/provider/rename.go), [`models.go`](../../internal/provider/models.go), [`importurl.go`](../../internal/provider/importurl.go) |
| Vertex AI tokens | `vertexCredentialsFile` finds the credentials as Google's libraries find Application Default Credentials: the provider's `credentials`, else the file `GOOGLE_APPLICATION_CREDENTIALS` names, else `application_default_credentials.json` in gcloud's folder (`CLOUDSDK_CONFIG`, else `~/.config/gcloud`, `%APPDATA%\gcloud` on Windows); a `~/` that starts any of them is the home. `mint` reads three kinds: `authorized_user` (a refresh-token grant), `service_account` (an RS256 JWT, RFC 7523: `signed`) and gcloud's `impersonated_service_account`, whose `source_credentials` are minted and traded at IAM Credentials, along its `delegates`, for the account its `service_account_impersonation_url` names (`impersonationURL`: the token never goes to that URL's host). With `impersonate` set, the token those give is traded at IAM Credentials' `generateAccessToken` for a `cloud-platform` token of that account's, as gcloud's `--impersonate-service-account` does (`impersonateFor`); the credentials' account needs `roles/iam.serviceAccountTokenCreator` on it, which the 403 names. `vertexTokens` keeps one token per file and impersonated account, in memory only; requests made together mint it once, and those that waited through a mint that failed are given its error rather than each minting in turn (`mints`, `failed`). A mint cut short because its own request was given up on fails none of them: the next one mints. It is minted again within `vertexRefreshLead` (5 minutes) of expiry, or when the file's size or modification time has changed (gcloud signed in again). One mint, every exchange included, gets `vertexMintWait` (30 seconds). The file is only read. | [`vertex.go`](../../internal/provider/vertex.go), [`signin.go`](../../internal/provider/signin.go) |
| Subscription accounts | `Accounts` reads the credentials each agent keeps on disk or in the macOS Keychain; nothing is stored twice. With account discovery off (#1535, below) none of them is read. A built-in that has moved to its plugin is dropped (`Moved`), and plugin accounts are placed in its slot (`placeMoved`). `Sign` adds the account's own auth, then the user's `Headers`. | [`account.go`](../../internal/provider/account.go) |
| Token refresh | Each account refreshes through its vendor. For example, `codexToken` refreshes within 5 minutes of expiry and writes the rotated tokens back into `~/.codex/auth.json` for Codex CLI. A 400 or 401 from the vendor's refresh endpoint means it was refused (`refreshFailed`). | [`account.go`](../../internal/provider/account.go) |
| Token refresh | Each account refreshes through its vendor. For example, `codexToken` refreshes within 5 minutes of expiry and writes the rotated tokens back where it read them (`codexStore.write`: `~/.codex/auth.json`, or Codex's keychain item), every other field kept, for Codex CLI. Before refreshing a sign-in read from the keychain it asks the item again, so a rotation Codex made since isn't spent twice. A 400 or 401 from the vendor's refresh endpoint means it was refused (`refreshFailed`). | [`account.go`](../../internal/provider/account.go) |
| Codex's credential store | Codex 0.162 keeps its ChatGPT sign-in where `cli_auth_credentials_store` in `$CODEX_HOME/config.toml` says (`codex-rs/login/src/auth/storage.rs`): `file` (default) is `auth.json`; `keyring` the system keychain alone; `auto` the keychain, else `auth.json`, on read and on save; `ephemeral` Codex's memory. Saved to the keychain, Codex removes `auth.json` (#2312, #2367, Dony2050). On macOS magpie reads that item through `security`, as it reads Claude Code's: service `Codex Auth`, account `cli|` + the first 16 hex digits of SHA-256 of the canonical CODEX_HOME (`codexKeychainAccount`), the value auth.json's JSON on one line. `readCodexLogin` is the one reader: `codexAccount`, `codexToken`, `liveLogin`, `CodexAPIKeySignedIn`, `codexLoginAuth`, the usage card's `codexUntil`, session identities and the agent's wiring (`provider.CodexSignIn`: `codexChatGPT`, `Agent.Source`) go through it. `keyring` with no item is signed out; `auto` with no item, or one the keychain wouldn't give, is `auth.json`, as Codex does. An item the keychain wouldn't give under `keyring` is not known (`codexStoreError`), never signed out. With `[features] secret_auth_storage` on (Codex's default on Windows) keyring and auto mean Codex's encrypted auth storage, which magpie doesn't read; nor does it read the Linux or Windows keychain. There `keyring` and `ephemeral` are not known, `auto` is `auth.json` when Codex left one, and the saved accounts' reason says to set `file` (`codexSignedOutWhy`). Requirements an admin manages (`requirements.cli_auth_credentials_store`) aren't read. Each `security` run can put a prompt in front of the user, so a read is kept 10s and a refusal 10 minutes, one ask at a time (`findCodexKeychain`); switching and refreshing ask afresh. A switch or a first sign-in (`saveCodexLogin`) writes the store Codex reads, and refuses when that store couldn't be read, when config.toml doesn't parse, or when it is one magpie doesn't read; it leaves an `auth.json` beside the item to Codex. Signing the last account out (`deleteCodexLogin`) removes the item, then `auth.json`, as `codex logout`. Not tried against an item Codex itself wrote: macOS may ask whether magpie can read it, and Codex whether it can read one magpie rewrote. | [`codex_store.go`](../../internal/provider/codex_store.go), [`codex_store_test.go`](../../internal/provider/codex_store_test.go) |
| A revoked sign-in | A 401 whose words say the sign-in itself is gone (`SignInRevoked`: ChatGPT's `token_revoked`, `invalid_grant`, `refresh_token_reused`; never `token_expired`, a 403, a 5xx or a network error) marks the account for the credential it was sent with (`NoteRevokedSignIn`, #1793). A saved ChatGPT account is refreshed first, as Codex does on a 401, and a refresh that goes through marks nothing. The mark is a hash of the header, never the credential, kept in `logins.json` as `Refused: "revoked:<mark>"` with the account's `Lapsed`, and read back after a restart. While the account has that credential, the gateway doesn't send its requests (`RevokedSignIn`); its row says Sign-in required with Sign in again. Signed in anew (`upsertLogin` with another credential, `addSideLogin`), refreshed, or served a request (`ServedSignIn`), it is clear. Claude (`claude_auth.go`), Copilot (`copilot_lapsed.go`: GitHub's 401/403 on the token exchange, the CLI's stand-in or the usage read, cleared when a token is served) and plugins keep their own marks. | [`signin_revoked.go`](../../internal/provider/signin_revoked.go), [`copilot_lapsed.go`](../../internal/provider/copilot_lapsed.go) |
| Saved accounts | `logins.json` remembers every Codex and Claude Code account seen signed in. A switch moves the credentials into the agent's own store and saves the ones it replaces. A saved account that is on (`SetLoginOn`) stands behind the agent's own. Its tokens stay in `logins.json`. | [`logins.go`](../../internal/provider/logins.go), [`logins_on.go`](../../internal/provider/logins_on.go) |
| Sign-in in magpie | `StartSignIn` runs the vendor's own browser OAuth with its client and takes the tokens at a callback on this machine. A browser that can't reach that callback (magpie on a server or in Docker) ends on a page that won't load; its address, pasted (`SubmitSignInCallback`), goes through the same callback handler (`pastedCallback`). ChatGPT's sign-in comes back only to port 1455; when that port can't be opened, the sign-in still starts and waits for the pasted address alone, and says why in `CallbackBlocked` with the port in `CallbackPort`: `reserved` for Windows' WSAEACCES on a port in a range it excludes for Hyper-V, WSL or Docker, `busy` for anything else, such as another program holding it (`callbackBlocked`, #1782). A plugin's browser sign-in (`auto`) whose page names a port on this machine to come back to takes its pasted address too: magpie opens it there on 127.0.0.1, for the plugin's own listener (`pluginCallback`, `loopbackPorts`); Command Code's page posts its key from script, so it offers the API key way instead. A Claude account is signed in by Claude Code itself. Signing in brings back an account removed from magpie (`ShowAccount`). A sign-in started in magpie (`StartSignIn`, `StartPluginSignIn`) reads as done (`SignInStatus`, `WaitSignIn`) only after `finish` has run `ShowAccount` for its account, so the window, which opens the account as soon as it sees done, finds it listed. If providers.json can't be written then, the account stays hidden and the sign-in still ends done. Signing in to a plugin's provider from the command line (`pluginLogin`, with a key or the browser) brings it back too. It also takes off the mark a sign-in its vendor turned away left on the account (`Lapsed`) and shows again the agent's own account removed in magpie (`clearPluginLapse`). The window's plugin sign-in does the same with the browser (`pluginDone`, then `finish`) or with a key (`PluginAPIKey`); a key and the command line share these steps in `PluginSignedIn`. A sign-in leaves through the proxy the account's own requests will use (#1663): `ProxyOfLogin` (the account's, else the subscription's, else the global one) for the account being signed in again, the subscription's for a new one. Every request of the flow goes through `signInFlow.via`, Claude Code's own login gets it as *_PROXY (`netproxy.EnvWith`), and a plugin's sign-in runs its fetch under that proxy (`via` in `host.js`; `plugins_cli.go` for the command line). The window's sign-in box shows it as a "Proxy: …" link (`signInProxyLink`, the app menu, no userinfo shown) with Global, Direct, the subscription's and each account's proxy, or a typed one; picking one starts the sign-in again through it (`SignInOptions.Proxy`), and when it ends the pick is kept as the account's (`keepSignInProxy`: the subscription's own when it is its only account, else the account's entry). Global isn't offered while the subscription has a proxy and other accounts, since nothing could keep it. The browser's own leg goes through the browser's network, not magpie's. Signing out leaves through the same exit: a ChatGPT account's refresh token is revoked through its own proxy, read before the account is forgotten (`forgetSIWCLogin`), and Devin's CLI, asked who is signed in or for its models, runs with the account's proxy (`devinCommand`, `devinProxy`), or with the sign-in's while one asks it. | [`signin.go`](../../internal/provider/signin.go), [`claude_signin.go`](../../internal/provider/claude_signin.go), [`pluginsignin.go`](../../internal/provider/pluginsignin.go), [`pluginsignin_paste.go`](../../internal/provider/pluginsignin_paste.go), [`proxy.go`](../../internal/provider/proxy.go), [`plugins_cli.go`](../../internal/cli/plugins_cli.go) |
@@ -113,7 +114,7 @@ successful model discovery for its decision result, and reports none when
no decision model was discovered (`Test` in
[`test.go`](../../internal/provider/test.go)).
Account discovery can be turned off (#1535): Settings → Privacy → *Subscription accounts*, `magpie accounts discovery off`, or `MAGPIE_NO_ACCOUNTS=1` for one process. The first two save `noAccountDiscovery: true`, which this computer keeps through a sync or a restored backup (`KeepOwn`); the variable only ever turns discovery off, never on what the user saved off (`settings.AccountDiscoveryOff`). It is on by default. In the GUI, Off asks first and names the subscriptions in use that it stops (`discoveryOffWarning` in `app.js`, #1761: a user turned it off without meaning to and was left with no subscription working). While it is off, magpie reads no agent's sign-in: no credential file (`~/.claude/.credentials.json`, `~/.claude.json`'s account, `~/.codex/auth.json`, Copilot's, Cursor's, Devin's, Kiro's, Gemini's, ZCode's, Command Code's, OpenCode's `auth.json`), no Keychain or Secret Service item (`security`, `secret-tool`), and no agent CLI asked who is signed in. The gates sit at each reader (`readAccountFile`, `discoveryOff` in [`discovery.go`](../../internal/provider/discovery.go)) and at each route that would read or write a sign-in: `Accounts` and `All`, `Logins`, usage, renewal, warm-up, session identities, check-ins, switching, forgetting, `SetLoginOn`, `StartSignIn`, the imports, and moves onto plugins (`MoveCandidates`, `HandOver`, `KeepRetiringMoved`). Those that write refuse with `errAccountDiscoveryOff`, which says how to turn it back on. The agents' side is gated too: the Agents page's *runs on* line (`Agent.Source`), OpenCode's own providers (`readOwnAuth`), and wiring Codex, which goes by magpie's stash instead of `auth.json` (`chatGPT` in [`codex.go`](../../internal/agent/codex.go)). Subscriptions aren't served; API-key providers, middleware plugins and Pi extensions run as before. What magpie kept of its own (`logins.json`, `plugin-auth.json`, `migrations.json`) is left as it is, unread for accounts, and serves again once discovery is on. A change takes effect at once (`ForgetAccounts`); no restart is needed.
Account discovery can be turned off (#1535): Settings → Privacy → *Subscription accounts*, `magpie accounts discovery off`, or `MAGPIE_NO_ACCOUNTS=1` for one process. The first two save `noAccountDiscovery: true`, which this computer keeps through a sync or a restored backup (`KeepOwn`); the variable only ever turns discovery off, never on what the user saved off (`settings.AccountDiscoveryOff`). It is on by default. In the GUI, Off asks first and names the subscriptions in use that it stops (`discoveryOffWarning` in `app.js`, #1761: a user turned it off without meaning to and was left with no subscription working). While it is off, magpie reads no agent's sign-in: no credential file (`~/.claude/.credentials.json`, `~/.claude.json`'s account, `~/.codex/auth.json` or Codex's keychain item, Copilot's, Cursor's, Devin's, Kiro's, Gemini's, ZCode's, Command Code's, OpenCode's `auth.json`), no Keychain or Secret Service item (`security`, `secret-tool`), and no agent CLI asked who is signed in. The gates sit at each reader (`readAccountFile`, `discoveryOff` in [`discovery.go`](../../internal/provider/discovery.go)) and at each route that would read or write a sign-in: `Accounts` and `All`, `Logins`, usage, renewal, warm-up, session identities, check-ins, switching, forgetting, `SetLoginOn`, `StartSignIn`, the imports, and moves onto plugins (`MoveCandidates`, `HandOver`, `KeepRetiringMoved`). Those that write refuse with `errAccountDiscoveryOff`, which says how to turn it back on. The agents' side is gated too: the Agents page's *runs on* line (`Agent.Source`), OpenCode's own providers (`readOwnAuth`), and wiring Codex, which goes by magpie's stash instead of `auth.json` (`chatGPT` in [`codex.go`](../../internal/agent/codex.go)). Subscriptions aren't served; API-key providers, middleware plugins and Pi extensions run as before. What magpie kept of its own (`logins.json`, `plugin-auth.json`, `migrations.json`) is left as it is, unread for accounts, and serves again once discovery is on. A change takes effect at once (`ForgetAccounts`); no restart is needed.
A signed-in account's model list exists only at its vendor (Cursor's `cursor-agent models`, WorkBuddy's config, …), so `FetchNew` asks for the lists not fetched yet. Every front end calls it at start: the window (`startBackend`, then `FetchNewSoon` behind `/api/state`), the TUI (`fetchModelsCmd` in `Init`) and `magpie serve` (#1789, reyoung: the terminal and a headless gateway had offered Cursor's fallback `auto` alone until the list was fetched by hand). Listing the accounts asks a CLI who is signed in, and a look waits `firstAsk` (3s) for that; `cursor-agent about` asks Cursor's servers and can take longer, so `FetchNew` waits for each CLI asked for the first time (`awaitIdentities` in [`cli_identity.go`](../../internal/provider/cli_identity.go)) and lists the accounts again. It reports whether an account was left without its list (failed, or waiting `newFetchRetry` after a failure): the TUI then asks again a minute later (`modelsRetry`) and `serve` loops the same way, while the window asks again from its pages. A TUI model picker open when the list arrives is filled in place (`relist`), keeping its filter and the model under the cursor. `TestFetchNewWaitsForASlowSignIn`, `TestFetchNewAccount` and the TUI's `TestTUIFetchesSubscriptionModels` / `TestTUIAsksAgainForAMissingList` cover it.
@@ -199,7 +200,7 @@ and `TestHistoricalWindowHoldsUsesEachWindowsOwnReading`.
- The Copilot account the editors and CLI keep is read by `copilotLogin` ([account.go](../../internal/provider/account.go)): an editor's github.com sign-in in `~/.config/github-copilot/apps.json` or `hosts.json` first, then the Copilot CLI's, then an editor's on GHE.com. When GitHub refuses the editor token's trade for a session token (401 or 403, `copilotRefusals`, retried after an hour), the CLI's sign-in of the same login on the same host takes its place, sent as the CLI sends it, from that request on and on the Usage card (`copilotStandIn`); a CLI signed in to another account is never used for it, and the error names the editors' file (#1238). A sign-in from magpie of the account whose editor token is refused is kept and stands for it (`copilotProbeEditor`, `addCopilotLogin`); while the editor token works, it is let go as the agent's own, as before.
- An unreadable `providers.json` is an error, never an empty list. Saving over an empty list would lose every provider.
- When `logins.json` cannot be decoded as saved accounts, reads keep the accounts read before. Before saving a change, `lastgood.Keep` ([lastgood.go](../../internal/lastgood/lastgood.go)) keeps the file there now: as `logins.json.bak`, its last good generation, when it reads, or copied aside as `logins.json.bad-<time>` (`-2`, `-3`… for another within one second) when it doesn't, including valid JSON with invalid account field types, so its credentials can be recovered. If the existing file cannot be read or the copy fails, saving returns the error and leaves the original file unchanged. A missing file can be created normally.
- A Windows machine that went down mid-write left `logins.json` and `plugin-auth.json` at their full length, every byte zero (#1505): the rename reached the disk before the data. Every write of magpie's own state goes through `steady.WriteFile` (or `edit.WriteAtomic`), which flushes the temp file before renaming it in, and the plugin host's `writeDurable` does the same. So does every write of an agent's own sign-in (#2239): `codexToken`'s rotated tokens into Codex's `auth.json` (`~/.codex`, or `$CODEX_HOME` when set) and `writeClaudeCredential`'s `.credentials.json` go through `writePrivate`, never a truncating `os.WriteFile`, so a machine going down mid-write leaves the old sign-in whole, and on Windows a file another program holds for a moment is waited out (`steady.Rename`) instead of the rotation being dropped while the refresh token on the disk is spent. A file that is there but doesn't read on a cold start is read from its `.bak` (`lastgood.Read`/`Fallback`): `logins.json`, `providers.json`, `migrations.json`, `settings.json`, `profiles.json`, `plugins.json`, `plugin-auth.json` and `mcp-signins.json`. `caller-keys.json` is flushed the same way but never read from a `.bak`: a key revoked in the last write would come back, so a store that doesn't read still refuses every key. The recovery is logged and listed in `/api/state`'s `recovered`, which the window tells once (`recoveredOnce`). The `.bak` lags one write behind on purpose: a crash zeroes the latest write, so a copy made with it could be zeroed too. With no good `.bak` the file is unknown, never empty: a sign-out leaves `plugin-auth.json` or `mcp-signins.json` as it is (magpie's own returns the error), and a sign-in added copies the file aside before it writes.
- A Windows machine that went down mid-write left `logins.json` and `plugin-auth.json` at their full length, every byte zero (#1505): the rename reached the disk before the data. Every write of magpie's own state goes through `steady.WriteFile` (or `edit.WriteAtomic`), which flushes the temp file before renaming it in, and the plugin host's `writeDurable` does the same. So does every write of an agent's own sign-in (#2239): `codexToken`'s rotated tokens into Codex's `auth.json` (`~/.codex`, or `$CODEX_HOME` when set; its keychain item instead when Codex keeps the sign-in there) and `writeClaudeCredential`'s `.credentials.json` go through `writePrivate`, never a truncating `os.WriteFile`, so a machine going down mid-write leaves the old sign-in whole, and on Windows a file another program holds for a moment is waited out (`steady.Rename`) instead of the rotation being dropped while the refresh token on the disk is spent. A file that is there but doesn't read on a cold start is read from its `.bak` (`lastgood.Read`/`Fallback`): `logins.json`, `providers.json`, `migrations.json`, `settings.json`, `profiles.json`, `plugins.json`, `plugin-auth.json` and `mcp-signins.json`. `caller-keys.json` is flushed the same way but never read from a `.bak`: a key revoked in the last write would come back, so a store that doesn't read still refuses every key. The recovery is logged and listed in `/api/state`'s `recovered`, which the window tells once (`recoveredOnce`). The `.bak` lags one write behind on purpose: a crash zeroes the latest write, so a copy made with it could be zeroed too. With no good `.bak` the file is unknown, never empty: a sign-out leaves `plugin-auth.json` or `mcp-signins.json` as it is (magpie's own returns the error), and a sign-in added copies the file aside before it writes.
- A state file whose reader takes one that doesn't unmarshal into its type as empty is copied aside before it is written over (`lastgood.KeepUnparsed` with `lastgood.Into[T]`, #2263): valid JSON of another shape, `[]` for a map, counts as not parsing. A copy that can't be made stops the write. These are `stash.json`, `applied.json` and `wsl.json` ([agent](../../internal/agent/)), `sessions-wsl.json` and `gateway-sessions-hidden.json` ([sessions](../../internal/sessions/)), `stepfun-auth.json`, `login-returns.json`, `quota-history.json`, `balance-history.json` and `credits-daily.json` ([provider](../../internal/provider/)), `claude-desktop.tiers.json`, `plugin-updates.json`, `usage-computer.json` and `sync-state.json`. Caches magpie fills again by itself (last quota readings, check-in and warm-up marks, plugin icons, npm and GitHub lookups, client shapes, seats, alert marks, `served.json`, `bun/state.json`) are still written over: losing one costs a refetch or a repeated notice.
- The gateway and a magpie run from a terminal change the same files (#1674). `loginsMu` is a [`filelock.Mutex`](../../internal/filelock/filelock.go): besides the mutex it holds an OS lock on `logins.json.lock` (flock, `LockFileEx` on Windows), and taking it has `logins.json` read afresh (`filememo.Look`), so every read a change is made from sees what another magpie wrote, and a refresh the gateway wrote is never written back over. `savedTokenMu` holds `logins.json.renew.lock` the same way, so two magpies never spend one refresh token. `caller-keys.json` (`access`) and `mcp-signins.json` (`mcpauth`, with `mcp-signins.json.renew.lock` around a renewal) are changed under such locks too; `plugin-auth.json` already was, under `plugin-auth.json.lock`, which `host.js` takes too. A lock another magpie holds is waited for up to `filelock.Wait` (10s), then gone on without, as before there was one. `rememberLogins` writes nothing when only `Seen` would move on and the saved one is less than `seenEvery` (10 minutes) old, so a run that only lists accounts (`magpie ls`, `providers`, `sessions`, `usage`) leaves `logins.json` as it is. [`logins_lock_test.go`](../../internal/provider/logins_lock_test.go) covers both, the second with another test process writing between this one's read and write.
- The account Codex or Claude Code is signed in to can be paused (`SetLoginOn` off, #263) only while another of its accounts is on. The gateway then sends it nothing: Codex's own-model turns go through routing, which passes over it (`OwnPaused`), and a native compaction (`/responses/compact`) goes to the first account on that isn't resting, signed as that account (`compactOn` in [codex_backend.go](../../internal/gateway/codex_backend.go)). The last other account off, the paused one is used again. A switched-off Codex provider is not a pause: Codex's own-model requests still relay on its sign-in as they came.
+4 -2
View File
@@ -1792,8 +1792,10 @@ func codexChatGPT(dir string) bool {
Access string `json:"access_token"`
} `json:"tokens"`
}
b, err := os.ReadFile(filepath.Join(dir, "auth.json"))
if err != nil || json.Unmarshal(b, &a) != nil {
// auth.json, or the macOS keychain item when Codex's config.toml
// keeps the sign-in there (#2367)
b, ok := provider.CodexSignIn(dir)
if !ok || json.Unmarshal(b, &a) != nil {
return false
}
return a.Tokens.Access != ""
+39
View File
@@ -0,0 +1,39 @@
package agent
import (
"io/fs"
"path/filepath"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// #2367 (Dony2050): Codex keeping its ChatGPT sign-in in the macOS
// keychain has no auth.json. It is wired and told as signed in to ChatGPT
// all the same, from the item (a fake: no test reads the real keychain);
// an API key kept there is told as a key.
func TestCodexSignInInKeychain(t *testing.T) {
home, _ := codexHome(t, "", "cli_auth_credentials_store = \"keyring\"\n")
dir := filepath.Join(home, ".codex")
item := ""
defer provider.CodexKeychainForTest(func(service, account string) ([]byte, error) {
if service != "Codex Auth" || item == "" {
return nil, fs.ErrNotExist
}
return []byte(item), nil
})()
a := &Agent{ID: "codex", Path: filepath.Join(dir, "config.toml")}
if codexChatGPT(dir) || a.Source() != "" {
t.Fatalf("no item: signed in (%q)", a.Source())
}
item = `{"auth_mode":"chatgpt","tokens":{"access_token":"x","account_id":"acc-1"}}`
provider.ForgetAccounts()
if !codexChatGPT(dir) || a.Source() != "chatgpt" {
t.Fatalf("the item's ChatGPT sign-in wasn't seen: %q", a.Source())
}
item = `{"auth_mode":"apikey","OPENAI_API_KEY":"sk-x"}`
provider.ForgetAccounts()
if a.Source() != "key" {
t.Fatalf("the item's key wasn't seen: %q", a.Source())
}
}
+5 -1
View File
@@ -14,6 +14,7 @@ import (
"github.com/yetone/magpie/internal/edit"
"github.com/yetone/magpie/internal/proc"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
)
@@ -61,7 +62,10 @@ func (a *Agent) Source() string {
if codexChatGPT(dir) {
return "chatgpt"
}
if v, _ := edit.GetJSON(filepath.Join(dir, "auth.json"), "OPENAI_API_KEY"); v != "" {
var k struct {
Key string `json:"OPENAI_API_KEY"`
}
if b, ok := provider.CodexSignIn(dir); ok && json.Unmarshal(b, &k) == nil && k.Key != "" {
return "key"
}
case "opencode", "mimocode", "deveco":
+53 -25
View File
@@ -971,8 +971,10 @@ func codexAccount(home string) (Provider, bool) {
if settings.AccountDiscoveryOff() {
return Provider{}, false
}
path := filepath.Join(appdir.CodexHomeIn(home), "auth.json")
b, err := readAccountFile(path)
dir := appdir.CodexHomeIn(home)
// where Codex's config.toml keeps it: auth.json, or the macOS
// keychain item (#2367)
b, _, err := readCodexLogin(dir, false)
var a codexAuth
if err != nil || json.Unmarshal(b, &a) != nil || a.Tokens.AccessToken == "" || a.AuthMode == "apikey" {
return Provider{}, false
@@ -987,7 +989,7 @@ func codexAccount(home string) (Provider, bool) {
// the email is "email · Team · <workspace>" (#1424)
acct.User = codexLiveName(acct.User, bytes.TrimSpace(b))
}
acct.sign = codexSign(func(ctx context.Context) (string, string, error) { return codexToken(ctx, path) })
acct.sign = codexSign(func(ctx context.Context) (string, string, error) { return codexToken(ctx, dir) })
acct.body = codexBody
acct.models = catalog.Codex
acct.fetch = func(ctx context.Context) ([]catalog.Model, error) {
@@ -1003,46 +1005,72 @@ func codexAccount(home string) (Provider, bool) {
return Provider{ID: "codex", Name: "Codex", Icon: "codex-color", Responses: CodexBase, Website: "https://chatgpt.com/codex", Account: acct}, true
}
// codexToken returns a usable access token, refreshing it through OpenAI
// when it is about to expire. A refresh rotates the tokens, so the new
// ones go back into auth.json for Codex CLI to find.
func codexToken(ctx context.Context, path string) (tok, accountID string, err error) {
// codexToken returns a usable access token for the Codex home dir,
// refreshing it through OpenAI when it is about to expire. A refresh
// rotates the tokens, so the new ones go back where Codex keeps its
// sign-in (auth.json or the keychain item, codexStore.write) for Codex to
// find.
func codexToken(ctx context.Context, dir string) (tok, accountID string, err error) {
codexMu.Lock()
defer codexMu.Unlock()
b, st, err := readCodexLogin(dir, false)
var a codexAuth
if !readJSON(path, &a) || a.Tokens.AccessToken == "" {
return "", "", errors.New("Codex is signed out; run codex login")
if err == nil && json.Unmarshal(b, &a) == nil && a.Tokens.AccessToken != "" {
if exp, _ := jwtClaims(a.Tokens.AccessToken)["exp"].(float64); exp == 0 || time.Until(time.Unix(int64(exp), 0)) > 5*time.Minute {
return a.Tokens.AccessToken, codexAccountID(a), nil
}
// about to be refreshed: the store's own, not a kept read, which
// Codex may have rotated since (its refresh token spent)
if st.keychain {
b, st, err = readCodexLogin(dir, true)
a = codexAuth{}
if err == nil && json.Unmarshal(b, &a) == nil && a.Tokens.AccessToken != "" {
if exp, _ := jwtClaims(a.Tokens.AccessToken)["exp"].(float64); exp == 0 || time.Until(time.Unix(int64(exp), 0)) > 5*time.Minute {
return a.Tokens.AccessToken, codexAccountID(a), nil
}
}
}
}
accountID = a.Tokens.AccountID
if accountID == "" {
accountID = claimString(jwtClaims(a.Tokens.IDToken), "https://api.openai.com/auth", "chatgpt_account_id")
}
if exp, _ := jwtClaims(a.Tokens.AccessToken)["exp"].(float64); exp == 0 || time.Until(time.Unix(int64(exp), 0)) > 5*time.Minute {
return a.Tokens.AccessToken, accountID, nil
var se *codexStoreError
if errors.As(err, &se) {
return "", "", se
}
var raw map[string]any
if !readJSON(path, &raw) {
if err != nil || a.Tokens.AccessToken == "" || json.Unmarshal(b, &raw) != nil {
return "", "", errors.New("Codex is signed out; run codex login")
}
accountID = codexAccountID(a)
tok, err = codexRefresh(ctx, raw)
if err != nil {
return "", "", err
}
// keep every other field of the file as Codex CLI wrote it. The file
// is the user's own sign-in, which Codex CLI and the Codex app read:
// written beside it, flushed and renamed in, never truncated in place,
// so a machine going down mid-write leaves the old one whole and a
// file held for a moment on Windows is waited out (#2239, #1505). A
// write that still fails loses the rotation, said in the log; the
// fresh access token in hand still serves this request.
// keep every other field as Codex wrote it. auth.json is the user's
// own sign-in, which Codex CLI and the Codex app read: written beside
// it, flushed and renamed in, never truncated in place, so a machine
// going down mid-write leaves the old one whole and a file held for a
// moment on Windows is waited out (#2239, #1505). A write that still
// fails loses the rotation, said in the log; the fresh access token in
// hand still serves this request.
if out, err := json.MarshalIndent(raw, "", " "); err == nil {
if werr := writePrivate(path, append(out, '\n')); werr != nil {
log.Printf("codex: the refreshed sign-in didn't reach %s: %v", path, werr)
if werr := st.write(out); werr != nil {
where := st.file()
if st.keychain {
where = "the keychain item " + codexKeychainService
}
log.Printf("codex: the refreshed sign-in didn't reach %s: %v", where, werr)
}
}
return tok, accountID, nil
}
// codexAccountID is the ChatGPT account a sign-in's requests name.
func codexAccountID(a codexAuth) string {
if a.Tokens.AccountID != "" {
return a.Tokens.AccountID
}
return claimString(jwtClaims(a.Tokens.IDToken), "https://api.openai.com/auth", "chatgpt_account_id")
}
// codexRefresh renews the tokens of an auth.json-shaped sign-in in place,
// every other field left as it was, and returns the new access token.
func codexRefresh(ctx context.Context, raw map[string]any) (string, error) {
+7
View File
@@ -79,6 +79,11 @@ func isolate(t *testing.T) {
forgetClaudeCredential()
forgetClaudeStatus()
forgetDevinStatus()
// nor Codex's keychain item (#2367): a test's has nothing in it,
// whatever the system
oldCodexKeychain, oldCodexHere := codexKeychain, codexKeychainHere
codexKeychain = &fakeKeychain{}
forgetCodexKeychain()
// nor an account's allowance another test read, which LoginUsage and
// the Usage page share
loginUsageCache.Lock()
@@ -95,6 +100,8 @@ func isolate(t *testing.T) {
t.Cleanup(func() {
claudeKeychain, claudeBase, claudeExecutable = oldKeychain, oldBase, oldExe
cursorKeychain, DevinExecutable = oldCursor, oldDevin
codexKeychain, codexKeychainHere = oldCodexKeychain, oldCodexHere
forgetCodexKeychain()
forgetClaudeCredential()
forgetClaudeStatus()
forgetDevinStatus()
+1 -1
View File
@@ -249,7 +249,7 @@ func codexUserToken(ctx context.Context, user string) (who, tok, accountID strin
// the one signed in now, read from Codex's own file: the list of those
// kept may not have caught up with it yet
if live, ok := liveLogin("codex"); user == "" || ok && strings.EqualFold(live.User, user) {
tok, accountID, err = codexToken(ctx, codexAuthPath())
tok, accountID, err = codexToken(ctx, codexHome())
return live.User, tok, accountID, err
}
for _, l := range Logins("codex") {
+2 -2
View File
@@ -48,7 +48,7 @@ func fakeCodexResets(t *testing.T, count int, details any) *atomic.Int32 {
func TestCodexResetsCounted(t *testing.T) {
home := signIn(t)
auth := home + "/.codex/auth.json"
dir := home + "/.codex"
soon := "2026-10-03T14:30:00Z"
later := "2026-11-01T00:00:00Z"
for _, c := range []struct {
@@ -82,7 +82,7 @@ func TestCodexResetsCounted(t *testing.T) {
} {
t.Run(c.name, func(t *testing.T) {
asked := fakeCodexResets(t, c.count, c.details)
q := codexSubscriptionUsage(context.Background(), auth)
q := codexSubscriptionUsage(context.Background(), dir)
if q.Error != "" || len(q.Windows) != 1 {
t.Fatalf("quota %+v", q)
}
+459
View File
@@ -0,0 +1,459 @@
package provider
// Codex's own sign-in, where Codex keeps it (#2367, #2312, Dony2050).
//
// Codex 0.162's config.toml says where (codex-rs/login/src/auth/storage.rs,
// codex-rs/config/src/types.rs): cli_auth_credentials_store "file" (the
// default) is auth.json in CODEX_HOME; "keyring" is the system keychain
// alone; "auto" is the keychain, else auth.json, read and saved in that
// order; "ephemeral" is Codex's memory. With [features]
// secret_auth_storage on (the default on Windows), keyring and auto mean
// Codex's encrypted auth storage instead of the keychain item.
//
// magpie reads and writes the keychain item on macOS only, through
// `security` as it does Claude Code's (readClaudeKeychainItem): the
// generic password of service "Codex Auth" and account
// "cli|<first 16 hex of SHA-256 of the canonical CODEX_HOME>", holding
// auth.json's JSON on one line. Elsewhere, and for the encrypted
// storage, the store is one magpie doesn't read: keyring reads as
// unknown, auto as auth.json, which is what Codex falls back to.
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io/fs"
"os"
"os/exec"
"path/filepath"
"runtime"
"sync"
"time"
toml "github.com/pelletier/go-toml/v2"
"github.com/yetone/magpie/internal/filememo"
"github.com/yetone/magpie/internal/proc"
)
const codexKeychainService = "Codex Auth"
// keychain is the system keychain as magpie reaches an item in it. Find
// gives fs.ErrNotExist for no item; Remove, nil. Tests put a fake in
// codexKeychain: no test reaches the user's own keychain.
type keychain interface {
Find(service, account string) ([]byte, error)
Put(service, account string, secret []byte) error
Remove(service, account string) error
}
var (
codexKeychain keychain = securityKeychain{}
// codexKeychainHere: the keychain item is magpie's to read on this
// system (macOS); a var so tests run the macOS path everywhere
codexKeychainHere = runtime.GOOS == "darwin"
// secretAuthStorageDefault is Codex's default for [features]
// secret_auth_storage: cfg!(windows) (codex-rs/features/src/lib.rs)
secretAuthStorageDefault = runtime.GOOS == "windows"
)
// keychainWait bounds one `security` run: one waiting on a keychain
// prompt nobody answers would hold whoever asked.
var keychainWait = 10 * time.Second
var errKeychainUnread = errors.New("the keychain didn't give it to magpie (refused, or no answer)")
// securityKeychain is macOS' `security`, as readClaudeKeychainItem and
// writeClaudeCredential run it. Neither its output nor its arguments go
// into an error: both can hold the credential.
type securityKeychain struct{}
func (securityKeychain) Find(service, account string) ([]byte, error) {
ctx, cancel := context.WithTimeout(context.Background(), keychainWait)
defer cancel()
out, err := proc.CommandContext(ctx, "security", "find-generic-password", "-s", service, "-a", account, "-w").Output()
if err != nil {
if keychainItemMissing(err) {
return nil, fs.ErrNotExist
}
return nil, errKeychainUnread
}
b, _ := keychainText(bytes.TrimSpace(out))
return b, nil
}
func (securityKeychain) Put(service, account string, secret []byte) error {
ctx, cancel := context.WithTimeout(context.Background(), keychainWait)
defer cancel()
if err := proc.CommandContext(ctx, "security", "add-generic-password", "-U", "-s", service, "-a", account, "-w", string(secret)).Run(); err != nil {
return errors.New("the keychain didn't take the sign-in")
}
return nil
}
func (securityKeychain) Remove(service, account string) error {
ctx, cancel := context.WithTimeout(context.Background(), keychainWait)
defer cancel()
if err := proc.CommandContext(ctx, "security", "delete-generic-password", "-s", service, "-a", account).Run(); err != nil && !keychainItemMissing(err) {
return errors.New("the keychain didn't remove the sign-in")
}
return nil
}
// keychainItemMissing: `security` exits 44 for errSecItemNotFound.
func keychainItemMissing(err error) bool {
var exit *exec.ExitError
return errors.As(err, &exit) && exit.ExitCode() == 44
}
// codexKeychainAccount is Codex's compute_store_key: the home made
// canonical where it can be (else as given), SHA-256, its first 16 hex
// digits after "cli|".
func codexKeychainAccount(home string) string {
p := home
if abs, err := filepath.Abs(home); err == nil {
if real, err := filepath.EvalSymlinks(abs); err == nil {
p = real
}
}
sum := sha256.Sum256([]byte(p))
return "cli|" + hex.EncodeToString(sum[:])[:16]
}
// codexStoreSetting is what config.toml in a Codex home says of where
// the sign-in is kept.
type codexStoreSetting struct {
Mode string // file, keyring, auto or ephemeral
Secrets bool // [features] secret_auth_storage
}
// readCodexStoreSetting reads config.toml as Codex does: no file or no
// key is "file". A file that doesn't parse, or a value Codex doesn't
// know (it would refuse to start), is an error: where the sign-in is
// isn't known.
func readCodexStoreSetting(home string) (codexStoreSetting, error) {
path := filepath.Join(home, "config.toml")
s, err := filememo.Read("codex credential store", path, func(b []byte) (codexStoreSetting, error) {
var c struct {
Store string `toml:"cli_auth_credentials_store"`
Features map[string]any `toml:"features"`
}
if err := toml.Unmarshal(b, &c); err != nil {
return codexStoreSetting{}, fmt.Errorf("%s doesn't read as TOML", path)
}
s := codexStoreSetting{Mode: c.Store, Secrets: secretAuthStorageDefault}
if v, ok := c.Features["secret_auth_storage"].(bool); ok {
s.Secrets = v
}
return s, nil
})
if errors.Is(err, fs.ErrNotExist) {
return codexStoreSetting{Mode: "file", Secrets: secretAuthStorageDefault}, nil
}
if err != nil {
return codexStoreSetting{}, err
}
switch s.Mode {
case "":
s.Mode = "file"
case "file", "keyring", "auto", "ephemeral":
default:
return codexStoreSetting{}, fmt.Errorf("cli_auth_credentials_store = %q in %s isn't one Codex knows", s.Mode, path)
}
return s, nil
}
// keychainItem: the store is the keychain item magpie reads.
func (s codexStoreSetting) keychainItem() bool {
return (s.Mode == "keyring" || s.Mode == "auto") && !s.Secrets && codexKeychainHere
}
// where names the store keyring and auto mean here.
func (s codexStoreSetting) where() string {
switch {
case s.Secrets:
return "Codex's encrypted auth storage (features.secret_auth_storage)"
case runtime.GOOS == "darwin" || codexKeychainHere:
return "the macOS keychain"
}
return "the system keychain"
}
// codexStoreError: Codex keeps its sign-in where magpie couldn't read it,
// so whether it is signed in, and to whom, isn't known.
type codexStoreError struct {
Setting codexStoreSetting
Config string
Cause error // nil: a store magpie doesn't read on this system
}
func (e *codexStoreError) Error() string {
if e.Setting.Mode == "ephemeral" {
return fmt.Sprintf("Codex keeps its sign-in in its own memory (cli_auth_credentials_store = \"ephemeral\" in %s), which no other program can read", e.Config)
}
if e.Cause != nil {
return fmt.Sprintf("Codex keeps its sign-in in %s (cli_auth_credentials_store = %q in %s), and %v", e.Setting.where(), e.Setting.Mode, e.Config, e.Cause)
}
return fmt.Sprintf("Codex keeps its sign-in in %s (cli_auth_credentials_store = %q in %s), which magpie doesn't read", e.Setting.where(), e.Setting.Mode, e.Config)
}
// codexStore is where a Codex sign-in was read from, so that a refresh
// writes its rotated tokens back there.
type codexStore struct {
home string
keychain bool
}
func (s codexStore) file() string { return filepath.Join(s.home, "auth.json") }
// codexKeychainCache keeps what the keychain gave for a home: each read is
// a `security` run, which may put a prompt in front of the user, and
// every request and page reads the sign-in. A refusal or no answer is
// kept longer, so that a prompt isn't put up again at once (as Copilot's,
// copilotSecret). codexKeychainMu has one `security` ask at a time: two
// readers at once would put up two prompts.
var (
codexKeychainMu sync.Mutex
codexKeychainCache = map[string]codexKeychainRead{}
)
type codexKeychainRead struct {
b []byte
err error
at time.Time
}
const (
codexKeychainTTL = 10 * time.Second
codexKeychainRefused = 10 * time.Minute
)
// findCodexKeychain reads the item for home; fresh asks the keychain
// whatever was kept, for a read whose tokens will be spent or saved.
func findCodexKeychain(home string, fresh bool) ([]byte, error) {
account := codexKeychainAccount(home)
codexKeychainMu.Lock()
defer codexKeychainMu.Unlock()
if r, ok := codexKeychainCache[account]; ok && !fresh {
ttl := codexKeychainTTL
if r.err != nil && !errors.Is(r.err, fs.ErrNotExist) {
ttl = codexKeychainRefused
}
if time.Since(r.at) < ttl {
return r.b, r.err
}
}
b, err := codexKeychain.Find(codexKeychainService, account)
if err == nil {
var obj map[string]json.RawMessage
if json.Unmarshal(b, &obj) != nil || obj == nil {
b, err = nil, errors.New("the keychain item isn't a Codex sign-in magpie can read")
}
}
codexKeychainCache[account] = codexKeychainRead{b: b, err: err, at: time.Now()}
return b, err
}
func keepCodexKeychain(home string, b []byte) {
codexKeychainMu.Lock()
codexKeychainCache[codexKeychainAccount(home)] = codexKeychainRead{b: b, at: time.Now()}
codexKeychainMu.Unlock()
}
// forgetCodexKeychain has the next read ask the keychain.
func forgetCodexKeychain() {
codexKeychainMu.Lock()
clear(codexKeychainCache)
codexKeychainMu.Unlock()
}
// readCodexLogin is Codex's sign-in under home as Codex would load it,
// and where it came from. fs.ErrNotExist (wrapped or not): signed out,
// as far as magpie can see. *codexStoreError: kept where magpie couldn't
// read it, so not known. A config.toml that doesn't read leaves auth.json
// read as before there was a setting (Codex itself wouldn't start), and
// nothing is saved over it (saveCodexLogin).
func readCodexLogin(home string, fresh bool) ([]byte, codexStore, error) {
st := codexStore{home: home}
if discoveryOff() {
return nil, st, errAccountDiscoveryOff
}
s, err := readCodexStoreSetting(home)
if err != nil {
b, err := readAccountFile(st.file())
return b, st, err
}
cfg := filepath.Join(home, "config.toml")
switch {
case s.Mode == "ephemeral":
return nil, st, &codexStoreError{Setting: s, Config: cfg}
case s.keychainItem():
b, kerr := findCodexKeychain(home, fresh)
if kerr == nil {
st.keychain = true
return b, st, nil
}
if s.Mode == "keyring" {
if errors.Is(kerr, fs.ErrNotExist) {
return nil, st, kerr
}
return nil, st, &codexStoreError{Setting: s, Config: cfg, Cause: kerr}
}
// auto: the file, as Codex falls back to it on no item and on an
// item it couldn't load
b, err := readAccountFile(st.file())
if err != nil && !errors.Is(kerr, fs.ErrNotExist) {
// Codex, which the item lets in, may well be signed in
return nil, st, &codexStoreError{Setting: s, Config: cfg, Cause: kerr}
}
return b, st, err
case s.Mode == "keyring":
return nil, st, &codexStoreError{Setting: s, Config: cfg}
case s.Mode == "auto":
// a store magpie doesn't read: auth.json is there only when Codex
// is on its fallback (a save to the store removes it)
b, err := readAccountFile(st.file())
if errors.Is(err, fs.ErrNotExist) {
return nil, st, &codexStoreError{Setting: s, Config: cfg}
}
return b, st, err
}
b, err := readAccountFile(st.file())
return b, st, err
}
// write puts a sign-in back where it was read from: rotated tokens, every
// other field as it was. The keychain item takes it on one line, as Codex
// writes it; `security -w` prints one with a newline as hex (#70).
func (s codexStore) write(b []byte) error {
if discoveryOff() {
return errAccountDiscoveryOff
}
if !s.keychain {
// the user's own sign-in, which Codex CLI and the Codex app
// read: written beside it, flushed and renamed in, never
// truncated in place (#2239, #1505)
return writePrivate(s.file(), append(bytes.TrimSpace(b), '\n'))
}
var one bytes.Buffer
if err := json.Compact(&one, b); err != nil {
return errors.New("the Codex sign-in to save isn't JSON")
}
if err := codexKeychain.Put(codexKeychainService, codexKeychainAccount(s.home), one.Bytes()); err != nil {
forgetCodexKeychain()
return err
}
keepCodexKeychain(s.home, one.Bytes())
return nil
}
// saveCodexLogin makes b the sign-in Codex goes by (a switch, or the
// first sign-in in magpie), in the store its config.toml names. The
// store's own sign-in is read first, never taken for absent when it
// couldn't be read: one that wasn't read is never written over. auth.json
// left beside a keychain item is left to Codex, which removes it at its
// next save; the item goes first when it reads.
func saveCodexLogin(home string, b []byte) error {
if discoveryOff() {
return errAccountDiscoveryOff
}
s, err := readCodexStoreSetting(home)
if err != nil {
return fmt.Errorf("where Codex keeps its sign-in isn't known (%v); nothing was changed", err)
}
st := codexStore{home: home}
cfg := filepath.Join(home, "config.toml")
switch {
case s.Mode == "ephemeral":
return &codexStoreError{Setting: s, Config: cfg}
case s.keychainItem():
_, kerr := findCodexKeychain(home, true)
if kerr != nil && !errors.Is(kerr, fs.ErrNotExist) {
return &codexStoreError{Setting: s, Config: cfg, Cause: kerr}
}
st.keychain = true
werr := st.write(b)
if werr == nil || s.Mode == "keyring" || kerr == nil {
// an item that is there goes first with Codex: a file beside
// it would be passed over
return werr
}
// auto with no item, and the keychain not taking one: Codex
// saves to the file then, and loads it
st.keychain = false
case s.Mode == "keyring":
return &codexStoreError{Setting: s, Config: cfg}
case s.Mode == "auto":
// a store magpie doesn't read: only a Codex on its file fallback
// goes by auth.json
if _, err := os.Stat(st.file()); err != nil {
return &codexStoreError{Setting: s, Config: cfg}
}
}
return st.write(b)
}
// deleteCodexLogin signs Codex out, as `codex logout` does: the item
// for this home and auth.json both go (auto would fall back to the file).
// The item not removed, the file is left too.
func deleteCodexLogin(home string) error {
if discoveryOff() {
return errAccountDiscoveryOff
}
s, err := readCodexStoreSetting(home)
if err != nil {
return fmt.Errorf("where Codex keeps its sign-in isn't known (%v); nothing was changed", err)
}
cfg := filepath.Join(home, "config.toml")
switch {
case s.Mode == "ephemeral":
return &codexStoreError{Setting: s, Config: cfg}
case s.keychainItem():
err := codexKeychain.Remove(codexKeychainService, codexKeychainAccount(home))
forgetCodexKeychain()
if err != nil {
return err
}
case s.Mode == "keyring":
return &codexStoreError{Setting: s, Config: cfg}
}
defer filememo.Forget()
if err := os.Remove(filepath.Join(home, "auth.json")); err != nil && !errors.Is(err, fs.ErrNotExist) {
return err
}
return nil
}
// CodexSignIn is the sign-in Codex goes by under its home dir, from
// wherever its config.toml has it kept (readCodexLogin); ok is false for
// none, or one magpie couldn't read. Agents' wiring reads it here.
func CodexSignIn(dir string) (b []byte, ok bool) {
b, _, err := readCodexLogin(dir, false)
return b, err == nil
}
// CodexKeychainForTest has Codex's keychain item read through find (no
// item: fs.ErrNotExist) on every system, until restore.
func CodexKeychainForTest(find func(service, account string) ([]byte, error)) (restore func()) {
old, oldHere := codexKeychain, codexKeychainHere
codexKeychain, codexKeychainHere = findOnly(find), true
forgetCodexKeychain()
return func() {
codexKeychain, codexKeychainHere = old, oldHere
forgetCodexKeychain()
}
}
type findOnly func(service, account string) ([]byte, error)
func (f findOnly) Find(service, account string) ([]byte, error) { return f(service, account) }
func (findOnly) Put(string, string, []byte) error {
return errors.New("this test's keychain takes nothing")
}
func (findOnly) Remove(string, string) error {
return errors.New("this test's keychain removes nothing")
}
+341
View File
@@ -0,0 +1,341 @@
package provider
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"io/fs"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
)
// fakeKeychain is the system keychain for a test: no test reaches the
// user's own (isolate puts an empty one in).
type fakeKeychain struct {
mu sync.Mutex
items map[string][]byte // by account
findErr error // every Find answers it
putErr error
finds, puts int
removes int
findAccounts []string
}
func (k *fakeKeychain) Find(service, account string) ([]byte, error) {
k.mu.Lock()
defer k.mu.Unlock()
k.finds++
k.findAccounts = append(k.findAccounts, account)
if service != codexKeychainService {
return nil, errors.New("not Codex's service: " + service)
}
if k.findErr != nil {
return nil, k.findErr
}
b, ok := k.items[account]
if !ok {
return nil, fs.ErrNotExist
}
return append([]byte(nil), b...), nil
}
func (k *fakeKeychain) Put(service, account string, secret []byte) error {
k.mu.Lock()
defer k.mu.Unlock()
k.puts++
if k.putErr != nil {
return k.putErr
}
if k.items == nil {
k.items = map[string][]byte{}
}
k.items[account] = append([]byte(nil), secret...)
return nil
}
func (k *fakeKeychain) Remove(service, account string) error {
k.mu.Lock()
defer k.mu.Unlock()
k.removes++
delete(k.items, account)
return nil
}
func (k *fakeKeychain) item(account string) []byte {
k.mu.Lock()
defer k.mu.Unlock()
return k.items[account]
}
// codexInKeychain moves signIn's auth.json into a fake keychain item, as
// Codex 0.162 does with cli_auth_credentials_store = store: the item on
// one line, with a field magpie doesn't know, and auth.json gone.
func codexInKeychain(t *testing.T, home, store string) (*fakeKeychain, string) {
t.Helper()
dir := filepath.Join(home, ".codex")
b, err := os.ReadFile(filepath.Join(dir, "auth.json"))
if err != nil {
t.Fatal(err)
}
var m map[string]any
json.Unmarshal(b, &m)
m["agent_identity"] = map[string]any{"kept": "as is"}
one, _ := json.Marshal(m)
os.Remove(filepath.Join(dir, "auth.json"))
os.WriteFile(filepath.Join(dir, "config.toml"), []byte("cli_auth_credentials_store = \""+store+"\"\n"), 0o600)
k := &fakeKeychain{items: map[string][]byte{codexKeychainAccount(dir): one}}
codexKeychain, codexKeychainHere = k, true // isolate puts them back
forgetCodexKeychain()
return k, codexKeychainAccount(dir)
}
// Codex's account key is its compute_store_key: SHA-256 of the canonical
// CODEX_HOME, its first 16 hex digits after "cli|". A home reached
// through a link is the same item.
func TestCodexKeychainAccountIsCodexs(t *testing.T) {
real := t.TempDir()
link := filepath.Join(t.TempDir(), "codex-home")
if err := os.Symlink(real, link); err != nil {
t.Skip(err)
}
canon, _ := filepath.EvalSymlinks(real)
sum := sha256.Sum256([]byte(canon))
want := "cli|" + hex.EncodeToString(sum[:])[:16]
if got := codexKeychainAccount(real); got != want {
t.Fatalf("account %q, want %q", got, want)
}
if got := codexKeychainAccount(link); got != want {
t.Fatalf("through a link: %q, want %q", got, want)
}
// a home not there is hashed as given, as Codex does
gone := filepath.Join(real, "nothing-here")
sum = sha256.Sum256([]byte(gone))
if got := codexKeychainAccount(gone); got != "cli|"+hex.EncodeToString(sum[:])[:16] {
t.Fatalf("a home not there: %q", got)
}
}
// #2367 (Dony2050): Codex set to keep its sign-in in the keychain has no
// auth.json. Its account is found there all the same: the provider, its
// saved login, the session identity and the agent's wiring all go by it.
func TestCodexSignedInInKeychain(t *testing.T) {
for _, store := range []string{"keyring", "auto"} {
t.Run(store, func(t *testing.T) {
home := signIn(t)
k, account := codexInKeychain(t, home, store)
dir := filepath.Join(home, ".codex")
p, ok := codexAccount(home)
if !ok || p.Account.User != "me@example.com" {
t.Fatalf("no Codex provider from the keychain item: %v %+v", ok, p.Account)
}
if l, ok := liveLogin("codex"); !ok || l.User != "me@example.com" || !strings.Contains(string(l.Auth), "agent_identity") {
t.Fatalf("live login: %v %+v", ok, l)
}
if b, ok := CodexSignIn(dir); !ok || !strings.Contains(string(b), "access_token") {
t.Fatalf("CodexSignIn: %v %s", ok, b)
}
ids := currentSessionIdentities(dir)
if len(ids) == 0 || ids[0].Agent != "codex" || ids[0].User != "me@example.com" {
t.Fatalf("session identities %+v", ids)
}
if k.findAccounts[0] != account {
t.Fatalf("asked the keychain for %q, want %q", k.findAccounts[0], account)
}
if _, err := os.Stat(filepath.Join(dir, "auth.json")); !errors.Is(err, fs.ErrNotExist) {
t.Fatalf("auth.json written by reading: %v", err)
}
})
}
}
// auto with no item is auth.json, as Codex falls back to it; keyring with
// no item is signed out, whatever auth.json is left.
func TestCodexKeychainFallback(t *testing.T) {
home := signIn(t)
dir := filepath.Join(home, ".codex")
codexKeychain, codexKeychainHere = &fakeKeychain{}, true
os.WriteFile(filepath.Join(dir, "config.toml"), []byte("cli_auth_credentials_store = \"auto\"\n"), 0o600)
if _, ok := codexAccount(home); !ok {
t.Fatal("auto, no item: auth.json wasn't read")
}
os.WriteFile(filepath.Join(dir, "config.toml"), []byte("cli_auth_credentials_store = \"keyring\"\n"), 0o600)
forgetCodexKeychain()
if _, ok := codexAccount(home); ok {
t.Fatal("keyring, no item: auth.json left beside it was taken for the sign-in")
}
// auto, the keychain refusing: Codex reads the file then too
codexKeychain = &fakeKeychain{findErr: errKeychainUnread}
os.WriteFile(filepath.Join(dir, "config.toml"), []byte("cli_auth_credentials_store = \"auto\"\n"), 0o600)
forgetCodexKeychain()
if _, ok := codexAccount(home); !ok {
t.Fatal("auto, keychain refused: auth.json wasn't read")
}
}
// A refresh's rotated tokens go back into the item they came from, on one
// line, every other field kept; no auth.json is made.
func TestCodexKeychainRefreshWritesItem(t *testing.T) {
home := signIn(t)
dir := filepath.Join(home, ".codex")
k, account := codexInKeychain(t, home, "keyring")
var m map[string]any
json.Unmarshal(k.item(account), &m)
toks := m["tokens"].(map[string]any)
toks["access_token"] = fakeJWT(map[string]any{"exp": float64(time.Now().Add(time.Minute).Unix())})
toks["refresh_token"] = "r-work"
b, _ := json.Marshal(m)
k.items[account] = b
fakeCodexRefresh(t)
if tok, _, err := codexToken(context.Background(), dir); err != nil || tok == "" {
t.Fatalf("codexToken: %q %v", tok, err)
}
got := k.item(account)
if strings.Contains(string(got), "\n") || !strings.Contains(string(got), `"r-work-2"`) || !strings.Contains(string(got), `"agent_identity":{"kept":"as is"}`) {
t.Fatalf("item after the refresh: %s", got)
}
if _, err := os.Stat(filepath.Join(dir, "auth.json")); !errors.Is(err, fs.ErrNotExist) {
t.Fatalf("the refresh wrote auth.json: %v", err)
}
// the next read is the rotated one, not what was kept from before
if tok, _, err := codexToken(context.Background(), dir); err != nil || tok == "" || k.puts != 1 {
t.Fatalf("again: %q %v, %d puts", tok, err, k.puts)
}
}
// A switch puts the saved account into the item Codex reads, and keeps
// the one it replaces; a keychain that wouldn't say what is there has
// nothing written over it.
func TestCodexKeychainSwitch(t *testing.T) {
home := signIn(t)
dir := filepath.Join(home, ".codex")
rememberLogins(true)
codexSignIn(t, home, "work@example.com", "r-work")
rememberLogins(true)
k, account := codexInKeychain(t, home, "keyring")
if from, err := switchSavedLogin("codex", "me@example.com"); err != nil || from != "work@example.com" {
t.Fatalf("switch: %q %v", from, err)
}
if got := k.item(account); !strings.Contains(string(got), `"refresh_token":"r"`) {
t.Fatalf("the item after the switch: %s", got)
}
if _, err := os.Stat(filepath.Join(dir, "auth.json")); !errors.Is(err, fs.ErrNotExist) {
t.Fatalf("the switch wrote auth.json beside the item: %v", err)
}
saved := false
for _, l := range readLogins() {
if l.User == "work@example.com" && strings.Contains(string(l.Auth), "agent_identity") {
saved = true
}
}
if !saved {
t.Fatal("the account replaced wasn't saved as the keychain had it")
}
was := string(k.item(account))
k.findErr = errKeychainUnread
forgetCodexKeychain()
if _, err := switchSavedLogin("codex", "work@example.com"); err == nil {
t.Fatal("switched over a sign-in the keychain wouldn't give")
}
if k.puts != 1 || string(k.item(account)) != was {
t.Fatalf("written over a sign-in not read: %d puts", k.puts)
}
}
// Codex's encrypted auth storage (features.secret_auth_storage) and a
// system keychain magpie doesn't read are neither read nor written; one
// whose config.toml doesn't parse is read as auth.json, as before, and
// nothing is saved over it.
func TestCodexStoreNotReadIsLeftAlone(t *testing.T) {
home := signIn(t)
dir := filepath.Join(home, ".codex")
k, _ := codexInKeychain(t, home, "keyring")
login := []byte(`{"tokens":{"access_token":"x"}}`)
for name, config := range map[string]string{
"encrypted": "cli_auth_credentials_store = \"keyring\"\n[features]\nsecret_auth_storage = true\n",
"ephemeral": "cli_auth_credentials_store = \"ephemeral\"\n",
} {
os.WriteFile(filepath.Join(dir, "config.toml"), []byte(config), 0o600)
forgetCodexKeychain()
if _, ok := codexAccount(home); ok {
t.Errorf("%s: read as signed in", name)
}
if err := saveCodexLogin(dir, login); err == nil {
t.Errorf("%s: saved", name)
}
}
codexKeychainHere = false
os.WriteFile(filepath.Join(dir, "config.toml"), []byte("cli_auth_credentials_store = \"keyring\"\n"), 0o600)
if _, ok := codexAccount(home); ok {
t.Error("keychain not read here: read as signed in")
}
if err := saveCodexLogin(dir, login); err == nil {
t.Error("keychain not read here: saved")
}
if k.finds != 0 || k.puts != 0 {
t.Fatalf("the item was reached: %d finds, %d puts", k.finds, k.puts)
}
if _, err := os.Stat(filepath.Join(dir, "auth.json")); !errors.Is(err, fs.ErrNotExist) {
t.Fatalf("auth.json written: %v", err)
}
codexKeychainHere = true
os.WriteFile(filepath.Join(dir, "auth.json"), login, 0o600)
os.WriteFile(filepath.Join(dir, "config.toml"), []byte("cli_auth_credentials_store = [\n"), 0o600)
if b, ok := CodexSignIn(dir); !ok || string(b) != string(login) {
t.Fatalf("config.toml not parsed: auth.json not read: %s", b)
}
if err := saveCodexLogin(dir, []byte(`{"tokens":{"access_token":"y"}}`)); err == nil {
t.Fatal("saved while where Codex keeps it isn't known")
}
if b, _ := os.ReadFile(filepath.Join(dir, "auth.json")); string(b) != string(login) {
t.Fatalf("auth.json written over: %s", b)
}
}
// Every read is a `security` run, which may put a prompt in front of the
// user: reads close together ask once, and a refusal isn't asked again
// for minutes.
func TestCodexKeychainAskedSeldom(t *testing.T) {
home := signIn(t)
k, _ := codexInKeychain(t, home, "keyring")
for range 20 {
if _, ok := codexAccount(home); !ok {
t.Fatal("not read")
}
}
if k.finds != 1 {
t.Fatalf("%d keychain asks for 20 reads", k.finds)
}
k.findErr = errKeychainUnread
forgetCodexKeychain()
for range 20 {
codexAccount(home)
}
if k.finds != 2 {
t.Fatalf("a refusal asked again: %d asks", k.finds-1)
}
}
// Signing Codex out, as `codex logout`, takes the item and auth.json both.
func TestCodexKeychainSignOut(t *testing.T) {
home := signIn(t)
dir := filepath.Join(home, ".codex")
k, account := codexInKeychain(t, home, "auto")
os.WriteFile(filepath.Join(dir, "auth.json"), []byte(`{}`), 0o600)
if err := deleteCodexLogin(dir); err != nil {
t.Fatal(err)
}
if k.item(account) != nil {
t.Fatal("the item was left")
}
if _, err := os.Stat(filepath.Join(dir, "auth.json")); !errors.Is(err, fs.ErrNotExist) {
t.Fatalf("auth.json left: %v", err)
}
}
@@ -0,0 +1,55 @@
//go:build !windows
package provider
import (
"encoding/hex"
"errors"
"io/fs"
"os"
"path/filepath"
"strings"
"testing"
)
// securityKeychain reads `security` as macOS answers: exit 44 is no item,
// a password with a newline comes back as hex, and an error says neither
// the arguments nor the output, which can hold the sign-in. The program is
// a fake on PATH: no test runs the real one.
func TestSecurityKeychainAnswers(t *testing.T) {
bin := t.TempDir()
hexed := hex.EncodeToString([]byte("{\"tokens\":{\"access_token\":\"x\"}}\n"))
script := `#!/bin/sh
case "$1" in
find-generic-password)
case "$5" in
"cli|none") exit 44 ;;
"cli|hex") echo ` + hexed + `; exit 0 ;;
esac
echo "denied SECRET-OUT" >&2; exit 51 ;;
add-generic-password) echo "$@" >&2; exit 1 ;;
delete-generic-password) exit 44 ;;
esac
exit 2
`
if err := os.WriteFile(filepath.Join(bin, "security"), []byte(script), 0o755); err != nil {
t.Fatal(err)
}
t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
k := securityKeychain{}
if _, err := k.Find(codexKeychainService, "cli|none"); !errors.Is(err, fs.ErrNotExist) {
t.Fatalf("exit 44: %v, want no item", err)
}
if b, err := k.Find(codexKeychainService, "cli|hex"); err != nil || !strings.HasPrefix(string(b), `{"tokens"`) {
t.Fatalf("hex: %q %v", b, err)
}
if _, err := k.Find(codexKeychainService, "cli|refused"); err == nil || errors.Is(err, fs.ErrNotExist) || strings.Contains(err.Error(), "SECRET") {
t.Fatalf("refused: %v, want an error that isn't no item and says nothing it was given", err)
}
if err := k.Put(codexKeychainService, "cli|x", []byte(`{"SECRET-IN":1}`)); err == nil || strings.Contains(err.Error(), "SECRET") {
t.Fatalf("put: %v", err)
}
if err := k.Remove(codexKeychainService, "cli|x"); err != nil {
t.Fatalf("removing no item: %v", err)
}
}
+1 -1
View File
@@ -371,7 +371,7 @@ func warmCodexLogin(ctx context.Context, user string) error {
l := ls[i]
token := func(ctx context.Context) (string, string, error) { return savedLoginToken(ctx, "codex", l.User) }
if l.Active {
token = func(ctx context.Context) (string, string, error) { return codexToken(ctx, codexAuthPath()) }
token = func(ctx context.Context) (string, string, error) { return codexToken(ctx, codexHome()) }
}
model, effort, err := warmModel(l.User)
if err != nil {
+2 -2
View File
@@ -66,7 +66,7 @@ func TestCodexRefreshFlushesAuthJSONBeforeReplacingIt(t *testing.T) {
// a flush that fails leaves auth.json whole, and the request served
path, was := dueCodexAuth(t)
steady.Sync = func(*os.File) error { return errors.New("the disk went away") }
if tok, _, err := codexToken(context.Background(), path); err != nil || tok == "" {
if tok, _, err := codexToken(context.Background(), filepath.Dir(path)); err != nil || tok == "" {
t.Fatalf("codexToken: %q, %v", tok, err)
}
if b, err := os.ReadFile(path); err != nil || string(b) != string(was) {
@@ -91,7 +91,7 @@ func TestCodexRefreshFlushesAuthJSONBeforeReplacingIt(t *testing.T) {
flushed = true
return f.Sync()
}
if _, _, err := codexToken(context.Background(), path); err != nil {
if _, _, err := codexToken(context.Background(), filepath.Dir(path)); err != nil {
t.Fatal(err)
}
if !flushed {
@@ -3,6 +3,7 @@ package provider
import (
"context"
"os"
"path/filepath"
"strings"
"syscall"
"testing"
@@ -31,7 +32,7 @@ func TestCodexRefreshOutlastsAHeldAuthJSON(t *testing.T) {
syscall.CloseHandle(h)
}()
defer func() { <-released }()
if _, _, err := codexToken(context.Background(), path); err != nil {
if _, _, err := codexToken(context.Background(), filepath.Dir(path)); err != nil {
t.Fatal(err)
}
<-released
+3 -3
View File
@@ -397,7 +397,7 @@ func loginQuota(ctx context.Context, l Login) SubscriptionQuota {
switch {
case l.Agent == "claude": // Claude Code reads its own (claudeWindows)
case l.Active:
tok, accountID, err = codexToken(ctx, codexAuthPath())
tok, accountID, err = codexToken(ctx, codexHome())
default:
tok, accountID, err = savedLoginToken(ctx, l.Agent, l.User)
}
@@ -489,10 +489,10 @@ func loginReadingKnown(l Login) (loginUsageEntry, bool) {
}
// codexLoginAuth is the auth.json of a ChatGPT account magpie knows: the
// file Codex is signed in with, or the one kept for it.
// sign-in Codex goes by (auth.json or its keychain item), or the one kept for it.
func codexLoginAuth(l Login) []byte {
if l.Active {
b, _ := readAccountFile(codexAuthPath())
b, _, _ := readCodexLogin(codexHome(), false)
return b
}
loginsMu.Lock()
+36 -33
View File
@@ -25,8 +25,6 @@ import (
"sync"
"time"
toml "github.com/pelletier/go-toml/v2"
"github.com/yetone/magpie/internal/appdir"
"github.com/yetone/magpie/internal/edit"
"github.com/yetone/magpie/internal/filelock"
@@ -529,7 +527,7 @@ func codexAuthPath() string { return filepath.Join(appdir.CodexHome(), "auth.jso
// sign-in is a key's, and spends no account a gateway key's list
// governs.
func CodexAPIKeySignedIn() bool {
b, err := readAccountFile(codexAuthPath())
b, _, err := readCodexLogin(codexHome(), false)
if err != nil {
return false
}
@@ -618,43 +616,39 @@ func savedButSignedOut() []Exclusion {
if _, ok := liveLogin(a); ok {
continue
}
why, signIn := "nothing at "+codexAuthPath(), "codex login"
n := "1 account is"
if saved[a] > 1 {
n = fmt.Sprintf("%d accounts are", saved[a])
}
if store := codexCredentialsStore(); store == "keyring" || store == "auto" {
// Codex keeps its sign-in in the system keyring, which magpie
// doesn't read: it is signed in, only not where magpie looks
// (#2312, Dony2050)
out = append(out, Exclusion{Agent: a, SignedOut: true, Users: users[a],
Why: fmt.Sprintf("%s saved in magpie, and they are only offered beside the account Codex is signed in to. Codex keeps its sign-in in the system keychain (cli_auth_credentials_store = %q in %s), which magpie doesn't read: it reads only %s. Set cli_auth_credentials_store = \"file\" there and sign in again (codex login).", n, store, codexConfigPath(), codexAuthPath())})
continue
}
out = append(out, Exclusion{Agent: a, SignedOut: true, Users: users[a],
Why: fmt.Sprintf("%s saved in magpie, but it isn't signed in here (%s), and they are only offered beside the account it is signed in to. Sign in (%s) with this HOME.", n, why, signIn)})
Why: fmt.Sprintf("%s saved in magpie, and they are only offered beside the account Codex is signed in to. %s", n, codexSignedOutWhy())})
}
return out
}
// codexCredentialsStore is where Codex keeps its ChatGPT sign-in, as its
// config.toml's top-level cli_auth_credentials_store says: "file" (Codex's
// default, auth.json), "keyring", "auto" (the keyring when there is one) or
// "ephemeral"; "" when it isn't set or the file can't be read. Codex
// 0.162's keyring and auto save to the keyring and remove auth.json
// (codex-rs/login/src/auth/storage.rs).
func codexCredentialsStore() string {
b, err := os.ReadFile(codexConfigPath())
if err != nil {
return ""
// codexSignedOutWhy says why magpie sees no Codex sign-in: none where
// Codex's config.toml keeps it, or one kept where magpie couldn't read it
// (#2312, #2367, Dony2050), and what to do.
func codexSignedOutWhy() string {
_, _, err := readCodexLogin(codexHome(), false)
var se *codexStoreError
if !errors.As(err, &se) {
where := codexAuthPath()
if s, serr := readCodexStoreSetting(codexHome()); serr == nil && s.keychainItem() {
where = fmt.Sprintf("the keychain item %q for %s", codexKeychainService, codexHome())
if s.Mode == "auto" {
where += " nor " + codexAuthPath()
}
}
return fmt.Sprintf("Codex isn't signed in here (nothing in %s). Sign in (codex login) with this HOME.", where)
}
var c struct {
Store string `toml:"cli_auth_credentials_store"`
switch {
case se.Setting.Mode == "ephemeral":
return se.Error() + ". Set cli_auth_credentials_store = \"file\" there and sign in again (codex login)."
case se.Cause != nil:
return se.Error() + ". Allow magpie when macOS asks for the keychain, or set cli_auth_credentials_store = \"file\" there and sign in again (codex login)."
}
if toml.Unmarshal(b, &c) != nil {
return ""
}
return strings.ToLower(strings.TrimSpace(c.Store))
return se.Error() + fmt.Sprintf(": here it reads only %s. Set cli_auth_credentials_store = \"file\" there and sign in again (codex login).", codexAuthPath())
}
// liveLogin reads the account an agent is signed in to now.
@@ -664,7 +658,7 @@ func liveLogin(agent string) (savedLogin, bool) {
}
switch agent {
case "codex":
b, err := readAccountFile(codexAuthPath())
b, _, err := readCodexLogin(codexHome(), false)
if err != nil {
return savedLogin{}, false
}
@@ -1143,6 +1137,10 @@ func switchSavedLogin(agent, user string) (from string, _ error) {
// old one is dead (0xAncientTwo on X: signed out again and again)
forgetClaudeCredential()
}
if agent == "codex" {
// so for Codex's keychain item, which Codex may have refreshed
forgetCodexKeychain()
}
if live, ok := liveLogin(agent); ok {
if strings.EqualFold(live.User, want.User) {
return "", nil
@@ -1164,7 +1162,9 @@ func switchSavedLogin(agent, user string) (from string, _ error) {
var err error
switch agent {
case "codex":
err = writePrivate(codexAuthPath(), append(bytes.TrimSpace(want.Auth), '\n'))
// where Codex's config.toml keeps it (#2367); never over a sign-in
// there that couldn't be read
err = saveCodexLogin(codexHome(), want.Auth)
case "claude":
if err = putClaudeLogin(want); err == nil {
// Claude Code's own now: its only holder
@@ -1319,8 +1319,9 @@ func forgetLogin(agent, user string) (signedOut bool, err error) {
if agent != "codex" || other {
return false, &SignedInError{Agent: agent, User: user}
}
// as `codex logout` does: the sign-in's file goes, all of it
if err := os.Remove(codexAuthPath()); err != nil && !os.IsNotExist(err) {
// as `codex logout` does: the sign-in goes, all of it, from the
// keychain item and auth.json both (#2367)
if err := deleteCodexLogin(codexHome()); err != nil {
return false, err
}
signedOut = true
@@ -1379,6 +1380,8 @@ func ForgetAccounts() {
clear(newFetches.m)
newFetches.Unlock()
forgetAccountCaches()
// Codex's keychain item is asked again (#2367)
forgetCodexKeychain()
// the revoked sign-ins known are read from logins.json again
resetRevoked()
}
+13 -5
View File
@@ -125,13 +125,21 @@ func currentSessionIdentities(codexDir string) []SessionIdentity {
}
var out []SessionIdentity
// Cache only the identity parse, not another copy of the credential blob.
current, _ := filememo.Read("session codex identity", filepath.Join(codexDir, "auth.json"), func(b []byte) ([]SessionIdentity, error) {
if b, st, err := readCodexLogin(codexDir, false); err == nil && st.keychain {
// Codex keeps its sign-in in the keychain item (#2367); one
// auth.json left beside it isn't the one Codex goes by
if id, ok := codexSessionIdentity(b); ok {
return []SessionIdentity{id}, nil
out = append(out, id)
}
return nil, nil
})
out = append(out, current...)
} else {
current, _ := filememo.Read("session codex identity", filepath.Join(codexDir, "auth.json"), func(b []byte) ([]SessionIdentity, error) {
if id, ok := codexSessionIdentity(b); ok {
return []SessionIdentity{id}, nil
}
return nil, nil
})
out = append(out, current...)
}
if acct, ok := claudeProfileAccount(); ok {
b, _ := json.Marshal(acct)
if id, ok := claudeSessionIdentity(b); ok {
+37 -10
View File
@@ -41,21 +41,48 @@ func TestSavedButSignedOut(t *testing.T) {
if strings.Contains(codex.Why, "keychain") {
t.Fatalf("no keyring set, yet: %s", codex.Why)
}
// Codex set to keep its sign-in in the keychain (#2312): it is signed
// in, only not where magpie looks, and the reason says so, with how to
// put it where magpie looks
// Codex set to keep its sign-in in the keychain (#2312, #2367). Where
// magpie reads the item (macOS), an empty one is signed out, said of
// the item; a read the keychain refused is not known, and the reason
// says how to let magpie in. Where it doesn't (Linux, Windows, or
// Codex's encrypted auth storage), it is signed in only not where
// magpie looks, and the reason says how to put it there.
os.MkdirAll(filepath.Join(home, ".codex"), 0o700)
for _, store := range []string{"keyring", "auto"} {
os.WriteFile(filepath.Join(home, ".codex", "config.toml"), []byte("model = \"gpt-5.6\"\ncli_auth_credentials_store = \""+store+"\"\n\n[profiles.x]\nmodel = \"o3\"\n"), 0o600)
codex = nil
excluded := func() *Exclusion {
forgetCodexKeychain()
for _, x := range Excluded() {
if x.Agent == "codex" && x.SignedOut {
codex = &x
return &x
}
}
if codex == nil || len(codex.Users) != 2 || strings.Contains(codex.Why, "isn't signed in here") ||
!strings.Contains(codex.Why, `cli_auth_credentials_store = "`+store+`"`) || !strings.Contains(codex.Why, `cli_auth_credentials_store = "file"`) {
t.Fatalf("%s: %+v", store, codex)
return nil
}
defer func(k keychain, here bool) { codexKeychain, codexKeychainHere = k, here }(codexKeychain, codexKeychainHere)
for _, store := range []string{"keyring", "auto"} {
config := "model = \"gpt-5.6\"\ncli_auth_credentials_store = \"" + store + "\"\n\n[profiles.x]\nmodel = \"o3\"\n"
os.WriteFile(filepath.Join(home, ".codex", "config.toml"), []byte(config), 0o600)
codexKeychain, codexKeychainHere = &fakeKeychain{}, true
if codex = excluded(); codex == nil || len(codex.Users) != 2 || !strings.Contains(codex.Why, "isn't signed in here") ||
!strings.Contains(codex.Why, `keychain item "Codex Auth"`) {
t.Fatalf("%s, no item: %+v", store, codex)
}
codexKeychain = &fakeKeychain{findErr: errKeychainUnread}
if codex = excluded(); codex == nil || strings.Contains(codex.Why, "isn't signed in here") ||
!strings.Contains(codex.Why, "Allow magpie") || !strings.Contains(codex.Why, `cli_auth_credentials_store = "file"`) {
t.Fatalf("%s, item not read: %+v", store, codex)
}
codexKeychainHere = false
if codex = excluded(); codex == nil || len(codex.Users) != 2 || strings.Contains(codex.Why, "isn't signed in here") ||
!strings.Contains(codex.Why, `cli_auth_credentials_store = "`+store+`"`) || !strings.Contains(codex.Why, `cli_auth_credentials_store = "file"`) ||
!strings.Contains(codex.Why, "doesn't read") {
t.Fatalf("%s, keychain not read here: %+v", store, codex)
}
codexKeychainHere = true
os.WriteFile(filepath.Join(home, ".codex", "config.toml"), []byte(config+"\n[features]\nsecret_auth_storage = true\n"), 0o600)
if codex = excluded(); codex == nil || !strings.Contains(codex.Why, "encrypted auth storage") || strings.Contains(codex.Why, "isn't signed in here") {
t.Fatalf("%s, encrypted storage: %+v", store, codex)
}
}
os.WriteFile(filepath.Join(home, ".codex", "config.toml"), []byte("cli_auth_credentials_store = \"file\"\n"), 0o600)
+2 -1
View File
@@ -1012,7 +1012,8 @@ func addLogin(l savedLogin) (using bool, err error) {
if using {
switch l.Agent {
case "codex":
err = writePrivate(codexAuthPath(), append(bytes.TrimSpace(l.Auth), '\n'))
// where Codex's config.toml keeps it (#2367)
err = saveCodexLogin(codexHome(), l.Auth)
case "claude":
err = putClaudeLogin(l)
}
+5 -5
View File
@@ -454,8 +454,8 @@ func fetchSubscriptionUsage(ctx context.Context) []SubscriptionQuota {
if ls := accountsOf("codex"); len(ls) > 1 {
fetches = append(fetches, perLogin(via("codex"), ls, accountCard("codex"))...)
} else {
auth := filepath.Join(appdir.CodexHomeIn(home), "auth.json")
fetches = append(fetches, withUser(ctx, p.Account.User, func() SubscriptionQuota { return codexSubscriptionUsage(viaLogin("codex", p.Account.User), auth) }))
dir := appdir.CodexHomeIn(home)
fetches = append(fetches, withUser(ctx, p.Account.User, func() SubscriptionQuota { return codexSubscriptionUsage(viaLogin("codex", p.Account.User), dir) }))
}
}
// Every Copilot account magpie knows, the editors' or the CLI's own
@@ -912,19 +912,19 @@ func claudeScopeModel(name string) string {
return strings.NewReplacer(" ", "-", ".", "-").Replace(strings.ToLower(name))
}
func codexSubscriptionUsage(ctx context.Context, path string) SubscriptionQuota {
func codexSubscriptionUsage(ctx context.Context, dir string) SubscriptionQuota {
q := SubscriptionQuota{Provider: "codex", Name: "Codex", Icon: "codex-color", Windows: []QuotaWindow{}}
if holding(ctx) {
q.Error = errNotAsked.Error()
return q
}
token, accountID, err := codexToken(ctx, path)
token, accountID, err := codexToken(ctx, dir)
if err != nil {
q.Error = err.Error()
return q
}
q.Plan, q.Windows, q.Resets, q.Balance, q.Held, err = codexWindows(ctx, token, accountID)
if b, rerr := readAccountFile(path); rerr == nil {
if b, _, rerr := readCodexLogin(dir, false); rerr == nil {
q.Until = codexUntil(b, time.Now())
}
if err != nil {