Repository navigation
fix(mobile): recover pairing saves from Android SecureStore failures - #11430
Conversation
…unusable Orca Mobile could reach a state where pairing succeeded but the host could never be saved, with every attempt failing identically: Could not encrypt the value for key 'orca.host-token.host-...' under keychain 'key_v1'. Caused by: unknown expo-secure-store derives ONE Android keystore alias from the keychain service (`<service>:unauthenticated`) and shares it across every host token, so a single unusable alias rejects all writes. Its built-in self-heal only covers KeyPermanentlyInvalidatedException, and a null-message GeneralSecurityException takes the unrecoverable branch instead — leaving onboarding permanently blocked, which a reinstall does not clear. Route host-token persistence through a keychain generation that rotates to a fresh service (and therefore a fresh alias) only after a write has already failed. Generation 0 keeps expo's default service so tokens written by earlier builds stay readable, reads walk back through retired services, and deletes clear every generation so a rotation cannot strand a live credential. Refs #6600
Greptile SummaryThis PR introduces a bounded keychain-generation recovery layer (
Confidence Score: 5/5Safe to merge. The recovery layer is correctly ordered, fail-closed on stale reads, bounded at 8 generations, and iOS-gated so no rotation fires on non-Android devices. The write-ordering invariants are all correct and independently tested. The read path correctly fails closed when a presence record exists but the item is absent, preventing silent fallback to superseded credentials. The mutation queue serializes all writes while reads safely drain it. No credential-loss, stale-read, or unbounded-growth paths were found. Files Needing Attention: No files require special attention. The four caller files are mechanical substitutions; all meaningful logic lives in pairing-keychain.ts, which is thoroughly covered by pairing-keychain.test.ts.
|
| Filename | Overview |
|---|---|
| mobile/src/transport/pairing-keychain.ts | New core module implementing bounded keychain-generation recovery. Write ordering, presence records, fail-closed reads, mutation serialization, and the generation cap are all correctly implemented and well-commented. |
| mobile/src/transport/pairing-keychain.test.ts | 403-line test file covering all meaningful branches: normal write, alias-local recovery, cap enforcement, pending-alias retry, write-order invariant, stale-read rejection, legacy fallback, partial delete, malformed record handling, and mutation serialization. |
| mobile/src/transport/host-store.ts | Replaces three direct SecureStore call sites with pairing-keychain equivalents; adds resetPairingKeychainForTests() to the test-reset function. Clean mechanical substitution. |
| mobile/src/transport/mobile-relay-pairing-journal-store.ts | Same three-site substitution pattern; adds resetPairingKeychainForTests() to the module-level reset. The existing metadata-first write ordering for crash safety is preserved. |
| mobile/src/transport/mobile-relay-credential-bundle.ts | Three SecureStore call sites replaced with pairing-keychain equivalents; KEYCHAIN_OPTIONS constant removed. No behavioural change on the read/write paths. |
| mobile/src/transport/mobile-relay-direct-upgrade-journal.ts | Same pattern as mobile-relay-credential-bundle.ts. Clean substitution with no logic changes. |
Reviews (5): Last reviewed commit: "fix(mobile): fail closed on unreadable p..." | Re-trigger Greptile
📝 WalkthroughWalkthroughIntroduces generation-aware pairing keychain persistence with AsyncStorage generation and presence records, SecureStore alias rotation, serialized mutations, recovery, and deletion cleanup. Native host, relay credential, direct-upgrade, and pairing-journal persistence now use shared pairing-keychain helpers, while web storage remains unchanged. Tests cover iOS defaults, Android rotation and failure handling, presence semantics, malformed records, deletion behavior, and relaunch recovery. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 54122ea5-f376-4e89-ad06-273ddcaf3d49
📒 Files selected for processing (4)
mobile/src/transport/host-store.test.tsmobile/src/transport/host-store.tsmobile/src/transport/host-token-keychain.test.tsmobile/src/transport/host-token-keychain.ts
…r it Greptile flagged that a token could be stored under a generation the generation record never captured. `commitGeneration` swallowed the AsyncStorage failure and cached the new generation in memory, so the write succeeded for the rest of the session — but the next launch re-read the old record, and because reads only walk back from the recorded generation they never probed the newer service. The host silently vanished and the user had to re-pair, which is the same class of loss this change set out to fix. Record the rotation first and let a storage failure propagate, so a token is never written under a generation reads won't reach. Advancing the record before the write is safe because reads walk back through every older service; the worst case is one spent generation and one extra probe per miss.
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
mobile/src/transport/pairing-keychain.ts (1)
106-142: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low valueMinor: untested case where a retried write on an already-pending generation succeeds but the confirm write fails again.
When
loaded.pendingis true andSecureStore.setItemAsyncsucceeds but the follow-upcommitGeneration(generation, false)throws, the surroundingcatchsetsfirstErrorto that confirm failure, and sinceloaded.pendingis true the function immediately re-throws it (Line 124-126) — even though the secret was durably written under the already-recorded pending alias and is reachable on the next read. Callers will see a spurious failure on an otherwise-successful write. Data isn't lost (safe fallback), but this isn't covered by a test the way the initial-rotation confirm failure is (Lines 183-208).
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 1af76043-8ad7-4134-b5cf-5d6f807e2156
📒 Files selected for processing (9)
mobile/src/transport/host-store.test.tsmobile/src/transport/host-store.tsmobile/src/transport/mobile-relay-credential-bundle.test.tsmobile/src/transport/mobile-relay-credential-bundle.tsmobile/src/transport/mobile-relay-direct-upgrade-journal.tsmobile/src/transport/mobile-relay-pairing-journal-store.test.tsmobile/src/transport/mobile-relay-pairing-journal-store.tsmobile/src/transport/pairing-keychain.test.tsmobile/src/transport/pairing-keychain.ts
|
Verified against the bundled expo-secure-store 55.0.13 Android source: the report is correct. Absent SharedPreferences entries return null, and stored entries also return null for a missing keystore entry, KeyPermanentlyInvalidatedException, and BadPaddingException. Pushed 8708e63: Android now durably records each item generation before its SecureStore write, restores the prior marker on ordinary write failure, and treats null at a recorded generation as a hard failure instead of scanning into a superseded credential. Unmarked legacy items retain the bounded fallback scan; iOS still bypasses the marker and uses the default generation-0 service. Regression proof: restoring only pairing-keychain.ts to the previous production source made the new test fail (the presence marker stayed null and the stale-token path remained reachable). Mobile-owned Vitest baseline was 352 files / 2,623 passed / 2 skipped; final is 352 files / 2,624 passed / 2 skipped. Mobile typecheck, lint, and changed-file format checks also pass; no simulator/emulator was used. |
brennanb2025
left a comment
There was a problem hiding this comment.
Current-head queue review at 8708e6372f: no findings. Fresh verification: 69 affected mobile tests, mobile typecheck, root oxlint, affected-file formatting, and git merge-tree --write-tree against current main all pass. Reverting only pairing-keychain.ts to the prior reviewed commit makes the new fail-closed regressions fail, confirming non-vacuity. The remaining review thread was invalid for the pinned dependency: [email protected] emits the exact Could not encrypt the value for key prefix matched by the guard, and the thread is now resolved. Device QA reproduces the save failure at the parent and confirms rotation, persisted generation, and relaunch at this head, with the native hardware-keystore caveat documented. No merge performed.
…s null Clearing the presence record on the self-heal removed the only thing that stops readPairingKeychainItem's generation walk, so the next read fell back to the superseded value under an older generation -- exactly what #11430's presence record exists to prevent, and reachable for host device tokens and relay resume bundles after an Android encrypt rotation. Return null and leave the record in place; the null return alone unlatches every caller's orphan cleanup, and delete/re-pair already clear or re-stamp the record. Co-authored-by: Orca <[email protected]>
…shake (#11690) * fix(mobile): restore pairing self-heal and recover a wedged handshake readPairingKeychainItem threw when an Android presence record pointed at a SecureStore entry that read back null. Android reports absent and undecryptable identically, so the keystore fault the presence record was added to survive latched every caller out of its own orphan cleanup: the pairing journal store never reached its null-secret branch, stale winner-stamped metadata survived, and every later QR scan failed with "mobile relay pairing recovery pending". Report absent instead and drop the stale presence claim, still without falling back to the superseded older generation. The handshake-timeout path closed the socket with no handleSocketClosed fallback, unlike the connect-timeout and activity-probe paths. When React Native omits onclose for a wedged transport the client stayed in 'handshaking' forever with no reconnect armed. * fix(mobile): keep the presence pin when a recorded keychain item reads null Clearing the presence record on the self-heal removed the only thing that stops readPairingKeychainItem's generation walk, so the next read fell back to the superseded value under an older generation -- exactly what #11430's presence record exists to prevent, and reachable for host device tokens and relay resume bundles after an Android encrypt rotation. Return null and leave the record in place; the null return alone unlatches every caller's orphan cleanup, and delete/re-pair already clear or re-stamp the record. Co-authored-by: Orca <[email protected]> * fix(mobile): date synthesized socket closes in transport diagnostics Move the log-only close clocks behind handleSocketClosed's stale guard so a synthesized close records them and a late onclose can't clobber the replacement. Co-authored-by: Orca <[email protected]> * fix(mobile): account for delayed synthesized closes --------- Co-authored-by: Orca <[email protected]>
…tablyai#11430) * fix(mobile): recover pairing save when the Android keystore alias is unusable Orca Mobile could reach a state where pairing succeeded but the host could never be saved, with every attempt failing identically: Could not encrypt the value for key 'orca.host-token.host-...' under keychain 'key_v1'. Caused by: unknown expo-secure-store derives ONE Android keystore alias from the keychain service (`<service>:unauthenticated`) and shares it across every host token, so a single unusable alias rejects all writes. Its built-in self-heal only covers KeyPermanentlyInvalidatedException, and a null-message GeneralSecurityException takes the unrecoverable branch instead — leaving onboarding permanently blocked, which a reinstall does not clear. Route host-token persistence through a keychain generation that rotates to a fresh service (and therefore a fresh alias) only after a write has already failed. Generation 0 keeps expo's default service so tokens written by earlier builds stay readable, reads walk back through retired services, and deletes clear every generation so a rotation cannot strand a live credential. Refs stablyai#6600 * fix(mobile): record a keychain rotation before storing the token under it Greptile flagged that a token could be stored under a generation the generation record never captured. `commitGeneration` swallowed the AsyncStorage failure and cached the new generation in memory, so the write succeeded for the rest of the session — but the next launch re-read the old record, and because reads only walk back from the recorded generation they never probed the newer service. The host silently vanished and the user had to re-pair, which is the same class of loss this change set out to fix. Record the rotation first and let a storage failure propagate, so a token is never written under a generation reads won't reach. Advancing the record before the write is safe because reads walk back through every older service; the worst case is one spent generation and one extra probe per miss. * fix(mobile): harden pairing keychain recovery * fix(mobile): harden pairing keychain recovery state * fix(mobile): fail closed on unreadable pairing credentials
…shake (stablyai#11690) * fix(mobile): restore pairing self-heal and recover a wedged handshake readPairingKeychainItem threw when an Android presence record pointed at a SecureStore entry that read back null. Android reports absent and undecryptable identically, so the keystore fault the presence record was added to survive latched every caller out of its own orphan cleanup: the pairing journal store never reached its null-secret branch, stale winner-stamped metadata survived, and every later QR scan failed with "mobile relay pairing recovery pending". Report absent instead and drop the stale presence claim, still without falling back to the superseded older generation. The handshake-timeout path closed the socket with no handleSocketClosed fallback, unlike the connect-timeout and activity-probe paths. When React Native omits onclose for a wedged transport the client stayed in 'handshaking' forever with no reconnect armed. * fix(mobile): keep the presence pin when a recorded keychain item reads null Clearing the presence record on the self-heal removed the only thing that stops readPairingKeychainItem's generation walk, so the next read fell back to the superseded value under an older generation -- exactly what stablyai#11430's presence record exists to prevent, and reachable for host device tokens and relay resume bundles after an Android encrypt rotation. Return null and leave the record in place; the null return alone unlatches every caller's orphan cleanup, and delete/re-pair already clear or re-stamp the record. Co-authored-by: Orca <[email protected]> * fix(mobile): date synthesized socket closes in transport diagnostics Move the log-only close clocks behind handleSocketClosed's stale guard so a synthesized close records them and a late onclose can't clobber the replacement. Co-authored-by: Orca <[email protected]> * fix(mobile): account for delayed synthesized closes --------- Co-authored-by: Orca <[email protected]>
Summary
Orca Mobile could complete pairing but then fail to save the host, blocking onboarding:
The address-family theory does not fit #6600: pairing already succeeded, so the failure occurred later while persisting the device token. The bundled
[email protected]Android sources show that this exact message reaches theGeneralSecurityExceptionpath while encrypting under the shared default Android alias; passing a differentkeychainServiceselects a different alias.This PR centralizes native pairing secrets behind a bounded keychain generation:
WHEN_UNLOCKED_THIS_DEVICE_ONLYoptions, so normal iOS/Android saves and legacy credentials keep their existing path.Could not encrypt the value for keytrigger rotation. iOS and unrelated/transient errors propagate without consuming a generation.Refs #6600.
What the user sees before and after
Before
Pairing succeeds, but Orca then says it could not save the host. The host is unavailable, so onboarding cannot finish.
After
When Android's existing SecureStore alias rejects encryption, Orca retries with a fresh bounded alias and saves the host. Normal Android and iOS pairing behavior remains unchanged.
Screenshots
No visual change.
Testing
Mobile Checksis the relevant CI gate for this code. The rootPR ChecksVitest shards use the root configuration, which excludesmobile/**.AI Review Report
A fresh independent two-pass adversarial review re-examined the full pairing, relay, persistence, relaunch, cleanup, and concurrency lifecycles after the four earlier design passes. Its first pass found two material regressions—stale credential fallback and generation-budget exhaustion—and its second returned clean after the fixes.
The review-driven changes ensure relay pairing reaches recovery before connecting, unreliable generation pointers cannot orphan or shadow credentials, current-generation read failures cannot fall back to superseded credentials, failed fresh aliases stay pending without burning generations, partial deletion failures remain durable retry signals, and iOS failures do not rotate.
Security Audit
Native pairing secrets remain in SecureStore with
WHEN_UNLOCKED_THIS_DEVICE_ONLY; there is no plaintext AsyncStorage or filesystem fallback. Rotation is restricted to the Android encryption rejection, all generations are bounded, and cleanup attempts every possible service so retired credentials are not silently stranded.No dependency, native module, manifest, command-execution, path-handling, IPC, or desktop surface changed.
Verified vs. device-assumed
Verified from the reported sequence and bundled source:
GeneralSecurityExceptionbranch while encrypting under the shared default Android alias.keychainServiceselects another Android alias.Not device-verified:
If the affected keystore rejects every alias, the fix fails safe and surfaces the error rather than downgrading secret storage.