Repository navigation
Make Claude credentials strictly read-only (no refresh, no writeback) - #84
Conversation
…e back Runway rotating Claude Code's OAuth refresh token (and writing it back to Claude's Keychain item / .credentials.json) can strand a concurrently running Claude process and trip the server's refresh-token reuse detection, revoking the whole session (2026-08-03 incident). Claude owns its credentials; Runway now only reads them. - Delete the /v1/oauth/token client, the writeback (ClaudeAuthStore.save), the credential-generation compare-and-swap, and the in-process SecItemUpdate machinery only that writeback used. - An expired or 401-rejected token now falls through the remaining sources and finally degrades to the local spend tiles under a "Claude login needs renewal" header notice instead of a hard error. - Local spend tiles, plan badge, and desktop fallback are unchanged.
There was a problem hiding this comment.
💡 Codex Review
runway/Sources/Runway/Providers/Claude/ClaudeProvider.swift
Lines 150 to 151 in 40ae516
When Claude Desktop is the only credential source and its cached token is stale, ClaudeDesktopAuthStore.load returns .stale without an OAuth candidate, so this branch is reached and publishes a hard error. That bypasses failureSnapshot and hides the still-valid local spend tiles, contrary to the new behavior documented for stale Desktop logins. Route this case through the local-usage warning path even though no renewalState is available.
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
… hard error Review finding: ClaudeDesktopAuthStore.load returns .stale with no credential state, so the empty-candidate branch produced an error-only card for Desktop-only users — skipping the local spend tiles the read-only model promises. failureSnapshot now degrades every renewal error; the credential state only feeds the optional plan badge.
…t-broken (#85) > Stacked on #84 (`claude-credentials-read-only`). **TL;DR**: Every *in-process* read of another app's Keychain item now goes through a small coordinator that only touches the secret when the item actually changed, shares one read between concurrent callers, and stops retrying an item after a denial until it changes or the user acts. (Runway's own item stays outside it — its ACL names Runway, so it never prompts or contends.) ## What was happening - Every 5-minute refresh (plus the default-account observer) performed a full ACL-checked secret read of Claude's Keychain item, even though the item rarely changes. - During the 2026-08-03 incident, securityd was wedged behind approval dialogs; Runway's repeated reads stacked onto it, its own refreshes blocked for 150 s, and there was no backoff — the next cycle piled on again. - Two Claude cards (default + extra account) could read concurrently with no coalescing. ## What this changes - New `KeychainReadCoordinator` (process-wide, injected into `SecurityKeychainAccessor`): - **Change-gated reads** — an attributes-only fingerprint probe (prompt-free, no ACL evaluation, microseconds) runs first; the secret is re-read only when the fingerprint moved (e.g. Claude Code rotated its token). One real read per rotation instead of one per cycle. - **Single-flight** — concurrent readers of the same service/account share one underlying read. A background caller waits at most 2 s on someone else's stuck read, then reports `.unavailable` instead of adding another blocked call to a wedged securityd. - **Circuit breaker** — after a denied/failed read (background or an explicitly denied manual prompt), background reads of that item are answered locally with no Keychain traffic until the item's fingerprint changes or a manual-refresh read succeeds. - Interactive (manual-refresh) reads always go through to securityd — they are the one place a prompt is legitimate — and seed the cache / clear the breaker on success. - Docs: keychain paragraph in `docs/providers/claude.md`. ## Heads-up - Cached secrets live in process memory only — the same lifetime as the credential states providers already hold between refreshes. - A `nil` fingerprint (item absent, or probe failed on a locked keychain) is never cached: it cannot distinguish those two cases, so such reads always go through. - The subprocess (`/usr/bin/security`) read path used by other providers is not coordinated here; it is in scope for the ownership follow-up (PR 3). ## Tests - Unit tests for the coordinator: cache hit on unchanged fingerprint, re-read on change, no caching without a fingerprint, breaker trip/reset, interactive success clearing the breaker, interactive denial tripping it, and a threaded single-flight/pile-up test. - A live login-keychain integration test: `SecItemUpdate` on a real item moves the fingerprint and the next read returns the fresh secret (skips where the keychain is unavailable). - `swift test`: 1,667 tests, 0 failures. --- ## Review follow-ups (later commits on this branch) - **The global UI gate is bounded in both directions.** `withUISuppressed` waited on an open approval dialog with no deadline, so an abandoned prompt could strand every concurrent refresh — the contention this gate exists to prevent. Past the deadline the body runs with `isSuppressed: false`, which by contract yields a local unavailable without touching Security.framework. - **Recovery probes hit the exact item.** Claude's probe was keyed `(service, nil)` while its read is keyed `(service, currentUser)`, so it neither waited on that flight nor saw its breaker. Added `genericPasswordForCurrentUserExists`. - **Claude Desktop and Sakana Safe Storage reads joined the coordinator** via a new `externalRead` entry point (they decode their own payloads, so they don't speak `NonInteractiveKeychainRead`). Denials throw from inside the flight so the breaker records them. - **The breaker covers metadata probes**, and a caller that times out behind a stuck flight serves a freshly recovered value rather than reporting unavailable. ### Scope note At this branch, subprocess (`/usr/bin/security`) readers still exist for the providers converted later in the stack — the coordinator covers the in-process path here, and #87/#89/#90 move the remaining providers onto it. Runway's own item (`RunwayOwnedKeychainStore`) stays outside by design: its ACL names Runway, so it never prompts or contends. ### Later review follow-ups on this branch - The suppressed side of the UI gate is bounded, so an abandoned approval dialog can't strand concurrent refreshes. - Recovery probes use the exact `(service, currentUser)` item, and a protected item ends the lookup instead of broadening to a service-wide read that could select another account's login. - Claude Desktop and Sakana Safe Storage reads run inside the coordinator (`externalRead`) with an epoch guard; every failing Security status trips the breaker.
…rets in-process (#86) > Stacked on #85 (`keychain-read-coordinator`), which is stacked on #84. **TL;DR**: The ownership rule — only the app that owns a credential may modify it — is now enforced by the type system, and the one secret Runway actually owns moves to in-process Keychain storage with no subprocess and no secret in an argument list. ## What was happening - Every store held the full read/write `KeychainAccessing` protocol, so nothing but discipline stopped a future change from writing another app's credential item — exactly the class of bug PR #84 removed for Claude. - Runway's own secret (the iCloud-sync device id) was written through `/usr/bin/security add-generic-password`, which passes the value through the subprocess argument list (briefly visible to `ps`) and ACL-binds the item to the helper binary instead of Runway. ## What this changes - Splits the Keychain protocol: `KeychainReading` (reads, probes, fingerprints) and `KeychainAccessing: KeychainReading` (writes). Stores that consume another app's credentials — Claude auth store, config-dir discovery, default-account observer, Copilot, Antigravity — now hold only `KeychainReading`, making a foreign-store write a compile error. - Adds `RunwayOwnedKeychainStore` for Runway-owned secrets: in-process `SecItemAdd`/`SecItemCopyMatching`/`SecItemUpdate`, a Runway-specific account, silent reads (the creating process's ACL), no subprocess. - Migrates the iCloud-sync device id to a Runway-owned v2 item with a one-time copy from the v1 item, so existing devices keep their iCloud record instead of minting a duplicate. The v1 item stays behind orphaned (its ACL belongs to the subprocess, so Runway cannot silently delete it) and is never read again once v2 exists. - Docs: a "Credential ownership" section in `docs/architecture.md`. ## Heads-up - **Deviation from the original plan**: the plan said `kSecUseDataProtectionKeychain`. My first rationale for skipping it was wrong and has been corrected: release builds — and dev builds that find an iCloud provisioning profile — *are* signed with `com.apple.application-identifier` and `keychain-access-groups` (`script/render_icloud_entitlements.sh`), so the data-protection keychain would work there. The real constraint is that a plain local build signs with `Runway.local.entitlements.plist`, which carries neither; choosing per build flavor would split this item across two stores and mint a second iCloud sync identity for the same Mac. The login keychain behaves identically everywhere and already delivers what motivated the move (no subprocess, no argv exposure, app-owned ACL). An entitlement-gated migration with a copy-forward is viable follow-up. - Codex and Cursor still write their providers' stores (token rotation) and keep `KeychainAccessing`; extending the read-only ownership model to them is the planned follow-up after this stack, since it changes their refresh behavior the way #84 changed Claude's. ## Tests - Device-id migration: legacy v1 value is copied into the owned v2 item once and never consulted again; a missing id stays `nil`; dev/prod bundle scoping preserved. - `RunwayOwnedKeychainStore` round-trip + in-place update against a real login keychain (skips where unavailable). - The protocol split itself is compile-time enforcement; the existing Claude no-write regression tests from #84 still pass on top. - `swift test`: 1,678 tests, 0 failures. --- ## Review follow-up (later commit on this branch) - **The legacy device-id migration no longer mints a duplicate identity.** The existence gate used `== true`, so an *unknown* probe (locked keychain, suppressed UI) read as "no legacy item" — and with v2 and the saved preference both gone, `resolveDeviceID` minted a fresh UUID and published a **second iCloud device record** for a Mac that already had one. The probe is tri-state now: `false` migrates nothing (fresh install, no subprocess), unknown throws so the store surfaces its existing duplicate warning, `true` proceeds.
…sr/bin/security (#87) > Stacked on #86 (`credential-ownership-model`) → #85 → #84. Closes the gap a post-stack review found: the exact `/usr/bin/security find-generic-password` pattern behind the 2026-08-03 prompt loop was still live for Copilot (and Antigravity), including at launch. **TL;DR**: The read-only providers' Keychain reads (Copilot's `gh:github.com`, Antigravity's `gemini`/`antigravity`) now run in-process through the coordinator: automatic refreshes are prompt-free by construction, and only a manual refresh may raise the approval dialog — once, authorizing Runway itself. ## What was happening - `CopilotAuthStore` and `AntigravityAuthStore` read their foreign Keychain items through the `/usr/bin/security` subprocess — the prompt-capable path whose dialogs authorize the helper binary instead of Runway, so approvals never stick to the app and the prompt can recur every cycle. Launch-time credential detection used the same path. - The PR #85 coordinator only covered in-process reads, so these subprocess reads bypassed the fingerprint gate, single-flight, and circuit breaker entirely. ## What this changes - `KeychainReading` gains account-scoped `readGenericPasswordWithoutUserInteraction(service:account:)` and `readGenericPasswordAllowingUserInteraction(service:account:)`; `SecurityKeychainAccessor` serves both through the existing coordinated in-process path (change-gated, single-flight, circuit-broken). Mock defaults route them through the plain account read, so existing test fakes are untouched. - Copilot: `loadToken` / `loadBillingTokenCandidates` take `allowKeychainInteraction` (default false). Automatic refresh and `hasLocalCredentials` use the prompt-free form; a manual refresh uses the interactive form. A denied interactive read is not retried through the broader service-only lookup — that would just repeat the same prompt. - Antigravity: `loadKeychainToken` gets the same mode split; an unauthorized item on the automatic path surfaces the existing friendly "couldn't read credentials" error locally instead of prompting. - Docs: prompt behavior notes in `docs/providers/copilot.md` and `docs/providers/antigravity.md`. ## Heads-up - **One-time migration friction**: users whose previous "Always Allow" was granted to `/usr/bin/security` will see the Copilot/Antigravity Keychain source report unavailable until one manual refresh re-approves access for Runway itself. After that, reads are silent and survive forever (the grant now sticks to the app). File-based sources (editor config, `hosts.yml`) are unaffected and remain first in line. - Also in this push (amendments from the same review, committed to their own PRs): the fingerprint probe now runs **inside** the coordinator's single flight (#85 — a late arriver no longer touches the Keychain at all, not even the attributes query), and the iCloud device-id migration seeds from the saved UserDefaults copy so the legacy prompt-capable read runs only after a preferences reset, at most once (#86). - After this PR, the only remaining `/usr/bin/security` reads (and writes) belong to Codex and Cursor — the disclosed read-write ownership audit that follows this stack. ## Tests - `ReadModeTrackingKeychain` regression tests: automatic Copilot/Antigravity loads perform only prompt-free reads and never the subprocess-style path; manual loads use the interactive read; an `.unavailable` item throws the friendly error without prompting. - Coordinator: new test proving a late arriver behind a stuck read performs no Keychain call at all (#85); iCloud tests proving the saved-preference seed never touches the legacy path and legacy recovery runs at most once (#86). - `swift test`: 1,689 tests, 0 failures. --- ## Review follow-ups (later commits on this branch) - **Copilot billing keeps the permission state.** `loadBillingTokenCandidates` discarded `keychainPermissionRequired`, so an org-managed seat fell back to an editor token that usually lacks billing scopes and the card said "you need billing access" when an existing credential just needed approval. - **Antigravity gained a permission-specific error.** A protected item mapped to `credentialStoreUnreadable`, whose text says unlock Keychain / sign in again — neither fixes an unapproved ACL. - **Corrected the CLI documentation twice.** `--force` is not equivalent to ⌘R (it never prompts), *and* — the part I got wrong on the first pass — approving an item in the app does **not** authorize the command, because `runway` is a separately signed binary and macOS grants Keychain access per binary. Keychain-only providers reach the CLI through the app's shared snapshot instead. ### Correction An earlier revision of this description said Codex/Cursor writes were the only remaining `/usr/bin/security` use. That omitted the one-shot, existence-gated **legacy iCloud device-id migration read**, which remains after the whole stack. Also in later commits on this branch: Copilot billing keeps its permission state, Antigravity distinguishes a locked keychain from an unapproved ACL (they need opposite advice), and `ProviderRefreshContext` carries `isForced` separately from `isManual` so `runway --force` keeps bypassing negative caches without unlocking credential UI.
…hain write path (#90) > Stacked on #89, the tail of the credential stack. Completes the write-side ownership audit the post-stack reviews kept flagging — the last automatic prompt-capable paths (token-rotation writes through `/usr/bin/security`) are gone. **TL;DR**: Codex and Cursor join Claude as strictly read-only credential consumers. With no writers left, the Keychain write protocol, the accessor's write methods, and the `security add-generic-password` subprocess (secrets in argv) are deleted outright — the only Keychain write API remaining in the app is `RunwayOwnedKeychainStore`. ## What was happening - Codex and Cursor automatically refreshed expiring tokens through the providers' OAuth endpoints and wrote the rotated pairs back into the providers' own stores (`auth.json` / keyring; Cursor's `state.vscdb` / keychain items) via prompt-capable subprocess writes. Both providers' backends have refresh-token reuse detection — Codex even carries a code comment about tripping `refresh_token_reused` (issue robinebers#516) — so this was the same incident class the Claude read-only change (#84) closed, still live for two providers. - A failed persistence stranded the old refresh token on disk, so the next cycle could rotate again — the shape of a recurring five-minute prompt loop. ## What this changes - **Codex**: never calls `auth.openai.com/oauth/token`, never writes `auth.json` or the keyring. The pre-fetch reload that adopts the `codex` CLI's own rotation stays (it is read-only and the reason meters keep working while the CLI is in use). A hard-expired token or a usage 401/403 shows **"Codex login needs renewal. Run `codex`, then refresh Runway."** — with source fallback preserved and local spend tiles unaffected. The refresh-era error cases (`sessionExpired`/`tokenConflict`/`tokenRevoked`/`tokenExpired`) collapse into one `loginRenewalRequired`. - **Cursor**: never calls the token endpoint, never writes the state database or keychain. Renewal notice: **"Cursor login needs renewal. Open the Cursor app (or run `agent login`), then refresh Runway."** — naming both remedies, since the keychain-source credential belongs to the agent CLI. `SQLiteAccessing.execute` (only used to write Cursor's DB) is deleted. - **Write path deleted**: `KeychainAccessing` collapses into `KeychainReading` everywhere; `SecurityKeychainAccessor` loses its write methods and the `writePassword` subprocess helper. The one remaining `/usr/bin/security` invocation in the app is the one-shot, existence-gated legacy device-id migration read. - **Prompt bounds** (from the review): a denied Codex prompt stops the per-home scan (never one dialog per home); a denied Cursor access-item prompt never chains into the refresh-item prompt; Cursor's unknown existence probe (`nil` = locked keychain) no longer collapses into "not logged in", matching Codex. - **Docs**: `architecture.md`'s ownership section is now unconditional (resolving the contradiction the review flagged), `privacy.md`, `codex.md`, `cursor.md` rewritten to the read-only reality, with renewal troubleshooting entries. ## Heads-up - Live Codex/Cursor meters now pause when the owning app hasn't run recently enough to hold a fresh token, showing the renewal notice — the same deliberate trade Claude made in #84. While the CLI/app is in active use it rotates its own token and Runway picks it up on the next read (Codex explicitly re-reads the live store before each fetch). - Kimi and Grok still refresh their own providers' tokens, but through file stores only — no Keychain, no prompts, outside this incident class. Their ownership audit can follow the same recipe later. - Codex now degrades exactly like Claude — local spend tiles under a header warning — for both a lapsed login and a pending keyring approval. (An earlier revision listed this as future cosmetic follow-up; it is implemented.) ## Tests - Read-only regressions mirroring #84: an expired Codex/Cursor token performs zero token-endpoint calls and zero store writes and shows the renewal notice; a usage 401 does one call (no refresh-and-retry). - Prompt bounds: denied Codex prompt → exactly one interactive read across homes; denied Cursor access prompt → exactly one interactive read total. - Refresh-era tests (rotation persistence, refresh-endpoint parsing) removed with the machinery. - `swift test`: 1,706 tests, 0 failures. --- ## Review follow-ups (later commits on this branch) - **A rejected token now tries this account's other local credential once.** Cursor's app and its `agent` CLI keep separate copies, and one can outlive the other. Previously only an *expired* selection fell back, so a revoked-but-unexpired token 401'd straight into the renewal notice while a live same-account token sat unread. The retry makes no OAuth call, writes nothing, and requires matching JWT subjects so it can never cross accounts. - **An expired paid SQLite login can reach its protected keychain token.** `keychainCanWin` suppressed prompts for every paid SQLite login, so even a manual refresh returned the dead credential with advice Runway could not act on. - **Scoped the no-write claims honestly.** `privacy.md`/`architecture.md` said Runway never writes another tool's credential files, but Grok and Kimi are refreshed and saved back to their CLIs' own files. The guarantee is now scoped to the Keychain (which the type system enforces), with Grok/Kimi and Antigravity's Google OAuth refresh named as the exceptions. ### Later review follow-ups on this branch - A rejected token retries this account's other local credential once (no OAuth call, subject must match), and reports the alternative's *own* failure rather than a bogus renewal notice. - A protected alternative asks for approval instead of collapsing to "no alternative". - A live SQLite login beats an expired agent login; an expired paid login can still reach its protected keychain token. - The Cursor credential tests moved to `CursorCredentialTests.swift` to stay within the repository's ~500-line guideline.
**TL;DR** Second batch from the production cleanup audit: rewrites comments and one doc page that describe code that no longer exists or no longer works that way. No code changes. **What was happening** - Claude and Codex comments still described the era before read-only credentials (#84, #90) and guarded renewal (#99): "Runway never refreshes a Claude token", "so Runway rotates on the same schedule", "a successful usage fetch (which rotates tokens back to disk)". Two functions in `CodexAuthStore` carried two doc comments fused together, the first describing removed behavior. - `DashboardView` comments said steady state keeps one live screen tree and that the outgoing page unmounts when the push completes. Since #67 the page stays parked until the popover closes. Others referred to a "scroll spacer" and an `outgoing` identifier that do not exist. - `WidgetRowView` described a per-row timeline gate that #60 replaced with the shared clock, 22 lines below a doc comment saying it is deliberately not that. - `MemoryEditorState.saveDirtyDocument` was documented as overwriting a moved file; it keeps the conflict check. - Comments named things that are gone or renamed: `EscapeToCloseReader`, `discover`, `compactValue`, `formatTokens`, `enterpriseUnverified`, a `Logger` in `LocalUsageServer`, the `MenuBarExtra` label, "Phase 1" of account discovery, a pinned count on `ProviderRow`. - `ProviderAuthRetry` was described as shared by every OAuth-style provider; only Grok calls `fetch`. - `docs/providers/openrouter.md` said `/credits` is required for a usable snapshot. The provider renders whatever either endpoint returned and reports an invalid key only when both return 401 or 403. **What this changes** - Rewrites each comment to match the code, after checking the claim against the current source. - Moves the keychain-before-file ordering doc in `ClaudeAuthStore` from the `StoredCandidateLoad` struct to `orderedStoredCandidates`, the function it describes. This is the only non-comment line movement in the diff. - Updates the OpenRouter page. **Tests** `swift build --build-tests` passes. The diff changes only comment lines, apart from the struct move above.
TL;DR: Runway no longer refreshes or writes Claude's OAuth credentials — it is now a strictly read-only consumer. A lapsed login degrades to the local spend tiles under a "Claude login needs renewal" notice instead of rotating Claude's token.
What was happening
/v1/oauth/tokenwith Claude Code's client ID and wrote the rotated token pair back into Claude's own Keychain item or.credentials.json.SecItemUpdatemachinery and background Keychain write traffic during the incident's securityd contention.What this changes
ClaudeAuthStore.save, theClaudeCredentialGenerationcompare-and-swap, and the Keychain update path (updateGenericPassword*, theSecItemUpdate/kSecUseItemListblock) that only the writeback used.expiresAtlapsed) candidate is skipped without a network call; a 401/403 falls through to the next credential source as before. When every source has lapsed, the card now shows the plan badge + local spend tiles + an amber "Claude login needs renewal. Open Claude Code, then refresh Runway." header warning instead of a hard error card.sessionExpired/tokenExpired/credentialsChangedinto oneloginRenewalRequirederror; drops the now-meaninglessrefresh=yes/noflag from the token-free source diagnostics.docs/providers/claude.md(read-only policy, renewal troubleshooting entry, "Under the hood") anddocs/privacy.md.Heads-up
ClaudeAccountIsolationTestspins the new semantics.Tests
testExpiredKeychainTokenNeverRefreshesOrWritesAndDegradesToRenewalNotice); a usage 401 never retries with a refresh and leaves.credentials.jsonbyte-identical; all-sources-expired serves spend tiles + renewal warning; a 5xx still surfaces as a loud request failure, not a renewal notice.swift test: 1,648 tests, 0 failures.