Skip to content

[PM-23301] feat: Share user session key across process boundaries#2661

Draft
fedemkr wants to merge 1 commit into
mainfrom
PM-23301/share-user-session-key-extensions
Draft

[PM-23301] feat: Share user session key across process boundaries#2661
fedemkr wants to merge 1 commit into
mainfrom
PM-23301/share-user-session-key-extensions

Conversation

@fedemkr
Copy link
Copy Markdown
Member

@fedemkr fedemkr commented May 18, 2026

🎟️ Tracking

https://bitwarden.atlassian.net/browse/PM-23301

📔 Objective

Stores the decrypted user encryption key in the keychain after a successful vault unlock, so that app extensions (AutoFill, Action, Share) can auto-unlock the vault without requiring user interaction, as long as the active session timeout policy permits it.

Key changes:

  • BitwardenKeychainItem.userSessionKey — new keychain item stored with kSecAttrAccessibleWhenUnlockedThisDeviceOnly, cleared on logout alongside other per-user items.
  • SessionTimeoutValue.allowsUserSessionKeySharing — returns true for all timed timeout values; false for .immediately, .onAppRestart, and .never (which uses its own dedicated keychain path).
  • AuthRepository.unlockVaultWithSessionKey() — reads the session key from the keychain and unlocks the vault. Returns false (not an error) if no key is stored; deletes the stale key and rethrows on a decryption failure.
  • Key lifecycle management — the session key is written after every successful unlock, and deleted on: manual lock, session timeout, and when the user changes to a timeout value that excludes sharing.
  • AuthRoute.completeWithUserSessionKey / AuthRouter+Redirects — new redirect branch that auto-unlocks via the session key when the vault is locked but a valid key exists, bypassing the unlock screen entirely.
  • NotificationCenterService.willResignActivePublisher() — new publisher for UIApplication.willResignActiveNotification; AppProcessor subscribes to it to record the last-active timestamp, covering the foreground → app-switcher-kill path where didEnterBackground never fires.

Stores the decrypted user key in the keychain after unlock so app extensions
can auto-unlock without user interaction when the vault timeout allows it.
Clears the key on manual lock, timeout expiry, and when switching to an
incompatible timeout value.
@fedemkr fedemkr added the ai-review Request a Claude code review label May 18, 2026
@github-actions github-actions Bot added app:password-manager Bitwarden Password Manager app context app:authenticator Bitwarden Authenticator app context t:feature labels May 18, 2026
@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented May 18, 2026

🤖 Bitwarden Claude Code Review

Overall Assessment: REQUEST CHANGES

Reviewed PM-23301, which introduces a userSessionKey keychain item, an AuthRepository.unlockVaultWithSessionKey() entry point, a new completeWithUserSessionKey auth route branch, and a willResignActivePublisher subscription in AppProcessor. The keychain design (per-user item, kSecAttrAccessibleWhenUnlockedThisDeviceOnly, mirrored cleanup on logout / manual lock / timeout / timeout-value change) is consistent with the existing neverLock mechanism. The main concern is that the new logic, despite touching security-critical paths in auth and key lifecycle, ships with zero unit tests.

Code Review Details
  • ⚠️ : unlockVaultWithSessionKey() has no unit tests covering the three branches (found, not-found, decryption failure)
    • BitwardenShared/Core/Auth/Repositories/AuthRepository.swift:1094-1108
  • ⚠️ : New (_, true, false) redirect branch (auto-unlock via session key) has no test coverage; .completeWithUserSessionKey also missing in AuthCoordinatorTests
    • BitwardenShared/UI/Auth/Extensions/AuthRouter+Redirects.swift:383-397
  • ⚠️ : listenForWillResignActive() has no test coverage in AppProcessorTests
    • BitwardenShared/UI/Platform/Application/AppProcessor.swift:546-559
  • Other untested behaviors mentioned for completeness (no separate inline comment posted; please cover when adding tests above): SessionTimeoutValue.allowsUserSessionKeySharing, session-key deletion in lockVault / checkSessionTimeouts / setVaultTimeout, and session-key write at the end of unlockVault(method:).

Comment on lines +1094 to +1108
func unlockVaultWithSessionKey() async throws -> Bool {
let id = try await stateService.getActiveAccountId()
do {
let sessionKey = try await keychainService.getUserAuthKeyValue(for: .userSessionKey(userId: id))
do {
try await unlockVault(method: .decryptedKey(decryptedUserKey: sessionKey), hadUserInteraction: false)
} catch {
try? await keychainService.deleteUserAuthKey(for: .userSessionKey(userId: id))
throw error
}
return true
} catch KeychainServiceError.osStatusError(errSecItemNotFound), KeychainServiceError.keyNotFound {
return false
}
}
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.

⚠️ IMPORTANT: New unlockVaultWithSessionKey() has no unit tests covering its three branches.

Details and fix

AuthRepositoryTests.swift contains zero references to unlockVaultWithSessionKey. Per Docs/Testing.md, "every type containing logic must be tested." Existing parallel functionality (unlockVaultWithNeverlockKey) is fully covered. Please add tests for:

  1. Returns true and calls unlockVault(method: .decryptedKey(...)) when a key exists in the keychain.
  2. Returns false when keychain throws KeychainServiceError.osStatusError(errSecItemNotFound) or KeychainServiceError.keyNotFound — no exception escapes.
  3. Deletes the keychain item and rethrows when unlockVault(...) itself throws (e.g., simulate an initializeUserCrypto failure).
  4. The call passes hadUserInteraction: false (important because this controls trust-device behavior).

This branch is exercised by extensions, so silent regressions here can leave users unable to autofill until they manually unlock the main app.

Comment on lines +383 to +397
case (_, true, false):
guard try await services.stateService.isAuthenticated(userId: userId) else {
return .landingSoftLoggedOut(email: activeAccount.profile.email)
}
// If a session key is present, auto-unlock without user interaction.
// checkSessionTimeouts() has already verified the timeout hasn't elapsed.
if try await services.authRepository.unlockVaultWithSessionKey() {
return .completeWithUserSessionKey
}
return .vaultUnlock(
activeAccount,
animated: animated,
attemptAutomaticBiometricUnlock: attemptAutomaticBiometricUnlock,
didSwitchAccountAutomatically: didSwitchAccountAutomatically,
)
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.

⚠️ IMPORTANT: New (_, true, false) redirect branch (auto-unlock via session key) has no test coverage in AuthRouterTests.swift.

Details and fix

This branch decides whether to bypass the unlock screen entirely — a security-relevant behavior. Suggested tests:

  1. When unlockVaultWithSessionKey() returns true, the redirect resolves to .completeWithUserSessionKey.
  2. When unlockVaultWithSessionKey() returns false, the redirect resolves to .vaultUnlock(...) with the correct animated, attemptAutomaticBiometricUnlock, and didSwitchAccountAutomatically propagated.
  3. When unlockVaultWithSessionKey() throws, the outer catch is invoked, the error is logged via errorReporter, and the route is .vaultUnlock(...).
  4. When isAuthenticated returns false, the route is .landingSoftLoggedOut(email:) and unlockVaultWithSessionKey is not called (avoids decrypting a soft-logged-out account's data).

Also worth adding a complementary test in AuthCoordinatorTests.swift for .completeWithUserSessionKey mirroring the existing test_navigate_completeWithNeverUnlockKey.

Comment on lines +546 to +559
private func listenForWillResignActive() {
Task {
for await _ in services.notificationCenterService.willResignActivePublisher() {
do {
let userId = try await self.services.stateService.getActiveAccountId()
try await services.vaultTimeoutService.setLastActiveTime(userId: userId)
} catch StateServiceError.noActiveAccount {
// No-op: nothing to do if there's no active account.
} catch {
services.errorReporter.log(error: error)
}
}
}
}
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.

⚠️ IMPORTANT: listenForWillResignActive() has no test coverage in AppProcessorTests.swift.

Details and fix

This subscription gates whether the "foreground → app-switcher-kill" auto-unlock path correctly records the last-active timestamp. Without a test, a regression here silently breaks the timeout window check on cold restart from the switcher. Suggested tests (mirroring the existing didEnterBackground tests):

  1. Sending a value through mockNotificationCenterService.willResignActiveSubject calls vaultTimeoutService.setLastActiveTime(userId:) with the active account id.
  2. When getActiveAccountId() throws StateServiceError.noActiveAccount, no error is logged and setLastActiveTime is not called.
  3. When setLastActiveTime(userId:) throws an unrelated error, it is logged via errorReporter.

@codecov
Copy link
Copy Markdown

codecov Bot commented May 18, 2026

Codecov Report

❌ Patch coverage is 0% with 16 lines in your changes missing coverage. Please review.
✅ Project coverage is 40.96%. Comparing base (68b33d5) to head (b90edde).
⚠️ Report is 9 commits behind head on main.

Files with missing lines Patch % Lines
...ore/Platform/Models/Enum/SessionTimeoutValue.swift 0.00% 16 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##             main    #2661       +/-   ##
===========================================
- Coverage   87.34%   40.96%   -46.39%     
===========================================
  Files        1919      593     -1326     
  Lines      171022    32702   -138320     
===========================================
- Hits       149386    13396   -135990     
+ Misses      21636    19306     -2330     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ai-review Request a Claude code review app:authenticator Bitwarden Authenticator app context app:password-manager Bitwarden Password Manager app context t:feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant