Skip to main content

bitwarden_unlock/
unlock_client.rs

1//! Client for unlocking a rehydrated Bitwarden SDK client.
2
3#[cfg(feature = "cli")]
4use bitwarden_core::client::persisted_state::{
5    ACCOUNT_CRYPTO_STATE, OrganizationSharedKey, SESSION_PROTECTED_USER_KEY,
6};
7use bitwarden_core::{
8    Client,
9    client::encryption_settings::EncryptionSettingsError,
10    key_management::{SymmetricKeySlotId, crypto::InitUserCryptoRequest},
11};
12use bitwarden_error::bitwarden_error;
13use serde::{Deserialize, Serialize};
14
15#[cfg(feature = "cli")]
16use crate::SessionKey;
17
18/// The unlock factor passed to [`UnlockClient::unlock`].
19#[derive(Serialize, Deserialize)]
20#[serde(rename_all = "camelCase")]
21// `SessionKey` has no UniFFI representation, so the enum is a UniFFI type only when the CLI-only
22// session-key variant is compiled out.
23#[cfg_attr(all(feature = "uniffi", not(feature = "cli")), derive(uniffi::Enum))]
24#[bitwarden_ffi::wasm_record]
25#[allow(clippy::large_enum_variant)]
26pub enum UnlockMethod {
27    /// Unlock by initializing the user's crypto state from an [`InitUserCryptoRequest`], as
28    /// [`CryptoClient::initialize_user_crypto`](bitwarden_core::key_management::CryptoClient::initialize_user_crypto)
29    /// does.
30    Legacy(InitUserCryptoRequest),
31    /// Unlock using a session key previously obtained from
32    /// [`UnlockClient::generate_session_key`].
33    ///
34    /// Only the CLI unlocks with a session key, so this variant is not part of the WASM or UniFFI
35    /// surface. `serde(skip)` keeps it out of the generated TypeScript type.
36    #[cfg(feature = "cli")]
37    #[serde(skip)]
38    SessionKey(SessionKey),
39}
40
41/// Errors returned by [`UnlockClient::generate_session_key`] and
42/// [`UnlockClient::unlock`].
43#[bitwarden_error(flat)]
44#[derive(Debug, thiserror::Error)]
45pub enum UnlockError {
46    /// The client already holds a user key. Nothing was changed.
47    #[error("The client is already unlocked")]
48    AlreadyUnlocked,
49    /// Initializing the user's crypto state failed, for example because of a wrong PIN or
50    /// password.
51    #[error(transparent)]
52    EncryptionSettings(#[from] EncryptionSettingsError),
53    /// An unknown error occurred while handling a session key. The detailed cause is emitted via
54    /// `tracing::error!` rather than carried in the error, so callers see a uniform failure shape
55    /// while operators retain diagnostic visibility through logs.
56    #[error("An unknown error occurred while unlocking the client")]
57    Unknown,
58}
59
60/// Client for unlocking and locking the vault in memory, and for minting session keys and
61/// unlocking the vault with one.
62#[derive(Clone)]
63#[cfg_attr(feature = "uniffi", derive(uniffi::Object))]
64#[bitwarden_ffi::wasm_object]
65pub struct UnlockClient {
66    pub(crate) client: Client,
67}
68
69impl UnlockClient {
70    pub(crate) fn new(client: Client) -> Self {
71        Self { client }
72    }
73
74    /// Mint a new session key and persist the user key wrapped by it.
75    ///
76    /// Requires the client to be unlocked (the user key must be present in the
77    /// key store). The returned [`SessionKey`] should be stored outside the SDK
78    /// by the caller and provided back to [`UnlockClient::unlock`] on the next
79    /// rehydrated client.
80    #[cfg(feature = "cli")]
81    pub async fn generate_session_key(&self) -> Result<SessionKey, UnlockError> {
82        let (envelope, session_key) = {
83            let key_store = self.client.internal.get_key_store();
84            let mut ctx = key_store.context_mut();
85            SessionKey::from_context(SymmetricKeySlotId::User, &mut ctx).map_err(|e| {
86                tracing::error!("Failed to encrypt user key with session key: {e}");
87                UnlockError::Unknown
88            })?
89        };
90
91        self.client
92            .platform()
93            .state()
94            .value::<SESSION_PROTECTED_USER_KEY>()
95            .set(envelope)
96            .await
97            .map_err(|_| UnlockError::Unknown)?;
98
99        Ok(session_key)
100    }
101
102    /// Whether the key store holds the user key.
103    fn has_user_key(&self) -> bool {
104        self.client
105            .internal
106            .get_key_store()
107            .context()
108            .has_symmetric_key(SymmetricKeySlotId::User)
109    }
110
111    /// Unlock a rehydrated client with a session key.
112    ///
113    /// Reads [`SESSION_PROTECTED_USER_KEY`] and [`ACCOUNT_CRYPTO_STATE`] from
114    /// the state registry, unwraps the user key, initializes the user's crypto
115    /// state, and restores any persisted organization keys.
116    #[cfg(feature = "cli")]
117    async fn unlock_with_session_key(&self, session_key: SessionKey) -> Result<(), UnlockError> {
118        let state = self.client.platform().state();
119
120        let session_protected_user_key = state
121            .value::<SESSION_PROTECTED_USER_KEY>()
122            .get()
123            .await
124            .map_err(|_| UnlockError::Unknown)?;
125
126        let account_crypto_state = state
127            .value::<ACCOUNT_CRYPTO_STATE>()
128            .get()
129            .await
130            .map_err(|_| UnlockError::Unknown)?;
131
132        let decrypted_key = {
133            let key_store = self.client.internal.get_key_store();
134            let mut ctx = key_store.context_mut();
135            let decrypted_key_id = session_key
136                .unwrap_to_context(&session_protected_user_key, &mut ctx)
137                .map_err(|e| {
138                    tracing::error!("Failed to unseal user key with session key: {e}");
139                    UnlockError::Unknown
140                })?;
141            #[allow(deprecated)]
142            ctx.dangerous_get_symmetric_key(decrypted_key_id)
143                .map_err(|e| {
144                    tracing::error!("Failed to read decrypted user key from key store: {e}");
145                    UnlockError::Unknown
146                })?
147                .clone()
148        };
149
150        self.client
151            .internal
152            .initialize_user_crypto_decrypted_key(decrypted_key, account_crypto_state, &None)
153            .map_err(|e| {
154                tracing::error!("Failed to initialize user crypto with decrypted key: {e}");
155                UnlockError::Unknown
156            })?;
157
158        let org_keys = state
159            .get::<OrganizationSharedKey>()
160            .map_err(|e| {
161                tracing::error!("Failed to read organization keys repository: {e}");
162                UnlockError::Unknown
163            })?
164            .list()
165            .await
166            .map_err(|e| {
167                tracing::error!("Failed to list organization keys: {e}");
168                UnlockError::Unknown
169            })?;
170
171        self.client
172            .internal
173            .initialize_org_crypto(org_keys.into_iter().map(|k| (k.org_id, k.key)).collect())
174            .map_err(|e| {
175                tracing::error!("Failed to decrypt organization keys: {e}");
176                UnlockError::Unknown
177            })?;
178
179        Ok(())
180    }
181
182    /// Delete the persisted session key, so later CLI invocations can no longer unlock with it.
183    ///
184    /// Removes [`SESSION_PROTECTED_USER_KEY`] from the database. This is how the CLI locks: each
185    /// command runs in a new process, so there are no in-memory keys to clear. Long-lived clients
186    /// lock with [`UnlockClient::lock`] instead.
187    #[cfg(feature = "cli")]
188    pub async fn invalidate_session_key(&self) -> Result<(), bitwarden_state::PersistedValueError> {
189        self.client
190            .platform()
191            .state()
192            .value::<SESSION_PROTECTED_USER_KEY>()
193            .remove()
194            .await
195    }
196}
197
198#[bitwarden_ffi::wasm_export]
199// `UnlockMethod` is a UniFFI type only without the `cli` feature, see its definition.
200#[cfg_attr(
201    all(feature = "uniffi", not(feature = "cli")),
202    uniffi::export(async_runtime = "tokio")
203)]
204impl UnlockClient {
205    /// Unlock the client with the supplied unlock factor.
206    ///
207    /// [`UnlockMethod::Legacy`] initializes the user's crypto state from the request, as
208    /// `CryptoClient::initialize_user_crypto` does, and returns its errors as
209    /// [`UnlockError::EncryptionSettings`].
210    ///
211    /// If the client is already unlocked, this returns [`UnlockError::AlreadyUnlocked`] before
212    /// doing any work and leaves the client's keys untouched. The check only looks at whether a
213    /// user key is present: it does not check which key the client holds, or whether it belongs
214    /// to the user or account in the request.
215    pub async fn unlock(&self, method: UnlockMethod) -> Result<(), UnlockError> {
216        if self.has_user_key() {
217            return Err(UnlockError::AlreadyUnlocked);
218        }
219
220        match method {
221            UnlockMethod::Legacy(request) => {
222                Ok(self.client.crypto().initialize_user_crypto(request).await?)
223            }
224            #[cfg(feature = "cli")]
225            UnlockMethod::SessionKey(session_key) => {
226                self.unlock_with_session_key(session_key).await
227            }
228        }
229    }
230}
231
232#[bitwarden_ffi::wasm_export]
233#[cfg_attr(feature = "uniffi", uniffi::export(async_runtime = "tokio"))]
234impl UnlockClient {
235    /// Clear the in-memory user and organization keys, retaining the client instance so that a
236    /// later [`UnlockClient::unlock`] re-unlocks it.
237    ///
238    /// On WASM, unlocking also copies the user key into client-held state through the
239    /// key-management state bridge, so locking clears it there as well. The in-memory keys are
240    /// cleared first, so the SDK is locked even if the state bridge call fails.
241    // The signature is part of the UniFFI and wasm public surface; only the WASM build awaits.
242    #[cfg_attr(not(feature = "wasm"), allow(clippy::unused_async))]
243    pub async fn lock(&self) {
244        self.client.internal.get_key_store().clear();
245
246        // Same gate as `copy_user_key_to_state`, which copies the unlocked user key to the state
247        // bridge only on WASM. Clients on other bindings keep their SDK instance for the whole
248        // unlocked session, so unlocking never puts the key there for them.
249        #[cfg(feature = "wasm")]
250        {
251            let bridge = self.client.km_state_bridge();
252            if bridge.is_bridge_registered() {
253                bridge.clear_user_key().await;
254            }
255        }
256    }
257}
258
259/// Extension trait to add the unlock client to the main Bitwarden SDK client.
260pub trait UnlockClientExt {
261    /// Get the unlock client.
262    fn unlock(&self) -> UnlockClient;
263}
264
265impl UnlockClientExt for Client {
266    fn unlock(&self) -> UnlockClient {
267        UnlockClient::new(self.clone())
268    }
269}
270
271#[cfg(test)]
272mod lock_tests {
273    use bitwarden_core::{
274        Client, UserId,
275        key_management::{
276            KeySlotIds, SymmetricKeySlotId,
277            account_cryptographic_state::WrappedAccountCryptographicState,
278            crypto::{InitUserCryptoMethod, InitUserCryptoRequest},
279        },
280    };
281    use bitwarden_crypto::{
282        CryptoError, Decryptable, EncString, Kdf, KeyStore, PrimitiveEncryptable,
283        SymmetricCryptoKey,
284    };
285
286    use super::*;
287
288    const PLAINTEXT: &str = "secret";
289
290    /// Mint a fresh `(user_key, account_crypto_state)` pair where the wrapped
291    /// state was sealed with `user_key`.
292    fn make_test_user_crypto() -> (SymmetricCryptoKey, WrappedAccountCryptographicState) {
293        let store: KeyStore<KeySlotIds> = KeyStore::default();
294        let mut ctx = store.context_mut();
295        let (user_key_id, crypto_state) = WrappedAccountCryptographicState::make(&mut ctx).unwrap();
296        #[allow(deprecated)]
297        let user_key = ctx
298            .dangerous_get_symmetric_key(user_key_id)
299            .unwrap()
300            .clone();
301        (user_key, crypto_state)
302    }
303
304    fn init_request(
305        user_key: &SymmetricCryptoKey,
306        crypto_state: &WrappedAccountCryptographicState,
307    ) -> InitUserCryptoRequest {
308        InitUserCryptoRequest {
309            user_id: Some(
310                "d5b1fde2-a1e3-4c5b-9e0f-1a2b3c4d5e6f"
311                    .parse::<UserId>()
312                    .unwrap(),
313            ),
314            kdf_params: Kdf::default_pbkdf2(),
315            email: "[email protected]".to_string(),
316            account_cryptographic_state: crypto_state.clone(),
317            method: InitUserCryptoMethod::DecryptedKey {
318                decrypted_user_key: user_key.to_base64().to_string(),
319            },
320            upgrade_token: None,
321        }
322    }
323
324    /// Build a client unlocked with a fresh user key, and a value encrypted with that key.
325    async fn unlocked_client() -> (Client, InitUserCryptoRequest, EncString) {
326        let (user_key, crypto_state) = make_test_user_crypto();
327        let client = Client::new_test(None);
328        client
329            .crypto()
330            .initialize_user_crypto(init_request(&user_key, &crypto_state))
331            .await
332            .unwrap();
333
334        let encrypted = {
335            let key_store = client.internal.get_key_store();
336            let mut ctx = key_store.context();
337            PLAINTEXT
338                .encrypt(&mut ctx, SymmetricKeySlotId::User)
339                .unwrap()
340        };
341
342        (client, init_request(&user_key, &crypto_state), encrypted)
343    }
344
345    fn decrypt_with_user_key(
346        client: &Client,
347        encrypted: &EncString,
348    ) -> Result<String, CryptoError> {
349        let key_store = client.internal.get_key_store();
350        let mut ctx = key_store.context();
351        encrypted.decrypt(&mut ctx, SymmetricKeySlotId::User)
352    }
353
354    #[tokio::test]
355    async fn lock_makes_crypto_operations_fail_as_uninitialized() {
356        let (client, _, encrypted) = unlocked_client().await;
357
358        client.unlock().lock().await;
359
360        let result = decrypt_with_user_key(&client, &encrypted);
361        assert!(
362            matches!(result, Err(CryptoError::MissingKeyId(_))),
363            "Decrypting after lock should fail with a missing key, got {result:?}"
364        );
365    }
366
367    #[tokio::test]
368    async fn initialize_user_crypto_after_lock_reunlocks_same_instance() {
369        let (client, request, encrypted) = unlocked_client().await;
370
371        client.unlock().lock().await;
372        client
373            .crypto()
374            .initialize_user_crypto(request)
375            .await
376            .unwrap();
377
378        assert_eq!(
379            decrypt_with_user_key(&client, &encrypted).unwrap(),
380            PLAINTEXT
381        );
382    }
383
384    #[cfg(feature = "wasm")]
385    #[tokio::test]
386    async fn lock_clears_user_key_from_state_bridge() {
387        use bitwarden_core::key_management::state_bridge::test_support::InMemoryStateBridge;
388
389        let (user_key, crypto_state) = make_test_user_crypto();
390        let client = Client::new_test(None);
391        let bridge = client.km_state_bridge();
392        bridge.register_bridge(Box::new(InMemoryStateBridge::default()));
393        client
394            .crypto()
395            .initialize_user_crypto(init_request(&user_key, &crypto_state))
396            .await
397            .unwrap();
398        assert!(
399            bridge.get_user_key().await.is_some(),
400            "Unlocking should copy the user key into the state bridge"
401        );
402
403        client.unlock().lock().await;
404
405        assert!(
406            bridge.get_user_key().await.is_none(),
407            "Locking should clear the user key from the state bridge"
408        );
409    }
410
411    fn user_key_base64(client: &Client) -> String {
412        let key_store = client.internal.get_key_store();
413        let ctx = key_store.context();
414        #[allow(deprecated)]
415        ctx.dangerous_get_symmetric_key(SymmetricKeySlotId::User)
416            .unwrap()
417            .to_base64()
418            .to_string()
419    }
420
421    #[tokio::test]
422    async fn legacy_unlock_unlocks_fresh_client() {
423        let (user_key, crypto_state) = make_test_user_crypto();
424        let client = Client::new_test(None);
425
426        client
427            .unlock()
428            .unlock(UnlockMethod::Legacy(init_request(&user_key, &crypto_state)))
429            .await
430            .unwrap();
431
432        assert_eq!(
433            user_key_base64(&client),
434            user_key.to_base64().to_string(),
435            "Unlocking should load the request's user key into the key store"
436        );
437    }
438
439    #[tokio::test]
440    async fn unlock_on_unlocked_client_returns_already_unlocked_and_keeps_user_key() {
441        let (client, _, encrypted) = unlocked_client().await;
442        let user_key_before = user_key_base64(&client);
443
444        // A request for a different user key: the check must not depend on the request.
445        let (other_user_key, other_crypto_state) = make_test_user_crypto();
446        let result = client
447            .unlock()
448            .unlock(UnlockMethod::Legacy(init_request(
449                &other_user_key,
450                &other_crypto_state,
451            )))
452            .await;
453
454        assert!(
455            matches!(result, Err(UnlockError::AlreadyUnlocked)),
456            "Unlocking an unlocked client should return AlreadyUnlocked, got {result:?}"
457        );
458        assert_eq!(user_key_base64(&client), user_key_before);
459        assert_eq!(
460            decrypt_with_user_key(&client, &encrypted).unwrap(),
461            PLAINTEXT
462        );
463    }
464
465    #[tokio::test]
466    async fn unlock_after_lock_reunlocks_same_instance() {
467        let (client, request, encrypted) = unlocked_client().await;
468
469        client.unlock().lock().await;
470        client
471            .unlock()
472            .unlock(UnlockMethod::Legacy(request))
473            .await
474            .unwrap();
475
476        assert_eq!(
477            decrypt_with_user_key(&client, &encrypted).unwrap(),
478            PLAINTEXT
479        );
480    }
481
482    #[tokio::test]
483    async fn legacy_unlock_with_wrong_pin_passes_through_wrong_pin() {
484        use bitwarden_core::client::encryption_settings::EncryptionSettingsError;
485        use bitwarden_crypto::safe::{
486            PasswordProtectedKeyEnvelope, PasswordProtectedKeyEnvelopeNamespace,
487        };
488
489        let (user_key, crypto_state) = make_test_user_crypto();
490        let envelope = {
491            let store: KeyStore<KeySlotIds> = KeyStore::default();
492            let mut ctx = store.context_mut();
493            let user_key_id = ctx.add_local_symmetric_key(user_key.clone());
494            PasswordProtectedKeyEnvelope::seal(
495                user_key_id,
496                "1234",
497                PasswordProtectedKeyEnvelopeNamespace::PinUnlock,
498                &ctx,
499            )
500            .unwrap()
501        };
502        let mut request = init_request(&user_key, &crypto_state);
503        request.method = InitUserCryptoMethod::PinEnvelope {
504            pin: "0000".to_string(),
505            pin_protected_user_key_envelope: envelope,
506        };
507        let client = Client::new_test(None);
508
509        let result = client.unlock().unlock(UnlockMethod::Legacy(request)).await;
510
511        assert!(
512            matches!(
513                result,
514                Err(UnlockError::EncryptionSettings(
515                    EncryptionSettingsError::WrongPin
516                ))
517            ),
518            "A wrong PIN should pass through as WrongPin, got {result:?}"
519        );
520        assert_eq!(result.unwrap_err().to_string(), "Wrong Pin");
521        assert!(
522            !client
523                .internal
524                .get_key_store()
525                .context()
526                .has_symmetric_key(SymmetricKeySlotId::User),
527            "A failed unlock should leave the client locked"
528        );
529    }
530
531    #[cfg(feature = "wasm")]
532    #[tokio::test]
533    async fn unlock_on_unlocked_client_keeps_user_key_in_state_bridge() {
534        use bitwarden_core::key_management::state_bridge::test_support::InMemoryStateBridge;
535
536        let (user_key, crypto_state) = make_test_user_crypto();
537        let client = Client::new_test(None);
538        let bridge = client.km_state_bridge();
539        bridge.register_bridge(Box::new(InMemoryStateBridge::default()));
540        client
541            .unlock()
542            .unlock(UnlockMethod::Legacy(init_request(&user_key, &crypto_state)))
543            .await
544            .unwrap();
545
546        let (other_user_key, other_crypto_state) = make_test_user_crypto();
547        let result = client
548            .unlock()
549            .unlock(UnlockMethod::Legacy(init_request(
550                &other_user_key,
551                &other_crypto_state,
552            )))
553            .await;
554
555        assert!(matches!(result, Err(UnlockError::AlreadyUnlocked)));
556        assert_eq!(
557            bridge
558                .get_user_key()
559                .await
560                .map(|k| k.to_base64().to_string()),
561            Some(user_key.to_base64().to_string()),
562            "An AlreadyUnlocked result should leave the state bridge user key in place"
563        );
564        assert_eq!(user_key_base64(&client), user_key.to_base64().to_string());
565    }
566}
567
568#[cfg(all(test, feature = "cli"))]
569mod tests {
570    // Clippy's automatic test-code exemption for `unwrap_used` keys off a bare
571    // `#[cfg(test)]` and doesn't trigger when extra cfg predicates are present.
572    #![allow(clippy::unwrap_used)]
573
574    use std::sync::{Arc, Once};
575
576    use bitwarden_core::{
577        Client, DeviceType, HostPlatformInfo, SaveStateData, UserId,
578        auth::auth_tokens::{NoopTokenHandler, TokenHandler},
579        client::persisted_state::{BASE_URLS, BaseUrls, SESSION_PROTECTED_USER_KEY, USER_ID},
580        key_management::{
581            KeySlotIds, SecurityState, SymmetricKeySlotId,
582            account_cryptographic_state::WrappedAccountCryptographicState,
583        },
584    };
585    use bitwarden_crypto::{
586        KeyStore, PublicKeyEncryptionAlgorithm, SignatureAlgorithm, SymmetricCryptoKey,
587        SymmetricKeyAlgorithm,
588        safe::{SymmetricKeyEnvelope, SymmetricKeyEnvelopeNamespace},
589    };
590    use bitwarden_state::registry::StateRegistry;
591
592    use super::*;
593
594    static INIT: Once = Once::new();
595
596    fn ensure_platform_info() {
597        INIT.call_once(|| {
598            bitwarden_core::init_host_platform_info(HostPlatformInfo {
599                user_agent: "unlock-tests".to_string(),
600                device_type: DeviceType::SDK,
601                device_identifier: None,
602                bitwarden_client_version: None,
603                bitwarden_package_type: None,
604            });
605        });
606    }
607
608    fn test_user_id() -> UserId {
609        "d5b1fde2-a1e3-4c5b-9e0f-1a2b3c4d5e6f".parse().unwrap()
610    }
611
612    fn test_email() -> String {
613        "[email protected]".to_string()
614    }
615
616    fn test_base_urls() -> BaseUrls {
617        BaseUrls {
618            identity_url: "https://identity.example.com".to_string(),
619            api_url: "https://api.example.com".to_string(),
620        }
621    }
622
623    fn has_user_key(client: &Client) -> bool {
624        client
625            .internal
626            .get_key_store()
627            .context()
628            .has_symmetric_key(SymmetricKeySlotId::User)
629    }
630
631    fn user_key_base64(client: &Client) -> String {
632        let key_store = client.internal.get_key_store();
633        let ctx = key_store.context();
634        #[allow(deprecated)]
635        ctx.dangerous_get_symmetric_key(SymmetricKeySlotId::User)
636            .unwrap()
637            .to_base64()
638            .to_string()
639    }
640
641    /// Mint a fresh `(user_key, account_crypto_state)` pair where the wrapped
642    /// state was sealed with `user_key`.
643    fn make_test_user_crypto() -> (SymmetricCryptoKey, WrappedAccountCryptographicState) {
644        let store: KeyStore<KeySlotIds> = KeyStore::default();
645        let mut ctx = store.context_mut();
646        let user_key_id = ctx.make_symmetric_key(SymmetricKeyAlgorithm::XAes256Gcm);
647        let private_key_id = ctx.make_private_key(PublicKeyEncryptionAlgorithm::RsaOaepSha1);
648        let signing_key_id = ctx.make_signing_key(SignatureAlgorithm::Ed25519);
649        let signed_public_key = ctx
650            .make_signed_public_key(private_key_id, signing_key_id)
651            .unwrap();
652        let security_state = SecurityState::new();
653        let signed_security_state = security_state.sign(signing_key_id, &mut ctx).unwrap();
654        let wrapped_private = ctx.wrap_private_key(user_key_id, private_key_id).unwrap();
655        let wrapped_signing = ctx.wrap_signing_key(user_key_id, signing_key_id).unwrap();
656        #[allow(deprecated)]
657        let user_key = ctx
658            .dangerous_get_symmetric_key(user_key_id)
659            .unwrap()
660            .clone();
661        (
662            user_key,
663            WrappedAccountCryptographicState::V2 {
664                private_key: wrapped_private,
665                signed_public_key,
666                signing_key: wrapped_signing,
667                security_state: signed_security_state,
668            },
669        )
670    }
671
672    /// Wrap `user_key` with a freshly generated session key, returning the
673    /// envelope and the session key.
674    fn seal_with_new_session_key(
675        user_key: &SymmetricCryptoKey,
676    ) -> (SymmetricKeyEnvelope, SessionKey) {
677        let store: KeyStore<KeySlotIds> = KeyStore::default();
678        let mut ctx = store.context_mut();
679        let user_key_id = ctx.add_local_symmetric_key(user_key.clone());
680        let session_key_id = ctx.make_symmetric_key(SymmetricKeyAlgorithm::XAes256Gcm);
681        let envelope = SymmetricKeyEnvelope::seal(
682            user_key_id,
683            session_key_id,
684            SymmetricKeyEnvelopeNamespace::SessionKey,
685            &ctx,
686        )
687        .unwrap();
688        #[allow(deprecated)]
689        let session_key = ctx
690            .dangerous_get_symmetric_key(session_key_id)
691            .unwrap()
692            .clone();
693        (envelope, SessionKey(session_key))
694    }
695
696    async fn populate_registry_for_unlock(
697        envelope: SymmetricKeyEnvelope,
698        crypto_state: WrappedAccountCryptographicState,
699    ) -> StateRegistry {
700        let reg = StateRegistry::new_with_memory_db();
701        reg.value::<SESSION_PROTECTED_USER_KEY>()
702            .set(envelope)
703            .await
704            .unwrap();
705        Client::save_to_state(
706            SaveStateData {
707                user_id: test_user_id(),
708                email: test_email(),
709                urls: test_base_urls(),
710                crypto_state,
711            },
712            &reg,
713        )
714        .await
715        .unwrap();
716        reg
717    }
718
719    #[tokio::test]
720    async fn generate_session_key_persists_envelope() {
721        ensure_platform_info();
722        let (user_key, crypto_state) = make_test_user_crypto();
723
724        let reg = StateRegistry::new_with_memory_db();
725        Client::save_to_state(
726            SaveStateData {
727                user_id: test_user_id(),
728                email: test_email(),
729                urls: test_base_urls(),
730                crypto_state: crypto_state.clone(),
731            },
732            &reg,
733        )
734        .await
735        .unwrap();
736
737        let token_handler: Arc<dyn TokenHandler> = Arc::new(NoopTokenHandler);
738        let client = Client::load_from_state(token_handler, reg).await.unwrap();
739        client
740            .internal
741            .initialize_user_crypto_decrypted_key(user_key, crypto_state, &None)
742            .unwrap();
743
744        let _session_key = client.unlock().generate_session_key().await.unwrap();
745
746        client
747            .platform()
748            .state()
749            .value::<SESSION_PROTECTED_USER_KEY>()
750            .get()
751            .await
752            .expect("SESSION_PROTECTED_USER_KEY should be persisted after generate_session_key");
753    }
754
755    #[tokio::test]
756    async fn unlock_with_session_key_restores_user_key() {
757        ensure_platform_info();
758        let (user_key, crypto_state) = make_test_user_crypto();
759        let expected_user_key = user_key.to_base64().to_string();
760        let (envelope, session_key) = seal_with_new_session_key(&user_key);
761
762        let reg = populate_registry_for_unlock(envelope, crypto_state).await;
763        let token_handler: Arc<dyn TokenHandler> = Arc::new(NoopTokenHandler);
764        let client = Client::load_from_state(token_handler, reg).await.unwrap();
765        assert!(
766            !has_user_key(&client),
767            "Rehydrated client should start locked"
768        );
769
770        client
771            .unlock()
772            .unlock(UnlockMethod::SessionKey(session_key))
773            .await
774            .unwrap();
775
776        assert!(has_user_key(&client));
777        assert_eq!(
778            user_key_base64(&client),
779            expected_user_key,
780            "Unlocked user key should match the original"
781        );
782    }
783
784    #[tokio::test]
785    async fn unlock_with_session_key_on_unlocked_client_returns_already_unlocked() {
786        ensure_platform_info();
787        let (user_key, crypto_state) = make_test_user_crypto();
788        let expected_user_key = user_key.to_base64().to_string();
789        let (envelope, session_key) = seal_with_new_session_key(&user_key);
790
791        let reg = populate_registry_for_unlock(envelope, crypto_state).await;
792        let token_handler: Arc<dyn TokenHandler> = Arc::new(NoopTokenHandler);
793        let client = Client::load_from_state(token_handler, reg).await.unwrap();
794        client
795            .unlock()
796            .unlock(UnlockMethod::SessionKey(session_key.clone()))
797            .await
798            .unwrap();
799
800        let result = client
801            .unlock()
802            .unlock(UnlockMethod::SessionKey(session_key))
803            .await;
804
805        assert!(matches!(result, Err(UnlockError::AlreadyUnlocked)));
806        assert_eq!(user_key_base64(&client), expected_user_key);
807    }
808
809    #[tokio::test]
810    async fn unlock_missing_session_protected_user_key_returns_unknown() {
811        ensure_platform_info();
812        let (user_key, crypto_state) = make_test_user_crypto();
813        let (_, session_key) = seal_with_new_session_key(&user_key);
814
815        let reg = StateRegistry::new_with_memory_db();
816        Client::save_to_state(
817            SaveStateData {
818                user_id: test_user_id(),
819                email: test_email(),
820                urls: test_base_urls(),
821                crypto_state,
822            },
823            &reg,
824        )
825        .await
826        .unwrap();
827        let token_handler: Arc<dyn TokenHandler> = Arc::new(NoopTokenHandler);
828        let client = Client::load_from_state(token_handler, reg).await.unwrap();
829
830        let result = client
831            .unlock()
832            .unlock(UnlockMethod::SessionKey(session_key))
833            .await;
834        assert!(matches!(result, Err(UnlockError::Unknown)));
835    }
836
837    #[tokio::test]
838    async fn unlock_missing_account_crypto_state_returns_unknown() {
839        ensure_platform_info();
840        let (user_key, _crypto_state) = make_test_user_crypto();
841        let (envelope, session_key) = seal_with_new_session_key(&user_key);
842
843        let reg = StateRegistry::new_with_memory_db();
844        reg.value::<BASE_URLS>()
845            .set(test_base_urls())
846            .await
847            .unwrap();
848        reg.value::<USER_ID>().set(test_user_id()).await.unwrap();
849        reg.value::<SESSION_PROTECTED_USER_KEY>()
850            .set(envelope)
851            .await
852            .unwrap();
853        let token_handler: Arc<dyn TokenHandler> = Arc::new(NoopTokenHandler);
854        let client = Client::load_from_state(token_handler, reg).await.unwrap();
855
856        let result = client
857            .unlock()
858            .unlock(UnlockMethod::SessionKey(session_key))
859            .await;
860        assert!(matches!(result, Err(UnlockError::Unknown)));
861    }
862
863    #[tokio::test]
864    async fn unlock_with_wrong_session_key_returns_unknown() {
865        ensure_platform_info();
866        let (user_key, crypto_state) = make_test_user_crypto();
867        let (envelope, _real_session_key) = seal_with_new_session_key(&user_key);
868
869        let reg = populate_registry_for_unlock(envelope, crypto_state).await;
870        let token_handler: Arc<dyn TokenHandler> = Arc::new(NoopTokenHandler);
871        let client = Client::load_from_state(token_handler, reg).await.unwrap();
872
873        let wrong_key = SymmetricCryptoKey::make(SymmetricKeyAlgorithm::XAes256Gcm);
874        let result = client
875            .unlock()
876            .unlock(UnlockMethod::SessionKey(SessionKey(wrong_key)))
877            .await;
878        assert!(matches!(result, Err(UnlockError::Unknown)));
879    }
880}