Skip to content

fix(vaultstore): catch Keystore-key-deleted race during PIN unlock - #580

Merged
github-actions[bot] merged 2 commits into
devfrom
fix/keystore-key-deleted-race-unlockwithpin
Aug 25, 2026
Merged

github-actions[bot] merged 2 commits into
devfrom
fix/keystore-key-deleted-race-unlockwithpin

Conversation

@libravault-pipeline-bot

Copy link
Copy Markdown
Contributor

Summary

If the Keystore key is deleted between forExisting()'s existence check and the subsequent unwrap() call inside unlockWithPin, the resulting KeyStoreException escaped uncaught instead of mapping to UnlockOutcome.KeystoreKeyLost (the path that correctly routes the user to recovery-key unlock). Widened the catch block in VaultStore.unlockWithPin to also cover java.security.KeyStoreException, returning KeystoreKeyLost without incrementing the failed-attempt throttle (same as the existing early-return path — the user didn't supply a wrong credential here).

A correct, tested fix for this exact bug already existed in the now-stalled batch PR #537 (L3 of issue #530's split); this PR reimplements that same pattern directly against current dev, since #537 diverged (added mutationMutex/openReaders in the meantime) and is itself stuck on status:needs-info.

Testing

  • Added a regression test using an anonymous HardwareKeyWrapFactory whose forExisting() succeeds (key still exists) but whose returned HardwareKeyWrap.unwrap() throws KeyStoreException, simulating the deletion race.
  • Widened newStore()'s test helper parameter type from FakeHardwareKeyWrapFactory to the HardwareKeyWrapFactory interface so the anonymous test double can be passed in.
  • Verified the new test fails (red) against the pre-fix code by temporarily reverting the catch block, then restored it — per AGENTS.md's "prove a new test can fail" rule.
  • ./gradlew :core:vaultstore:testDebugUnitTest passes locally (23/23 tests in VaultStoreTest).

Risk

Touches core/vaultstore/**, on agent-policy.yml's sensitive_paths list — this will be force-classified risk:high regardless of size. That's correct here: this changes behavior in the Keystore-key-loss path of the vault unlock flow, though the change itself is narrowly scoped (widen one catch clause + a regression test).

Closes #566.

If the Keystore key is deleted between forExisting()'s existence check
and the subsequent unwrap() call inside unlockWithPin, the resulting
KeyStoreException escaped uncaught instead of mapping to
UnlockOutcome.KeystoreKeyLost — the same recovery-key fallback path
forExisting()'s own KeystoreKeyLostException catch already routes to.
Widened the catch to cover this race, without counting it toward the
failed-attempt throttle (same as the existing early-return path,
since the user didn't supply a wrong credential).

Closes #566.
@libravault-pipeline-bot
libravault-pipeline-bot Bot force-pushed the fix/keystore-key-deleted-race-unlockwithpin branch from 8a79da7 to 991a94a Compare August 25, 2026 06:03
@github-actions
github-actions Bot marked this pull request as ready for review August 25, 2026 06:04
The pull_request "ready_for_review" event didn't fire a fresh Actions
run within several minutes of gh pr ready — jvm-tests.yml's unit-test
job is gated to skip on drafts, so no CI run has actually exercised it
yet on this PR. Empty commit to produce a synchronize event instead.
@github-actions

Copy link
Copy Markdown
Contributor

📱 iOS Build Status: PASSED

⏭️ iOS Simulator Build & Unit Tests - skipped
✅ Android Core Modules - success

iOS UI tests run in a separate, informational job and are not reflected above — check "iOS UI Tests (informational)" for those.

View run details

@github-actions github-actions Bot added the risk:high Touches a sensitive path or exceeds diff-size threshold — always human merge label Aug 25, 2026
@libravault-pipeline-bot libravault-pipeline-bot Bot added the status:needs-qa PR open, awaiting qa-agent verification label Aug 25, 2026
@claude

claude Bot commented Aug 25, 2026

Copy link
Copy Markdown
Contributor

QA verification — PR #580 vs issue #566

Issue type: bug report (no explicit checklist) → checklist is "repro no longer reproduces, and a regression test proves it."

  • ✅ Repro fixed: VaultStore.unlockWithPin now catches java.security.KeyStoreException thrown by unwrap() (the Keystore-key-deleted-mid-race case) and maps it to UnlockOutcome.KeystoreKeyLost, without incrementing the failed-attempt throttle — same treatment as the existing forExisting()/KeystoreKeyLostException early-return path. Matches the issue's described root cause and the reference fix pattern from the (closed/stalled) PR fix(vault): code review cleanup batch (L1-L8) #537.
  • ✅ Regression test proves it: I reverted just VaultStore.kt to its pre-fix state (parent commit af04059) with the new test still in place and reran VaultStoreTest. The new test (PIN unlock reports KeystoreKeyLost when the Keystore key is deleted between forExisting and unwrap) fails red exactly as expected — java.security.KeyStoreException escapes uncaught:
    VaultStoreTest > PIN unlock reports KeystoreKeyLost when the Keystore key is deleted between forExisting and unwrap() FAILED
        java.security.KeyStoreException at VaultStoreTest.kt:171
    23 tests completed, 1 failed
    
    Restoring the fix, all 24 tests in VaultStoreTest pass.
  • ✅ Full module suite: ./gradlew :core:vaultstore:testDebugUnitTest → BUILD SUCCESSFUL, all tests green. PR's own CI run (Unit & Integration Tests (JVM)) also passes (8m59s).
  • ✅ Test exercises real routing logic, not a trivial mock: the anonymous HardwareKeyWrapFactory test double lets forExisting() succeed (real FakeHardwareKeyWrapFactory delegate, key exists) and only unwrap() throws — this isolates exactly the race window the bug lived in, not just "does some exception map to KeystoreKeyLost."
  • ✅ AGENTS.md conventions: branch name fix/keystore-key-deleted-race-unlockwithpin fits fix/<slug>; commit messages use Conventional Commits (fix(vaultstore): …, chore: …); fix + its integral test are one commit (allowed per "one concern per commit"); no hardcoded versions; risk:high label is correctly present since this touches core/vaultstore/**, a sensitive path.
  • ✅ No regressions found: checked other consumers of HardwareKeyWrapFactory/unlockWithPin (VaultSessionManager, UnlockVaultViewModel, core:cloudtts's own unrelated HardwareKeyWrapFactory usage) — none touched, behavior of WrongCredential/Throttled/Success paths unchanged.

Note, not a blocker: the exact JVM exception type a real Android Keystore throws for this specific race (key deleted between forExistingKey()'s containsAlias() check and the subsequent unwrap()'s getKey() call) is asserted only by the fake-double unit test above, not by anything running against the real AndroidKeyStore provider — AndroidKeystoreHardwareKeyWrapTest.kt (instrumented) doesn't cover this exact race window either. That's a pre-existing gap in this test architecture (per HardwareKeyWrap.kt's own doc comment, only AndroidKeystoreHardwareKeyWrap needs a real device, and AGENTS.md's own test-level table names Keystore as the canonical case Robolectric can't model), not something this PR introduced — it reimplements the identical catch (e: KeyStoreException) pattern already used in the previously-accepted PR #537. Worth a follow-up instrumented test if anyone wants to close that gap, but out of scope here.

Verdict rationale: fix matches the issue, regression test is proven real (fails pre-fix, passes post-fix), full suite green, conventions followed, no regressions found.

QA verdict: PASS

@github-actions github-actions Bot removed the status:needs-qa PR open, awaiting qa-agent verification label Aug 25, 2026
@libravault-pipeline-bot libravault-pipeline-bot Bot added the status:needs-review QA passed, awaiting principal-review-agent label Aug 25, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Principal review — verdict: human-merge

Risk label: risk:high is correct and fresh — re-ran classify_pr_risk.py origin/dev origin/fix/keystore-key-deleted-race-unlockwithpin myself and it independently reproduces risk:high (core/vaultstore/src/main/kotlin/.../VaultStore.kt matches sensitive_paths pattern core/vaultstore/**). Label was applied at 06:26:04Z, after both commits (05:57:54Z, 06:15:55Z) — not stale. That alone routes this to a human regardless of anything else below.

Independently verified, not just taken on faith:

  • Checked out the branch and ran ./gradlew :core:vaultstore:testDebugUnitTest myself: 23/23 pass, matching the PR description exactly.
  • Reverted the new catch (e: KeyStoreException) block locally and re-ran the suite: exactly the new regression test fails, with the raw java.security.KeyStoreException propagating uncaught from VaultStoreTest.kt:171 — confirming both that the pre-fix bug is real and that the new test actually observes it (AGENTS.md's "prove a new test can fail" rule, done here for real rather than just claimed). Restored the file after.
  • The second commit is genuinely an empty CI-retrigger commit, as its message claims — no hidden content change.
  • No new networking dependency, no other sensitive_paths glob touched beyond the flagged one, no status:blocked on the PR or on L3: Keystore-key-deleted race escapes as raw crash instead of KeystoreKeyLost #566.

One thing worth a human's attention (PLAUSIBLE, not confirmed — not filing an issue per this role's bar, but flagging for the merger to weigh):

The fix's correctness rests on an unverified platform assumption: that a real AndroidKeystoreHardwareKeyWrap.unwrap() actually throws java.security.KeyStoreException when the Keystore key is deleted between forExisting()'s existence check and the unwrap() call. Looking at the real implementation (AndroidKeystoreHardwareKeyWrap.kt), unwrap()'s loadKey() calls KeyStore.getKey(alias, null) — per the JCA contract, getKey returns null for a missing alias, it does not throw. That null would then flow into cipher.init(Cipher.DECRYPT_MODE, null, ...), which more typically raises java.security.InvalidKeyException, not KeyStoreException — and modern (API 31+) Android Keystore2 has its own distinct android.security.KeyStoreException (an unrelated, unchecked class in a different package) that some crypto-operation failures surface instead.

The new JVM test only proves VaultStore's catch-block routing is correct given a KeyStoreException is thrown — via a hand-built HardwareKeyWrap test double that manually throws exactly that type. It can't observe whether the real Keystore-backed path actually throws that type in this race, because that's Android-framework behavior a JVM test has no visibility into. This is the same "level that cannot observe the property" trap AGENTS.md calls out by name (Keystore is literally the example given there: "its Robolectric shim has no securityLevel, no StrongBox" — the same gap applies to its exception behavior on a real device). AndroidKeystoreHardwareKeyWrapTest.kt (the on-device suite) doesn't cover this specific race either.

I can't verify the real exception type without a physical device / Test Lab run in this environment, so I'm not confirming this is broken — only that it's unverified and material to whether the fix does anything on a real device. Worth an on-device probe (delete the alias mid-flight, or between forExistingKey() and unwrap(), and log/assert the actual exception class) before or shortly after merge, and worth widening the catch to whatever that probe finds if it's not java.security.KeyStoreException.

Verdict rationale: risk:high alone already mandates human-merge here. The code change itself is small, logically consistent with the existing sibling KeystoreKeyLostException catch (same recovery-key fallback, same "don't count against the throttle" reasoning), and its tests are real (proven red/green). The one open question above doesn't change the routing but is worth a human's eyes before or shortly after merging.

@github-actions github-actions Bot added status:needs-human-merge Principal review done, requires human merge decision and removed status:needs-review QA passed, awaiting principal-review-agent labels Aug 25, 2026
@github-actions
github-actions Bot merged commit 96b8f34 into dev Aug 25, 2026
20 checks passed
@github-actions
github-actions Bot deleted the fix/keystore-key-deleted-race-unlockwithpin branch August 25, 2026 08:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

risk:high Touches a sensitive path or exceeds diff-size threshold — always human merge status:needs-human-merge Principal review done, requires human merge decision

Projects

None yet

Development

Successfully merging this pull request may close these issues.

L3: Keystore-key-deleted race escapes as raw crash instead of KeystoreKeyLost

0 participants