Skip to main content

bitwarden_core/key_management/
crypto.rs

1//! Mobile specific crypto operations
2//!
3//! This module contains temporary code for handling mobile specific cryptographic operations until
4//! the SDK is fully implemented. When porting functionality from `client` the mobile clients should
5//! be updated to consume the regular code paths and in this module should eventually disappear.
6
7#[cfg(any(feature = "uniffi", feature = "wasm"))]
8mod reinit_user_crypto;
9use std::collections::HashMap;
10
11use bitwarden_api_api::models::AccountKeysRequestModel;
12use bitwarden_crypto::{
13    CryptoError, DeviceKey, EncString, Kdf, KeyConnectorKey, KeyDecryptable, KeyEncryptable,
14    MasterKey, PrimitiveEncryptable, PublicKey, RotateableKeySet, SpkiPublicKeyBytes,
15    SymmetricCryptoKey, TrustDeviceResponse, UnsignedSharedKey, derive_symmetric_key_from_prf,
16    safe::{
17        PasswordProtectedKeyEnvelope, PasswordProtectedKeyEnvelopeError,
18        PasswordProtectedKeyEnvelopeNamespace,
19    },
20};
21use bitwarden_encoding::B64;
22use bitwarden_error::bitwarden_error;
23#[cfg(any(feature = "uniffi", feature = "wasm"))]
24pub(super) use reinit_user_crypto::reinit_user_crypto;
25#[cfg(any(feature = "uniffi", feature = "wasm"))]
26pub use reinit_user_crypto::{ReinitUserCryptoError, ReinitUserCryptoRequest};
27use schemars::JsonSchema;
28use serde::{Deserialize, Serialize};
29use tracing::info;
30
31#[cfg(feature = "wasm")]
32use crate::key_management::wasm_unlock_state::{copy_user_key_to_state, get_user_key_from_state};
33use crate::{
34    Client, NotAuthenticatedError, OrganizationId, UserId, WrongPasswordError,
35    client::{
36        LoginMethod, UserLoginMethod,
37        encryption_settings::EncryptionSettingsError,
38        persisted_state::{ACCOUNT_CRYPTO_STATE, OrganizationSharedKey},
39    },
40    key_management::{
41        MasterPasswordError, SymmetricKeySlotId, V2UpgradeToken,
42        account_cryptographic_state::{
43            AccountCryptographyInitializationError, WrappedAccountCryptographicState,
44        },
45        local_user_data_key_state::{
46            get_local_user_data_key_from_state, initialize_local_user_data_key_into_state,
47            migrate_local_user_data_key_for_user_key_upgrade,
48        },
49        master_password::{MasterPasswordAuthenticationData, MasterPasswordUnlockData},
50        pin_lock_system::{PinLockSystem, UnlockError},
51    },
52};
53
54/// Catch all error for mobile crypto operations.
55#[allow(missing_docs)]
56#[bitwarden_error(flat)]
57#[derive(Debug, thiserror::Error)]
58pub enum CryptoClientError {
59    #[error(transparent)]
60    NotAuthenticated(#[from] NotAuthenticatedError),
61    #[error(transparent)]
62    Crypto(#[from] bitwarden_crypto::CryptoError),
63    #[error("Invalid KDF settings")]
64    InvalidKdfSettings,
65    #[error(transparent)]
66    PasswordProtectedKeyEnvelope(#[from] PasswordProtectedKeyEnvelopeError),
67    #[error("Invalid PRF input")]
68    InvalidPrfInput,
69    #[error("Invalid upgrade token")]
70    InvalidUpgradeToken,
71    #[error("Upgrade token is required for V1 keys")]
72    UpgradeTokenRequired,
73    #[error("Invalid key type")]
74    InvalidKeyType,
75}
76
77/// State used for initializing the user cryptographic state.
78#[derive(Serialize, Deserialize, Debug)]
79#[serde(rename_all = "camelCase", deny_unknown_fields)]
80#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
81#[bitwarden_ffi::wasm_record]
82pub struct InitUserCryptoRequest {
83    /// The user's ID.
84    pub user_id: Option<UserId>,
85    /// The user's KDF parameters, as received from the prelogin request
86    pub kdf_params: Kdf,
87    /// The user's email address
88    pub email: String,
89    /// The user's account cryptographic state, containing their signature and
90    /// public-key-encryption keys, along with the signed security state, protected by the user key
91    pub account_cryptographic_state: WrappedAccountCryptographicState,
92    /// The method to decrypt the user's account symmetric key (user key)
93    pub method: InitUserCryptoMethod,
94    /// Optional V2 upgrade token for automatic key rotation from V1 to V2
95    #[serde(skip_serializing_if = "Option::is_none")]
96    pub upgrade_token: Option<V2UpgradeToken>,
97}
98
99/// The crypto method used to initialize the user cryptographic state.
100#[derive(Serialize, Deserialize, Debug)]
101#[serde(rename_all = "camelCase", deny_unknown_fields)]
102#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
103#[bitwarden_ffi::wasm_record]
104#[allow(clippy::large_enum_variant)]
105pub enum InitUserCryptoMethod {
106    /// Master Password Unlock
107    MasterPasswordUnlock {
108        /// The user's master password
109        password: String,
110        /// Contains the data needed to unlock with the master password
111        master_password_unlock: MasterPasswordUnlockData,
112    },
113    /// Read the user-key directly from client-managed state
114    /// Note: In contrast to [`InitUserCryptoMethod::DecryptedKey`], this does not update the state
115    /// after initalizing
116    #[cfg(feature = "wasm")]
117    ClientManagedState {},
118    /// Never lock and/or biometric unlock
119    DecryptedKey {
120        /// The user's decrypted encryption key, obtained using `get_user_encryption_key`
121        decrypted_user_key: String,
122    },
123    /// PIN
124    Pin {
125        /// The user's PIN
126        pin: String,
127        /// The user's symmetric crypto key, encrypted with the PIN. Use `derive_pin_key` to obtain
128        /// this.
129        pin_protected_user_key: EncString,
130    },
131    /// PIN state, where the PIN envelope is stored in persistent client-managed state
132    PinState {
133        /// The user's PIN
134        pin: String,
135    },
136    /// PIN Envelope
137    PinEnvelope {
138        /// The user's PIN
139        pin: String,
140        /// The user's symmetric crypto key, encrypted with the PIN-protected key envelope.
141        pin_protected_user_key_envelope: PasswordProtectedKeyEnvelope,
142    },
143    /// Auth request
144    AuthRequest {
145        /// Private Key generated by the `crate::auth::new_auth_request`.
146        request_private_key: B64,
147        /// The type of auth request
148        method: AuthRequestMethod,
149    },
150    /// Device Key
151    DeviceKey {
152        /// The device's DeviceKey
153        device_key: String,
154        /// The Device Private Key
155        protected_device_private_key: EncString,
156        /// The user's symmetric crypto key, encrypted with the Device Key.
157        device_protected_user_key: UnsignedSharedKey,
158    },
159    /// Key connector
160    KeyConnector {
161        /// Base64 encoded master key, retrieved from the key connector.
162        master_key: B64,
163        /// The user's encrypted symmetric crypto key
164        user_key: EncString,
165    },
166    /// In contrast to key-connector, this does all of the connection with key-connector in the sdk
167    KeyConnectorUrl {
168        /// The url to retrieve the key-connector-key from
169        url: String,
170        /// The encrypted user key, encrypted with the key connector key retrieved from the url
171        key_connector_key_wrapped_user_key: EncString,
172    },
173}
174
175/// Auth requests supports multiple initialization methods.
176#[derive(Serialize, Deserialize, Debug)]
177#[serde(rename_all = "camelCase", deny_unknown_fields)]
178#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
179#[bitwarden_ffi::wasm_record]
180pub enum AuthRequestMethod {
181    /// User Key
182    UserKey {
183        /// User Key protected by the private key provided in `AuthRequestResponse`.
184        protected_user_key: UnsignedSharedKey,
185    },
186    /// Master Key
187    MasterKey {
188        /// Master Key protected by the private key provided in `AuthRequestResponse`.
189        protected_master_key: UnsignedSharedKey,
190        /// User Key protected by the MasterKey, provided by the auth response.
191        auth_request_key: EncString,
192    },
193}
194
195/// Initialize the user's cryptographic state.
196#[bitwarden_logging::instrument(err)]
197pub(super) async fn initialize_user_crypto(
198    client: &Client,
199    req: InitUserCryptoRequest,
200) -> Result<(), EncryptionSettingsError> {
201    use bitwarden_crypto::{DeviceKey, PinKey};
202
203    use crate::auth::{auth_request_decrypt_master_key, auth_request_decrypt_user_key};
204
205    if let Some(user_id) = req.user_id {
206        client.internal.init_user_id(user_id).await?;
207    }
208
209    tracing::Span::current().record(
210        "user_id",
211        client.internal.get_user_id().map(|id| id.to_string()),
212    );
213
214    let account_crypto_state = req.account_cryptographic_state.to_owned();
215
216    #[cfg(feature = "wasm")]
217    let should_copy_user_key = matches!(
218        req.method,
219        InitUserCryptoMethod::MasterPasswordUnlock { .. }
220            | InitUserCryptoMethod::DecryptedKey { .. }
221            | InitUserCryptoMethod::PinEnvelope { .. }
222            | InitUserCryptoMethod::PinState { .. }
223            | InitUserCryptoMethod::KeyConnectorUrl { .. }
224            | InitUserCryptoMethod::AuthRequest { .. }
225            | InitUserCryptoMethod::ClientManagedState { .. }
226    );
227
228    match req.method {
229        InitUserCryptoMethod::MasterPasswordUnlock {
230            password,
231            master_password_unlock,
232        } => {
233            client
234                .internal
235                .initialize_user_crypto_master_password_unlock(
236                    password,
237                    master_password_unlock,
238                    account_crypto_state,
239                    &req.upgrade_token,
240                )?;
241        }
242        #[cfg(feature = "wasm")]
243        InitUserCryptoMethod::ClientManagedState {} => {
244            let user_key = get_user_key_from_state(client)
245                .await
246                .map_err(|_| EncryptionSettingsError::UserKeyStateRetrievalFailed)?;
247            client.internal.initialize_user_crypto_decrypted_key(
248                user_key,
249                account_crypto_state,
250                &req.upgrade_token,
251            )?;
252        }
253        InitUserCryptoMethod::DecryptedKey { decrypted_user_key } => {
254            let user_key = SymmetricCryptoKey::try_from(decrypted_user_key)?;
255            client.internal.initialize_user_crypto_decrypted_key(
256                user_key,
257                account_crypto_state,
258                &req.upgrade_token,
259            )?;
260        }
261        InitUserCryptoMethod::Pin {
262            pin,
263            pin_protected_user_key,
264        } => {
265            let pin_key = PinKey::derive(pin.as_bytes(), req.email.as_bytes(), &req.kdf_params)?;
266            client.internal.initialize_user_crypto_pin(
267                pin_key,
268                pin_protected_user_key,
269                account_crypto_state,
270                &req.upgrade_token,
271            )?;
272        }
273        InitUserCryptoMethod::PinEnvelope {
274            pin,
275            pin_protected_user_key_envelope,
276        } => {
277            client.internal.initialize_user_crypto_pin_envelope(
278                pin,
279                pin_protected_user_key_envelope,
280                account_crypto_state,
281                &req.upgrade_token,
282            )?;
283        }
284        InitUserCryptoMethod::PinState { pin } => {
285            PinLockSystem::with_client(client)
286                .unlock(pin.as_str())
287                .await
288                .map_err(|err| match err {
289                    UnlockError::PinWrong => EncryptionSettingsError::WrongPin,
290                    UnlockError::NoPinSet => EncryptionSettingsError::PinUnlockNotAvailable,
291                    UnlockError::InternalError => EncryptionSettingsError::CryptoInitialization,
292                })?;
293            // Note: PinLockSystem sets the user-key to state, and this section is reading it from
294            // state, then re-setting it via `initialize_user_crypto_decrypted_key`.
295            // This is not ideal and should be refactored in the future.
296            #[allow(deprecated)]
297            let user_key = client
298                .internal
299                .get_key_store()
300                .context()
301                .dangerous_get_symmetric_key(SymmetricKeySlotId::User)?
302                .to_owned();
303            // Otherwise the initialize will fail with a double init error.
304            client
305                .internal
306                .get_key_store()
307                .context_mut()
308                .drop_symmetric_key(SymmetricKeySlotId::User)?;
309
310            client.internal.initialize_user_crypto_decrypted_key(
311                user_key,
312                account_crypto_state,
313                &req.upgrade_token,
314            )?;
315        }
316        InitUserCryptoMethod::AuthRequest {
317            request_private_key,
318            method,
319        } => {
320            let user_key = match method {
321                AuthRequestMethod::UserKey { protected_user_key } => {
322                    auth_request_decrypt_user_key(request_private_key, protected_user_key)?
323                }
324                AuthRequestMethod::MasterKey {
325                    protected_master_key,
326                    auth_request_key,
327                } => auth_request_decrypt_master_key(
328                    request_private_key,
329                    protected_master_key,
330                    auth_request_key,
331                )?,
332            };
333            client.internal.initialize_user_crypto_decrypted_key(
334                user_key,
335                account_crypto_state,
336                &req.upgrade_token,
337            )?;
338        }
339        InitUserCryptoMethod::DeviceKey {
340            device_key,
341            protected_device_private_key,
342            device_protected_user_key,
343        } => {
344            let device_key = DeviceKey::try_from(device_key)?;
345            let user_key = device_key
346                .decrypt_user_key(protected_device_private_key, device_protected_user_key)?;
347
348            client.internal.initialize_user_crypto_decrypted_key(
349                user_key,
350                account_crypto_state,
351                &req.upgrade_token,
352            )?;
353        }
354        InitUserCryptoMethod::KeyConnector {
355            master_key,
356            user_key,
357        } => {
358            let bytes = master_key.into_bytes();
359            let master_key = MasterKey::try_from(bytes)?;
360
361            client.internal.initialize_user_crypto_key_connector_key(
362                master_key,
363                user_key,
364                account_crypto_state,
365                &req.upgrade_token,
366            )?;
367        }
368        InitUserCryptoMethod::KeyConnectorUrl {
369            url,
370            key_connector_key_wrapped_user_key,
371        } => {
372            let api_client = client.internal.get_key_connector_client(url);
373            let key_connector_key_response = api_client
374                .user_keys_api()
375                .get_user_key()
376                .await
377                .map_err(|_| EncryptionSettingsError::KeyConnectorRetrievalFailed)?;
378            let key_connector_key = KeyConnectorKey::try_from(key_connector_key_response)?;
379            let user_key =
380                key_connector_key.decrypt_user_key(key_connector_key_wrapped_user_key)?;
381            client.internal.initialize_user_crypto_decrypted_key(
382                user_key,
383                account_crypto_state,
384                &req.upgrade_token,
385            )?;
386        }
387    }
388
389    #[cfg(feature = "wasm")]
390    if should_copy_user_key {
391        copy_user_key_to_state(client)
392            .await
393            .map_err(|_| EncryptionSettingsError::UserKeyStateUpdateFailed)?;
394    }
395
396    on_unlock_handler(client).await?;
397
398    client
399        .internal
400        .set_login_method(LoginMethod::User(UserLoginMethod::Username {
401            client_id: "".to_string(),
402            email: req.email,
403            kdf: req.kdf_params,
404        }))
405        .await;
406
407    let _ = client
408        .internal
409        .state_registry
410        .value::<ACCOUNT_CRYPTO_STATE>()
411        .set(req.account_cryptographic_state)
412        .await;
413
414    info!("User crypto initialized successfully");
415
416    Ok(())
417}
418
419/// Represents the request to initialize the user's organizational cryptographic state.
420#[derive(Serialize, Deserialize, Debug)]
421#[serde(rename_all = "camelCase", deny_unknown_fields)]
422#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
423#[bitwarden_ffi::wasm_record]
424pub struct InitOrgCryptoRequest {
425    /// The encryption keys for all the organizations the user is a part of
426    pub organization_keys: HashMap<OrganizationId, UnsignedSharedKey>,
427}
428
429/// Initialize the user's organizational cryptographic state.
430pub(super) async fn initialize_org_crypto(
431    client: &Client,
432    req: InitOrgCryptoRequest,
433) -> Result<(), EncryptionSettingsError> {
434    let organization_keys: Vec<_> = req.organization_keys.into_iter().collect();
435    client
436        .internal
437        .initialize_org_crypto(organization_keys.clone())?;
438
439    // Persist org keys for rehydration
440    if let Ok(repo) = client
441        .internal
442        .state_registry
443        .get::<OrganizationSharedKey>()
444    {
445        for (org_id, key) in organization_keys {
446            if let Err(e) = repo
447                .set(org_id, OrganizationSharedKey { org_id, key })
448                .await
449            {
450                tracing::warn!("Failed to persist org key for {org_id}: {e}");
451            }
452        }
453    }
454
455    Ok(())
456}
457
458pub(super) async fn get_user_encryption_key(client: &Client) -> Result<B64, CryptoClientError> {
459    let key_store = client.internal.get_key_store();
460    let ctx = key_store.context();
461    // This is needed because the clients need access to the user encryption key
462    // in order to set side-effects such as biometrics, and never-lock
463    #[allow(deprecated)]
464    let user_key = ctx.dangerous_get_symmetric_key(SymmetricKeySlotId::User)?;
465
466    Ok(user_key.to_base64())
467}
468
469/// Response from the `update_kdf` function
470///
471/// Note: This is deprecated and will be removed after key-connector fully uses sdk
472#[derive(Serialize, Deserialize, Debug)]
473#[serde(rename_all = "camelCase", deny_unknown_fields)]
474#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
475#[bitwarden_ffi::wasm_record]
476pub struct UpdateKdfResponse {
477    /// The authentication data for the new KDF setting
478    master_password_authentication_data: MasterPasswordAuthenticationData,
479    /// The unlock data for the new KDF setting
480    master_password_unlock_data: MasterPasswordUnlockData,
481    /// The authentication data for the KDF setting prior to the change
482    old_master_password_authentication_data: MasterPasswordAuthenticationData,
483}
484
485// Note: This is deprecated and will be removed after key-connector fully uses sdk
486pub(super) async fn make_update_kdf(
487    client: &Client,
488    password: &str,
489    new_kdf: &Kdf,
490) -> Result<UpdateKdfResponse, CryptoClientError> {
491    let login_method = client
492        .internal
493        .get_login_method()
494        .await
495        .ok_or(NotAuthenticatedError)?;
496    let email = match login_method {
497        UserLoginMethod::Username { email, .. } | UserLoginMethod::ApiKey { email, .. } => email,
498    };
499
500    let old_authentication_data = MasterPasswordAuthenticationData::derive(
501        password,
502        &client
503            .internal
504            .get_kdf()
505            .await
506            .map_err(|_| NotAuthenticatedError)?,
507        &email,
508    )
509    .map_err(|_| CryptoClientError::InvalidKdfSettings)?;
510
511    let key_store = client.internal.get_key_store();
512    let ctx = key_store.context();
513
514    let authentication_data = MasterPasswordAuthenticationData::derive(password, new_kdf, &email)
515        .map_err(|_| CryptoClientError::InvalidKdfSettings)?;
516    let unlock_data =
517        MasterPasswordUnlockData::derive(password, new_kdf, &email, SymmetricKeySlotId::User, &ctx)
518            .map_err(|_| CryptoClientError::InvalidKdfSettings)?;
519
520    Ok(UpdateKdfResponse {
521        master_password_authentication_data: authentication_data,
522        master_password_unlock_data: unlock_data,
523        old_master_password_authentication_data: old_authentication_data,
524    })
525}
526
527/// Response from the `make_update_password` function
528#[derive(Serialize, Deserialize, Debug)]
529#[serde(rename_all = "camelCase", deny_unknown_fields)]
530#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
531#[bitwarden_ffi::wasm_record]
532pub struct UpdatePasswordResponse {
533    /// Hash of the new password
534    password_hash: B64,
535    /// User key, encrypted with the new password
536    new_key: EncString,
537}
538
539pub(super) async fn make_update_password(
540    client: &Client,
541    new_password: String,
542) -> Result<UpdatePasswordResponse, CryptoClientError> {
543    let login_method = client
544        .internal
545        .get_login_method()
546        .await
547        .ok_or(NotAuthenticatedError)?;
548
549    let key_store = client.internal.get_key_store();
550    let ctx = key_store.context();
551    // FIXME: [PM-18099] Once MasterKey deals with KeySlotIds, this should be updated
552    #[allow(deprecated)]
553    let user_key = ctx.dangerous_get_symmetric_key(SymmetricKeySlotId::User)?;
554
555    // Derive a new master key from password
556    let new_master_key = match login_method {
557        UserLoginMethod::Username { email, kdf, .. }
558        | UserLoginMethod::ApiKey { email, kdf, .. } => {
559            MasterKey::derive(&new_password, &email, &kdf)?
560        }
561    };
562
563    let new_key = new_master_key.encrypt_user_key(user_key)?;
564
565    let password_hash = new_master_key.derive_master_key_hash(
566        new_password.as_bytes(),
567        bitwarden_crypto::HashPurpose::ServerAuthorization,
568    );
569
570    Ok(UpdatePasswordResponse {
571        password_hash,
572        new_key,
573    })
574}
575
576/// Request for deriving a pin protected user key
577#[derive(Serialize, Deserialize, Debug)]
578#[serde(rename_all = "camelCase", deny_unknown_fields)]
579#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
580#[bitwarden_ffi::wasm_record]
581pub struct EnrollPinResponse {
582    /// [UserKey][bitwarden_crypto::UserKey] protected by PIN
583    pub pin_protected_user_key_envelope: PasswordProtectedKeyEnvelope,
584    /// PIN protected by [UserKey][bitwarden_crypto::UserKey]
585    pub user_key_encrypted_pin: EncString,
586}
587
588pub(super) fn enroll_pin(
589    client: &Client,
590    pin: String,
591) -> Result<EnrollPinResponse, CryptoClientError> {
592    let key_store = client.internal.get_key_store();
593    let mut ctx = key_store.context_mut();
594
595    let key_envelope = PasswordProtectedKeyEnvelope::seal(
596        SymmetricKeySlotId::User,
597        &pin,
598        PasswordProtectedKeyEnvelopeNamespace::PinUnlock,
599        &ctx,
600    )?;
601    let encrypted_pin = pin.encrypt(&mut ctx, SymmetricKeySlotId::User)?;
602    Ok(EnrollPinResponse {
603        pin_protected_user_key_envelope: key_envelope,
604        user_key_encrypted_pin: encrypted_pin,
605    })
606}
607
608/// Request for deriving a pin protected user key
609#[derive(Serialize, Deserialize, Debug)]
610#[serde(rename_all = "camelCase", deny_unknown_fields)]
611#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
612#[bitwarden_ffi::wasm_record]
613pub struct DerivePinKeyResponse {
614    /// [UserKey][bitwarden_crypto::UserKey] protected by PIN
615    pin_protected_user_key: EncString,
616    /// PIN protected by [UserKey][bitwarden_crypto::UserKey]
617    encrypted_pin: EncString,
618}
619
620pub(super) async fn derive_pin_key(
621    client: &Client,
622    pin: String,
623) -> Result<DerivePinKeyResponse, CryptoClientError> {
624    let login_method = client
625        .internal
626        .get_login_method()
627        .await
628        .ok_or(NotAuthenticatedError)?;
629
630    let key_store = client.internal.get_key_store();
631    let ctx = key_store.context();
632    // FIXME: [PM-18099] Once PinKey deals with KeySlotIds, this should be updated
633    #[allow(deprecated)]
634    let user_key = ctx.dangerous_get_symmetric_key(SymmetricKeySlotId::User)?;
635
636    let pin_protected_user_key = derive_pin_protected_user_key(&pin, &login_method, user_key)?;
637
638    Ok(DerivePinKeyResponse {
639        pin_protected_user_key,
640        encrypted_pin: pin.encrypt_with_key(user_key)?,
641    })
642}
643
644pub(super) async fn derive_pin_user_key(
645    client: &Client,
646    encrypted_pin: EncString,
647) -> Result<EncString, CryptoClientError> {
648    let login_method = client
649        .internal
650        .get_login_method()
651        .await
652        .ok_or(NotAuthenticatedError)?;
653
654    let key_store = client.internal.get_key_store();
655    let ctx = key_store.context();
656    // FIXME: [PM-18099] Once PinKey deals with KeySlotIds, this should be updated
657    #[allow(deprecated)]
658    let user_key = ctx.dangerous_get_symmetric_key(SymmetricKeySlotId::User)?;
659
660    let pin: String = encrypted_pin.decrypt_with_key(user_key)?;
661
662    derive_pin_protected_user_key(&pin, &login_method, user_key)
663}
664
665fn derive_pin_protected_user_key(
666    pin: &str,
667    login_method: &UserLoginMethod,
668    user_key: &SymmetricCryptoKey,
669) -> Result<EncString, CryptoClientError> {
670    use bitwarden_crypto::PinKey;
671
672    let derived_key = match login_method {
673        UserLoginMethod::Username { email, kdf, .. }
674        | UserLoginMethod::ApiKey { email, kdf, .. } => {
675            PinKey::derive(pin.as_bytes(), email.as_bytes(), kdf)?
676        }
677    };
678
679    Ok(derived_key.encrypt_user_key(user_key)?)
680}
681
682pub(super) fn make_prf_user_key_set(
683    client: &Client,
684    prf: B64,
685) -> Result<RotateableKeySet, CryptoClientError> {
686    let prf_key = derive_symmetric_key_from_prf(prf.as_bytes())
687        .map_err(|_| CryptoClientError::InvalidPrfInput)?;
688    let ctx = client.internal.get_key_store().context();
689    let key_set = RotateableKeySet::new(&ctx, &prf_key, SymmetricKeySlotId::User)?;
690    Ok(key_set)
691}
692
693#[allow(missing_docs)]
694#[bitwarden_error(flat)]
695#[derive(Debug, thiserror::Error)]
696pub enum EnrollAdminPasswordResetError {
697    #[error(transparent)]
698    Crypto(#[from] bitwarden_crypto::CryptoError),
699}
700
701pub(super) fn enroll_admin_password_reset(
702    client: &Client,
703    public_key: B64,
704) -> Result<UnsignedSharedKey, EnrollAdminPasswordResetError> {
705    use bitwarden_crypto::PublicKey;
706
707    let public_key = PublicKey::from_der(&SpkiPublicKeyBytes::from(&public_key))?;
708    let key_store = client.internal.get_key_store();
709    let ctx = key_store.context();
710    // FIXME: [PM-18110] This should be removed once the key store can handle public key encryption
711    #[allow(deprecated)]
712    let key = ctx.dangerous_get_symmetric_key(SymmetricKeySlotId::User)?;
713
714    #[expect(deprecated)]
715    Ok(UnsignedSharedKey::encapsulate_key_unsigned(
716        key,
717        &public_key,
718    )?)
719}
720
721/// Request for migrating an account from password to key connector.
722#[derive(Serialize, Deserialize, Debug, JsonSchema)]
723#[serde(rename_all = "camelCase", deny_unknown_fields)]
724#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
725#[bitwarden_ffi::wasm_record]
726pub struct DeriveKeyConnectorRequest {
727    /// Encrypted user key, used to validate the master key
728    pub user_key_encrypted: EncString,
729    /// The user's master password
730    pub password: String,
731    /// The KDF parameters used to derive the master key
732    pub kdf: Kdf,
733    /// The user's email address
734    pub email: String,
735}
736
737#[allow(missing_docs)]
738#[bitwarden_error(flat)]
739#[derive(Debug, thiserror::Error)]
740pub enum DeriveKeyConnectorError {
741    #[error(transparent)]
742    WrongPassword(#[from] WrongPasswordError),
743    #[error(transparent)]
744    Crypto(#[from] bitwarden_crypto::CryptoError),
745}
746
747/// Derive the master key for migrating to the key connector
748pub(super) fn derive_key_connector(
749    request: DeriveKeyConnectorRequest,
750) -> Result<B64, DeriveKeyConnectorError> {
751    let master_key = MasterKey::derive(&request.password, &request.email, &request.kdf)?;
752    master_key
753        .decrypt_user_key(request.user_key_encrypted)
754        .map_err(|_| WrongPasswordError)?;
755
756    Ok(master_key.to_base64())
757}
758
759/// The response from `make_user_tde_registration`.
760pub struct MakeTdeRegistrationResponse {
761    /// The account cryptographic state
762    pub account_cryptographic_state: WrappedAccountCryptographicState,
763    /// The user's user key
764    pub user_key: SymmetricCryptoKey,
765    /// The request model for the account cryptographic state (also called Account Keys)
766    pub account_keys_request: AccountKeysRequestModel,
767    /// The keys needed to set up TDE decryption
768    pub trusted_device_keys: TrustDeviceResponse,
769    /// The key needed for admin password reset
770    pub reset_password_key: UnsignedSharedKey,
771}
772
773/// The response from `make_user_jit_master_password_registration`.
774pub struct MakeJitMasterPasswordRegistrationResponse {
775    /// The account cryptographic state
776    pub account_cryptographic_state: WrappedAccountCryptographicState,
777    /// The user's user key
778    pub user_key: SymmetricCryptoKey,
779    /// The master password unlock data
780    pub master_password_authentication_data: MasterPasswordAuthenticationData,
781    /// The master password unlock data
782    pub master_password_unlock_data: MasterPasswordUnlockData,
783    /// The request model for the account cryptographic state (also called Account Keys)
784    pub account_keys_request: AccountKeysRequestModel,
785    /// The key needed for admin password reset
786    pub reset_password_key: UnsignedSharedKey,
787}
788
789/// Errors that can occur when making keys for account cryptography registration.
790#[bitwarden_error(flat)]
791#[derive(Debug, thiserror::Error)]
792pub enum MakeKeysError {
793    /// Failed to initialize account cryptography
794    #[error("Failed to initialize account cryptography")]
795    AccountCryptographyInitialization(AccountCryptographyInitializationError),
796    /// Failed to derive master password
797    #[error("Failed to derive master password")]
798    MasterPasswordDerivation(MasterPasswordError),
799    /// Failed to create request model
800    #[error("Failed to make a request model")]
801    RequestModelCreation,
802    /// Generic crypto error
803    #[error("Cryptography error: {0}")]
804    Crypto(#[from] CryptoError),
805}
806
807/// Create the data needed to register for TDE (Trusted Device Enrollment)
808pub(crate) fn make_user_tde_registration(
809    client: &Client,
810    org_public_key: B64,
811) -> Result<MakeTdeRegistrationResponse, MakeKeysError> {
812    let mut ctx = client.internal.get_key_store().context_mut();
813    let (user_key_id, wrapped_state) = WrappedAccountCryptographicState::make(&mut ctx)
814        .map_err(MakeKeysError::AccountCryptographyInitialization)?;
815    // TDE unlock method
816    #[expect(deprecated)]
817    let device_key = DeviceKey::trust_device(ctx.dangerous_get_symmetric_key(user_key_id)?)?;
818
819    // Account recovery enrollment
820    let public_key = PublicKey::from_der(&SpkiPublicKeyBytes::from(&org_public_key))
821        .map_err(MakeKeysError::Crypto)?;
822    #[expect(deprecated)]
823    let admin_reset = UnsignedSharedKey::encapsulate_key_unsigned(
824        ctx.dangerous_get_symmetric_key(user_key_id)?,
825        &public_key,
826    )
827    .map_err(MakeKeysError::Crypto)?;
828
829    let cryptography_state_request_model = wrapped_state
830        .to_request_model(&user_key_id, &mut ctx)
831        .map_err(|_| MakeKeysError::RequestModelCreation)?;
832
833    #[expect(deprecated)]
834    Ok(MakeTdeRegistrationResponse {
835        account_cryptographic_state: wrapped_state,
836        user_key: ctx.dangerous_get_symmetric_key(user_key_id)?.to_owned(),
837        account_keys_request: cryptography_state_request_model,
838        trusted_device_keys: device_key,
839        reset_password_key: admin_reset,
840    })
841}
842
843/// The response from `make_user_key_connector_registration`.
844pub struct MakeKeyConnectorRegistrationResponse {
845    /// The account cryptographic state
846    pub account_cryptographic_state: WrappedAccountCryptographicState,
847    /// Encrypted user's user key, wrapped with the key connector key
848    pub key_connector_key_wrapped_user_key: EncString,
849    /// The user's user key
850    pub user_key: SymmetricCryptoKey,
851    /// The request model for the account cryptographic state (also called Account Keys)
852    pub account_keys_request: AccountKeysRequestModel,
853    /// The key connector key used for unlocking
854    pub key_connector_key: KeyConnectorKey,
855}
856
857/// Create the data needed to register for Key Connector
858pub(crate) fn make_user_key_connector_registration(
859    client: &Client,
860) -> Result<MakeKeyConnectorRegistrationResponse, MakeKeysError> {
861    let mut ctx = client.internal.get_key_store().context_mut();
862    let (user_key_id, wrapped_state) = WrappedAccountCryptographicState::make(&mut ctx)
863        .map_err(MakeKeysError::AccountCryptographyInitialization)?;
864    #[expect(deprecated)]
865    let user_key = ctx.dangerous_get_symmetric_key(user_key_id)?.to_owned();
866
867    // Key Connector unlock method
868    let key_connector_key = KeyConnectorKey::make();
869
870    let wrapped_user_key = key_connector_key
871        .encrypt_user_key(&user_key)
872        .map_err(MakeKeysError::Crypto)?;
873
874    let cryptography_state_request_model =
875        wrapped_state
876            .to_request_model(&user_key_id, &mut ctx)
877            .map_err(MakeKeysError::AccountCryptographyInitialization)?;
878
879    Ok(MakeKeyConnectorRegistrationResponse {
880        account_cryptographic_state: wrapped_state,
881        key_connector_key_wrapped_user_key: wrapped_user_key,
882        user_key,
883        account_keys_request: cryptography_state_request_model,
884        key_connector_key,
885    })
886}
887
888/// Ensures the [`SymmetricKeySlotId::LocalUserData`] key is loaded into the key store context.
889///
890/// On first call the key is generated (wrapping the user key with itself) and persisted to state.
891/// Subsequent calls are idempotent: if the key already exists in state it is loaded as-is,
892/// preserving any data that was previously encrypted with it (e.g. after a key rotation).
893async fn initialize_user_local_data_key(client: &Client) -> Result<(), EncryptionSettingsError> {
894    let user_id = client
895        .internal
896        .get_user_id()
897        .ok_or(EncryptionSettingsError::LocalUserDataKeyInitFailed)?;
898
899    migrate_local_user_data_key_for_user_key_upgrade(client, user_id)
900        .await
901        .map_err(|_| EncryptionSettingsError::LocalUserDataMigrationFailed)?;
902
903    initialize_local_user_data_key_into_state(client, user_id)
904        .await
905        .map_err(|_| EncryptionSettingsError::LocalUserDataKeyInitFailed)?;
906
907    let wrapped_key = get_local_user_data_key_from_state(client, user_id)
908        .await
909        .map_err(|_| EncryptionSettingsError::LocalUserDataKeyLoadFailed)?;
910    let mut ctx = client.internal.get_key_store().context_mut();
911    wrapped_key
912        .unwrap_to_context(&mut ctx)
913        .map_err(|_| EncryptionSettingsError::LocalUserDataKeyLoadFailed)
914}
915
916/// Runs the code needed post unlock used by `initialize_user_crypto` and `reinit_user_crypto`.
917///
918/// Both code paths leave the SDK in an unlocked state with the active user key in the key store,
919/// and both need to ensure derived per-user state is consistent with that user key before clients
920/// can use the session.
921async fn on_unlock_handler(client: &Client) -> Result<(), EncryptionSettingsError> {
922    initialize_user_local_data_key(client).await?;
923
924    // A browser extension's background unlocks along with each open popup. Concurrent PIN
925    // migrations race on the PIN state, and each envelope reseal runs a full KDF, so only one
926    // client runs them.
927    if client
928        .internal
929        .crypto_settings
930        .perform_local_unlock_migrations()
931    {
932        PinLockSystem::on_unlock(&PinLockSystem::with_client(client)).await;
933    }
934
935    Ok(())
936}
937
938/// Create the data needed to register for JIT master password
939pub(crate) fn make_user_jit_master_password_registration(
940    client: &Client,
941    master_password: String,
942    salt: String,
943    org_public_key: B64,
944) -> Result<MakeJitMasterPasswordRegistrationResponse, MakeKeysError> {
945    let mut ctx = client.internal.get_key_store().context_mut();
946    let (user_key_id, wrapped_state) = WrappedAccountCryptographicState::make(&mut ctx)
947        .map_err(MakeKeysError::AccountCryptographyInitialization)?;
948
949    let kdf = ctx.cipher_suite().default_kdf_for_new_account();
950
951    #[expect(deprecated)]
952    let user_key = ctx.dangerous_get_symmetric_key(user_key_id)?.to_owned();
953
954    let master_password_unlock_data =
955        MasterPasswordUnlockData::derive(&master_password, &kdf, &salt, user_key_id, &ctx)
956            .map_err(MakeKeysError::MasterPasswordDerivation)?;
957
958    let master_password_authentication_data =
959        MasterPasswordAuthenticationData::derive(&master_password, &kdf, &salt)
960            .map_err(MakeKeysError::MasterPasswordDerivation)?;
961
962    let cryptography_state_request_model = wrapped_state
963        .to_request_model(&user_key_id, &mut ctx)
964        .map_err(|_| MakeKeysError::RequestModelCreation)?;
965
966    // Account recovery enrollment
967    let public_key = PublicKey::from_der(&SpkiPublicKeyBytes::from(&org_public_key))
968        .map_err(MakeKeysError::Crypto)?;
969    let admin_reset_key = UnsignedSharedKey::encapsulate(user_key_id, &public_key, &ctx)
970        .map_err(MakeKeysError::Crypto)?;
971
972    Ok(MakeJitMasterPasswordRegistrationResponse {
973        account_cryptographic_state: wrapped_state,
974        user_key,
975        master_password_unlock_data,
976        master_password_authentication_data,
977        account_keys_request: cryptography_state_request_model,
978        reset_password_key: admin_reset_key,
979    })
980}
981
982/// Response from `make_user_password_registration`
983pub struct MakeUserMasterPasswordRegistrationResponse {
984    /// The wrapped account cryptographic state
985    pub account_cryptographic_state: WrappedAccountCryptographicState,
986    /// The master password unlock data
987    pub master_password_unlock_data: MasterPasswordUnlockData,
988    /// The master password authentication data
989    pub master_password_authentication_data: MasterPasswordAuthenticationData,
990    /// The request model for account cryptographic key state
991    pub account_keys_request: AccountKeysRequestModel,
992    /// The user's user key
993    pub user_key: SymmetricCryptoKey,
994}
995
996/// Creates cryptographic data needed for user master password registration
997pub(crate) fn make_user_password_registration(
998    client: &Client,
999    master_password: String,
1000    salt: String,
1001) -> Result<MakeUserMasterPasswordRegistrationResponse, MakeKeysError> {
1002    // make_user_v2_crypto_state() - Creates user key (XAES-256-GCM), RSA key pair, ML-DSA
1003    // signing key pair, and signed security state
1004    let mut ctx = client.internal.get_key_store().context_mut();
1005    let (user_key_id, wrapped_state) = WrappedAccountCryptographicState::make(&mut ctx)
1006        .map_err(MakeKeysError::AccountCryptographyInitialization)?;
1007
1008    let kdf = ctx.cipher_suite().default_kdf_for_new_account();
1009
1010    #[expect(deprecated)]
1011    let user_key = ctx.dangerous_get_symmetric_key(user_key_id)?.to_owned();
1012
1013    let master_password_unlock_data =
1014        MasterPasswordUnlockData::derive(&master_password, &kdf, &salt, user_key_id, &ctx)
1015            .map_err(MakeKeysError::MasterPasswordDerivation)?;
1016
1017    let master_password_authentication_data =
1018        MasterPasswordAuthenticationData::derive(&master_password, &kdf, &salt)
1019            .map_err(MakeKeysError::MasterPasswordDerivation)?;
1020
1021    let account_keys_request = wrapped_state
1022        .to_request_model(&user_key_id, &mut ctx)
1023        .map_err(|_| MakeKeysError::RequestModelCreation)?;
1024
1025    Ok(MakeUserMasterPasswordRegistrationResponse {
1026        account_cryptographic_state: wrapped_state,
1027        master_password_unlock_data,
1028        master_password_authentication_data,
1029        account_keys_request,
1030        user_key,
1031    })
1032}
1033
1034#[cfg(test)]
1035mod tests {
1036    use std::num::NonZeroU32;
1037
1038    use bitwarden_crypto::{
1039        Decryptable, KeyStore, Pkcs8PrivateKeyBytes, PrivateKey, PublicKeyEncryptionAlgorithm,
1040        SymmetricKeyAlgorithm,
1041    };
1042
1043    use super::*;
1044    use crate::{
1045        Client,
1046        client::test_accounts::{test_bitwarden_com_account, test_bitwarden_com_account_v2},
1047        key_management::{
1048            KeySlotIds, PrivateKeySlotId, V2UpgradeToken,
1049            state_bridge::test_support::InMemoryStateBridge,
1050        },
1051    };
1052
1053    const TEST_VECTOR_USER_KEY_V2_B64: &str = "pQEEAlCxZkKFDpp70P5mWPmOjf3xAzoAARF5BIQDBAUGIFggCFcd6XLISUfLaITyU9yimrYHacdS5XhBayO2663jdSUB";
1054    const TEST_VECTO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DfKV2qQoofQMH9VvkWO4psaWDjBSdwIDAQAB";
1057    #[allow(unused)]
1058    const TEST_VECTOR_SIGNED_PUBLIC_KEY_V2: &str = "hFgepAEnAxg8BFAmkP0QgfdMVbIujX55W/yNOgABOH8BoFkBTqNpYWxnb3JpdGhtAG1jb250ZW50Rm9ybWF0AGlwdWJsaWNLZXlZASYwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDP/7WM8nUepxoJ0qtM+azxcly+eZ31qUjjZTZcX/gYw1MzkoXWAjqyeFH/bdktq1lEUwegrxkIxKkY2SMtp0CvPnaV1x5O8E6FBSJbKWRlDg181rfEhgm5tc6aR4PJ827IvFVm9xk6Sj091P5DHZDEOsWLZc2jYjtpUV3X38I4gSR7HiYnR4DcwcWkoJ3FhtxMCwYgPz6RVH0vzhLUmm1mgbzH6IH8Pf9DjLTZSxBikVO7S9s9jzhiZbTeeAl3FbNLxfj9Qkj+NoSfms7jGVTlBwvSXgjJs/ktGkT1cR5QcBMpU4bt41+l73MN8pXapCih9Awf1W+RY7imxpYOMFJ3AgMBAAFYQMq/hT4wod2w8xyoM7D86ctuLNX4ZRo+jRHf2sZfaO7QsvonG/ZYuNKF5fq8wpxMRjfoMvnY2TTShbgzLrW8BA4=";
1059    const TEST_VECTOR_SIGNING_KEY_V2: &str = "7.g1gcowE6AAEReQMYZQRQsWZChQ6ae9D+Zlj5jo398aEFWBj8Gg/gn4tQKWO3nq5e/2p9gkzIrKD829RYT3aEUIDOetEtnFqRuQ3Cz13693WqDnKHM5Buzi6LcTsxo1jphYR7vlE5nYLjCpOCAftPN1oLfs5SCNkwwMENhujpVftfDzciE99aLEJDS9A=";
1060    #[allow(unused)]
1061    const TEST_VECTOR_VERIFYING_KEY_V2: &str =
1062        "pgEBAlAmkP0QgfdMVbIujX55W/yNAycEgQIgBiFYIEM6JxBmjWQTruAm3s6BTaJy1q6BzQetMBacNeRJ0kxR";
1063    const TEST_VECTOR_SECURITY_STATE_V2: &str = "hFgepAEnAxg8BFAmkP0QgfdMVbIujX55W/yNOgABOH8CoFgkomhlbnRpdHlJZFBHOOw2BI9OQoNq+Vl1xZZKZ3ZlcnNpb24CWEAlchbJR0vmRfShG8On7Q2gknjkw4Dd6MYBLiH4u+/CmfQdmjNZdf6kozgW/6NXyKVNu8dAsKsin+xxXkDyVZoG";
1064
1065    const TEST_USER_EMAIL: &str = "[email protected]";
1066    const TEST_USER_PASSWORD: &str = "asdfasdfasdf";
1067    const TEST_ACCOUNT_USER_KEY: &str = "2.Q/2PhzcC7GdeiMHhWguYAQ==|GpqzVdr0go0ug5cZh1n+uixeBC3oC90CIe0hd/HWA/pTRDZ8ane4fmsEIcuc8eMKUt55Y2q/fbNzsYu41YTZzzsJUSeqVjT8/iTQtgnNdpo=|dwI+uyvZ1h/iZ03VQ+/wrGEFYVewBUUl/syYgjsNMbE=";
1068    const TEST_ACCOUNT_PRIVATE_KEY: &str = "2.yN7l00BOlUE0Sb0M//Q53w==|EwKG/BduQRQ33Izqc/ogoBROIoI5dmgrxSo82sgzgAMIBt3A2FZ9vPRMY+GWT85JiqytDitGR3TqwnFUBhKUpRRAq4x7rA6A1arHrFp5Tp1p21O3SfjtvB3quiOKbqWk6ZaU1Np9HwqwAecddFcB0YyBEiRX3VwF2pgpAdiPbSMuvo2qIgyob0CUoC/h4Bz1be7Qa7B0Xw9/fMKkB1LpOm925lzqosyMQM62YpMGkjMsbZz0uPopu32fxzDWSPr+kekNNyLt9InGhTpxLmq1go/pXR2uw5dfpXc5yuta7DB0EGBwnQ8Vl5HPdDooqOTD9I1jE0mRyuBpWTTI3FRnu3JUh3rIyGBJhUmHqGZvw2CKdqHCIrQeQkkEYqOeJRJVdBjhv5KGJifqT3BFRwX/YFJIChAQpebNQKXe/0kPivWokHWwXlDB7S7mBZzhaAPidZvnuIhalE2qmTypDwHy22FyqV58T8MGGMchcASDi/QXI6kcdpJzPXSeU9o+NC68QDlOIrMVxKFeE7w7PvVmAaxEo0YwmuAzzKy9Qpd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uPM=|09J28iXv9oWzYtzK2LBT6Yht4IT4MijEkk0fwFdrVQ4=";
1069
1070    async fn init_v2_account_with_master_password_and_upgrade_token(
1071        client: &Client,
1072        user_id: UserId,
1073        upgrade_token: V2UpgradeToken,
1074    ) {
1075        initialize_user_crypto(
1076            client,
1077            InitUserCryptoRequest {
1078                user_id: Some(user_id),
1079                kdf_params: Kdf::PBKDF2 {
1080                    iterations: 600_000.try_into().unwrap(),
1081                },
1082                email: TEST_USER_EMAIL.into(),
1083                account_cryptographic_state: WrappedAccountCryptographicState::V2 {
1084                    private_key: TEST_VECTOR_PRIVATE_KEY_V2.parse().unwrap(),
1085                    signing_key: TEST_VECTOR_SIGNING_KEY_V2.parse().unwrap(),
1086                    security_state: TEST_VECTOR_SECURITY_STATE_V2.parse().unwrap(),
1087                    signed_public_key: TEST_VECTOR_SIGNED_PUBLIC_KEY_V2.parse().unwrap(),
1088                },
1089                method: InitUserCryptoMethod::MasterPasswordUnlock {
1090                    password: TEST_USER_PASSWORD.into(),
1091                    master_password_unlock: MasterPasswordUnlockData {
1092                        kdf: Kdf::PBKDF2 {
1093                            iterations: 600_000.try_into().unwrap(),
1094                        },
1095                        master_key_wrapped_user_key: TEST_ACCOUNT_USER_KEY.parse().unwrap(),
1096                        salt: TEST_USER_EMAIL.to_string(),
1097                        contained_key_id: None,
1098                    },
1099                },
1100                upgrade_token: Some(upgrade_token),
1101            },
1102        )
1103        .await
1104        .unwrap();
1105    }
1106
1107    #[tokio::test]
1108    async fn test_update_kdf() {
1109        let client = Client::new_test(None);
1110
1111        let priv_key: EncString = "2.kmLY8NJVuiKBFJtNd/ZFpA==|qOodlRXER+9ogCe3yOibRHmUcSNvjSKhdDuztLlucs10jLiNoVVVAc+9KfNErLSpx5wmUF1hBOJM8zwVPjgQTrmnNf/wuDpwiaCxNYb/0v4FygPy7ccAHK94xP1lfqq7U9+tv+/yiZSwgcT+xF0wFpoxQeNdNRFzPTuD9o4134n8bzacD9DV/WjcrXfRjbBCzzu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dVpePF5uSCE+TPav/9FIRGXGiFn6NJMaU7aBsDTFBLloffFLYDpd8/bTwoSvifkj7buwLYM+h/qcnfdy5FWau1cKav+Blq/ZC0qBpo658RTC8ZtseAFDgXoQZuksM10hpP9bzD04Bx30xTGX81QbaSTNwSEEVrOtIhbDrj9OI43KH4O6zLzK+t30QxAv5zjk10RZ4+5SAdYndIlld9Y62opCfPDzRy3ubdve4ZEchpIKWTQvIxq3T5ogOhGaWBVYnkMtM2GVqvWV//46gET5SH/MdcwhACUcZ9kCpMnWH9CyyUwYvTT3UlNyV+DlS27LMPvaw7tx7qa+GfNCoCBd8S4esZpQYK/WReiS8=|pc7qpD42wxyXemdNPuwxbh8iIaryrBPu8f/DGwYdHTw=".parse().unwrap();
1112
1113        let kdf = Kdf::PBKDF2 {
1114            iterations: 100_000.try_into().unwrap(),
1115        };
1116
1117        initialize_user_crypto(
1118            &client,
1119            InitUserCryptoRequest {
1120                user_id: Some(UserId::new_v4()),
1121                kdf_params: kdf.clone(),
1122                email: "[email protected]".into(),
1123                account_cryptographic_state: WrappedAccountCryptographicState::V1 { private_key: priv_key.to_owned() },
1124                method: InitUserCryptoMethod::MasterPasswordUnlock {
1125                    password: "asdfasdfasdf".into(),
1126                    master_password_unlock: MasterPasswordUnlockData {
1127                        kdf: kdf.clone(),
1128                        master_key_wrapped_user_key: "2.u2HDQ/nH2J7f5tYHctZx6Q==|NnUKODz8TPycWJA5svexe1wJIz2VexvLbZh2RDfhj5VI3wP8ZkR0Vicvdv7oJRyLI1GyaZDBCf9CTBunRTYUk39DbZl42Rb+Xmzds02EQhc=|rwuo5wgqvTJf3rgwOUfabUyzqhguMYb3sGBjOYqjevc=".parse().unwrap(),
1129                        salt: "[email protected]".to_string(),
1130                        contained_key_id: None,
1131                    },
1132                },
1133                upgrade_token: None,
1134            },
1135        )
1136            .await
1137            .unwrap();
1138
1139        let new_kdf = Kdf::PBKDF2 {
1140            iterations: 600_000.try_into().unwrap(),
1141        };
1142        let new_kdf_response = make_update_kdf(&client, "123412341234", &new_kdf)
1143            .await
1144            .unwrap();
1145
1146        let client2 = Client::new_test(None);
1147
1148        initialize_user_crypto(
1149            &client2,
1150            InitUserCryptoRequest {
1151                user_id: Some(UserId::new_v4()),
1152                kdf_params: new_kdf.clone(),
1153                email: "[email protected]".into(),
1154                account_cryptographic_state: WrappedAccountCryptographicState::V1 {
1155                    private_key: priv_key.to_owned(),
1156                },
1157                method: InitUserCryptoMethod::MasterPasswordUnlock {
1158                    password: "123412341234".to_string(),
1159                    master_password_unlock: MasterPasswordUnlockData {
1160                        kdf: new_kdf.clone(),
1161                        master_key_wrapped_user_key: new_kdf_response
1162                            .master_password_unlock_data
1163                            .master_key_wrapped_user_key,
1164                        salt: "[email protected]".to_string(),
1165                        contained_key_id: None,
1166                    },
1167                },
1168                upgrade_token: None,
1169            },
1170        )
1171        .await
1172        .unwrap();
1173
1174        let new_hash = client2
1175            .kdf()
1176            .hash_password(
1177                "[email protected]".into(),
1178                "123412341234".into(),
1179                new_kdf.clone(),
1180                bitwarden_crypto::HashPurpose::ServerAuthorization,
1181            )
1182            .await
1183            .unwrap();
1184
1185        assert_eq!(
1186            new_hash,
1187            new_kdf_response
1188                .master_password_authentication_data
1189                .master_password_authentication_hash
1190        );
1191
1192        let client_key = {
1193            let key_store = client.internal.get_key_store();
1194            let ctx = key_store.context();
1195            #[allow(deprecated)]
1196            ctx.dangerous_get_symmetric_key(SymmetricKeySlotId::User)
1197                .unwrap()
1198                .to_base64()
1199        };
1200
1201        let client2_key = {
1202            let key_store = client2.internal.get_key_store();
1203            let ctx = key_store.context();
1204            #[allow(deprecated)]
1205            ctx.dangerous_get_symmetric_key(SymmetricKeySlotId::User)
1206                .unwrap()
1207                .to_base64()
1208        };
1209
1210        assert_eq!(client_key, client2_key);
1211    }
1212
1213    #[tokio::test]
1214    async fn test_update_password() {
1215        let client = Client::new_test(None);
1216
1217        let priv_key: EncString = "2.kmLY8NJVuiKBFJtNd/ZFpA==|qOodlRXER+9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z9no/hj6CUh0iyI+SJq4RGI60lKtypMvF6MR3nHLEHOycRUQbZIyTHWl4QQLdHzuwN9lv10ouTEvNr6sFflAX2yb6w3hlCo7oBytH3rJekjb3IIOzBpeTPIejxzVlh0N9OT5MZdh4sNKYHUoWJ8mnfjdM+L4j5Q2Kgk/XiGDgEebkUxiEOQUdVpePF5uSCE+TPav/9FIRGXGiFn6NJMaU7aBsDTFBLloffFLYDpd8/bTwoSvifkj7buwLYM+h/qcnfdy5FWau1cKav+Blq/ZC0qBpo658RTC8ZtseAFDgXoQZuksM10hpP9bzD04Bx30xTGX81QbaSTNwSEEVrOtIhbDrj9OI43KH4O6zLzK+t30QxAv5zjk10RZ4+5SAdYndIlld9Y62opCfPDzRy3ubdve4ZEchpIKWTQvIxq3T5ogOhGaWBVYnkMtM2GVqvWV//46gET5SH/MdcwhACUcZ9kCpMnWH9CyyUwYvTT3UlNyV+DlS27LMPvaw7tx7qa+GfNCoCBd8S4esZpQYK/WReiS8=|pc7qpD42wxyXemdNPuwxbh8iIaryrBPu8f/DGwYdHTw=".parse().unwrap();
1218
1219        let kdf = Kdf::PBKDF2 {
1220            iterations: 100_000.try_into().unwrap(),
1221        };
1222
1223        initialize_user_crypto(
1224            &client,
1225            InitUserCryptoRequest {
1226                user_id: Some(UserId::new_v4()),
1227                kdf_params: kdf.clone(),
1228                email: "[email protected]".into(),
1229                account_cryptographic_state: WrappedAccountCryptographicState::V1 { private_key: priv_key.to_owned() },
1230                method: InitUserCryptoMethod::MasterPasswordUnlock {
1231                    password: "asdfasdfasdf".to_string(),
1232                    master_password_unlock: MasterPasswordUnlockData {
1233                        kdf: kdf.clone(),
1234                        master_key_wrapped_user_key: "2.u2HDQ/nH2J7f5tYHctZx6Q==|NnUKODz8TPycWJA5svexe1wJIz2VexvLbZh2RDfhj5VI3wP8ZkR0Vicvdv7oJRyLI1GyaZDBCf9CTBunRTYUk39DbZl42Rb+Xmzds02EQhc=|rwuo5wgqvTJf3rgwOUfabUyzqhguMYb3sGBjOYqjevc=".parse().unwrap(),
1235                        salt: "[email protected]".to_string(),
1236                        contained_key_id: None,
1237                    },
1238                },
1239                upgrade_token: None,
1240            },
1241        )
1242            .await
1243            .unwrap();
1244
1245        let new_password_response = make_update_password(&client, "123412341234".into())
1246            .await
1247            .unwrap();
1248
1249        let client2 = Client::new_test(None);
1250
1251        initialize_user_crypto(
1252            &client2,
1253            InitUserCryptoRequest {
1254                user_id: Some(UserId::new_v4()),
1255                kdf_params: kdf.clone(),
1256                email: "[email protected]".into(),
1257                account_cryptographic_state: WrappedAccountCryptographicState::V1 {
1258                    private_key: priv_key.to_owned(),
1259                },
1260                method: InitUserCryptoMethod::MasterPasswordUnlock {
1261                    password: "123412341234".into(),
1262                    master_password_unlock: MasterPasswordUnlockData {
1263                        kdf: kdf.clone(),
1264                        master_key_wrapped_user_key: new_password_response.new_key,
1265                        salt: "[email protected]".to_string(),
1266                        contained_key_id: None,
1267                    },
1268                },
1269                upgrade_token: None,
1270            },
1271        )
1272        .await
1273        .unwrap();
1274
1275        let new_hash = client2
1276            .kdf()
1277            .hash_password(
1278                "[email protected]".into(),
1279                "123412341234".into(),
1280                kdf.clone(),
1281                bitwarden_crypto::HashPurpose::ServerAuthorization,
1282            )
1283            .await
1284            .unwrap();
1285
1286        assert_eq!(new_hash, new_password_response.password_hash);
1287
1288        let client_key = {
1289            let key_store = client.internal.get_key_store();
1290            let ctx = key_store.context();
1291            #[allow(deprecated)]
1292            ctx.dangerous_get_symmetric_key(SymmetricKeySlotId::User)
1293                .unwrap()
1294                .to_base64()
1295        };
1296
1297        let client2_key = {
1298            let key_store = client2.internal.get_key_store();
1299            let ctx = key_store.context();
1300            #[allow(deprecated)]
1301            ctx.dangerous_get_symmetric_key(SymmetricKeySlotId::User)
1302                .unwrap()
1303                .to_base64()
1304        };
1305
1306        assert_eq!(client_key, client2_key);
1307    }
1308
1309    #[tokio::test]
1310    async fn test_initialize_user_crypto_pin() {
1311        let client = Client::new_test(None);
1312
1313        let pri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QxYIlbThAO6eima6Zu5XHfqGPMNWv0bLf5+vAjIa5np5DJrSwz9no/hj6CUh0iyI+SJq4RGI60lKtypMvF6MR3nHLEHOycRUQbZIyTHWl4QQLdHzuwN9lv10ouTEvNr6sFflAX2yb6w3hlCo7oBytH3rJekjb3IIOzBpeTPIejxzVlh0N9OT5MZdh4sNKYHUoWJ8mnfjdM+L4j5Q2Kgk/XiGDgEebkUxiEOQUdVpePF5uSCE+TPav/9FIRGXGiFn6NJMaU7aBsDTFBLloffFLYDpd8/bTwoSvifkj7buwLYM+h/qcnfdy5FWau1cKav+Blq/ZC0qBpo658RTC8ZtseAFDgXoQZuksM10hpP9bzD04Bx30xTGX81QbaSTNwSEEVrOtIhbDrj9OI43KH4O6zLzK+t30QxAv5zjk10RZ4+5SAdYndIlld9Y62opCfPDzRy3ubdve4ZEchpIKWTQvIxq3T5ogOhGaWBVYnkMtM2GVqvWV//46gET5SH/MdcwhACUcZ9kCpMnWH9CyyUwYvTT3UlNyV+DlS27LMPvaw7tx7qa+GfNCoCBd8S4esZpQYK/WReiS8=|pc7qpD42wxyXemdNPuwxbh8iIaryrBPu8f/DGwYdHTw=".parse().unwrap();
1314
1315        initialize_user_crypto(
1316            &client,
1317            InitUserCryptoRequest {
1318                user_id: Some(UserId::new_v4()),
1319                kdf_params: Kdf::PBKDF2 {
1320                    iterations: 100_000.try_into().unwrap(),
1321                },
1322                email: "[email protected]".into(),
1323                account_cryptographic_state: WrappedAccountCryptographicState::V1 { private_key: priv_key.to_owned() },
1324                method: InitUserCryptoMethod::MasterPasswordUnlock {
1325                    password: "asdfasdfasdf".into(),
1326                    master_password_unlock: MasterPasswordUnlockData {
1327                        kdf: Kdf::PBKDF2 {
1328                            iterations: 100_000.try_into().unwrap(),
1329                        },
1330                        master_key_wrapped_user_key: "2.u2HDQ/nH2J7f5tYHctZx6Q==|NnUKODz8TPycWJA5svexe1wJIz2VexvLbZh2RDfhj5VI3wP8ZkR0Vicvdv7oJRyLI1GyaZDBCf9CTBunRTYUk39DbZl42Rb+Xmzds02EQhc=|rwuo5wgqvTJf3rgwOUfabUyzqhguMYb3sGBjOYqjevc=".parse().unwrap(),
1331                        salt: "[email protected]".to_string(),
1332                        contained_key_id: None,
1333                    },
1334                },
1335                upgrade_token: None,
1336            },
1337        )
1338            .await
1339            .unwrap();
1340
1341        let pin_key = derive_pin_key(&client, "1234".into()).await.unwrap();
1342
1343        // Verify we can unlock with the pin
1344        let client2 = Client::new_test(None);
1345        initialize_user_crypto(
1346            &client2,
1347            InitUserCryptoRequest {
1348                user_id: Some(UserId::new_v4()),
1349                kdf_params: Kdf::PBKDF2 {
1350                    iterations: 100_000.try_into().unwrap(),
1351                },
1352                email: "[email protected]".into(),
1353                account_cryptographic_state: WrappedAccountCryptographicState::V1 {
1354                    private_key: priv_key.to_owned(),
1355                },
1356                method: InitUserCryptoMethod::Pin {
1357                    pin: "1234".into(),
1358                    pin_protected_user_key: pin_key.pin_protected_user_key,
1359                },
1360                upgrade_token: None,
1361            },
1362        )
1363        .await
1364        .unwrap();
1365
1366        let client_key = {
1367            let key_store = client.internal.get_key_store();
1368            let ctx = key_store.context();
1369            #[allow(deprecated)]
1370            ctx.dangerous_get_symmetric_key(SymmetricKeySlotId::User)
1371                .unwrap()
1372                .to_base64()
1373        };
1374
1375        let client2_key = {
1376            let key_store = client2.internal.get_key_store();
1377            let ctx = key_store.context();
1378            #[allow(deprecated)]
1379            ctx.dangerous_get_symmetric_key(SymmetricKeySlotId::User)
1380                .unwrap()
1381                .to_base64()
1382        };
1383
1384        assert_eq!(client_key, client2_key);
1385
1386        // Verify we can derive the pin protected user key from the encrypted pin
1387        let pin_protected_user_key = derive_pin_user_key(&client, pin_key.encrypted_pin)
1388            .await
1389            .unwrap();
1390
1391        let client3 = Client::new_test(None);
1392
1393        initialize_user_crypto(
1394            &client3,
1395            InitUserCryptoRequest {
1396                user_id: Some(UserId::new_v4()),
1397                kdf_params: Kdf::PBKDF2 {
1398                    iterations: 100_000.try_into().unwrap(),
1399                },
1400                email: "[email protected]".into(),
1401                account_cryptographic_state: WrappedAccountCryptographicState::V1 {
1402                    private_key: priv_key.to_owned(),
1403                },
1404                method: InitUserCryptoMethod::Pin {
1405                    pin: "1234".into(),
1406                    pin_protected_user_key,
1407                },
1408                upgrade_token: None,
1409            },
1410        )
1411        .await
1412        .unwrap();
1413
1414        let client_key = {
1415            let key_store = client.internal.get_key_store();
1416            let ctx = key_store.context();
1417            #[allow(deprecated)]
1418            ctx.dangerous_get_symmetric_key(SymmetricKeySlotId::User)
1419                .unwrap()
1420                .to_base64()
1421        };
1422
1423        let client3_key = {
1424            let key_store = client3.internal.get_key_store();
1425            let ctx = key_store.context();
1426            #[allow(deprecated)]
1427            ctx.dangerous_get_symmetric_key(SymmetricKeySlotId::User)
1428                .unwrap()
1429                .to_base64()
1430        };
1431
1432        assert_eq!(client_key, client3_key);
1433    }
1434
1435    #[tokio::test]
1436    async fn test_initialize_user_crypto_pin_envelope() {
1437        let user_key = "5yKAZ4TSSEGje54MV5lc5ty6crkqUz4xvl+8Dm/piNLKf6OgRi2H0uzttNTXl9z6ILhkmuIXzGpAVc2YdorHgQ==";
1438        let test_pin = "1234";
1439
1440        let client1 = Client::new_test(None);
1441        initialize_user_crypto(
1442            &client1,
1443            InitUserCryptoRequest {
1444                user_id: Some(UserId::new_v4()),
1445                kdf_params: Kdf::PBKDF2 {
1446                    iterations: 100_000.try_into().unwrap(),
1447                },
1448                email: "[email protected]".into(),
1449                account_cryptographic_state: {
1450                    let store: KeyStore<KeySlotIds> = KeyStore::default();
1451                    let mut ctx = store.context_mut();
1452                    WrappedAccountCryptographicState::make_v1(&mut ctx)
1453                        .unwrap()
1454                        .1
1455                },
1456                method: InitUserCryptoMethod::DecryptedKey {
1457                    decrypted_user_key: user_key.to_string(),
1458                },
1459                upgrade_token: None,
1460            },
1461        )
1462        .await
1463        .unwrap();
1464
1465        let enroll_response = client1.crypto().enroll_pin(test_pin.to_string()).unwrap();
1466
1467        let client2 = Client::new_test(None);
1468        initialize_user_crypto(
1469            &client2,
1470            InitUserCryptoRequest {
1471                user_id: Some(UserId::new_v4()),
1472                // NOTE: THIS CHANGES KDF SETTINGS. We ensure in this test that even with different
1473                // KDF settings the pin can unlock the user key.
1474                kdf_params: Kdf::PBKDF2 {
1475                    iterations: 600_000.try_into().unwrap(),
1476                },
1477                email: "[email protected]".into(),
1478                account_cryptographic_state: {
1479                    let store: KeyStore<KeySlotIds> = KeyStore::default();
1480                    let mut ctx = store.context_mut();
1481                    WrappedAccountCryptographicState::make_v1(&mut ctx)
1482                        .unwrap()
1483                        .1
1484                },
1485                method: InitUserCryptoMethod::PinEnvelope {
1486                    pin: test_pin.to_string(),
1487                    pin_protected_user_key_envelope: enroll_response
1488                        .pin_protected_user_key_envelope,
1489                },
1490                upgrade_token: None,
1491            },
1492        )
1493        .await
1494        .unwrap();
1495    }
1496
1497    #[tokio::test]
1498    async fn test_initialize_user_crypto_pin_state() {
1499        use crate::key_management::pin_lock_system::PinLockType;
1500
1501        let client1 = Client::init_test_account(test_bitwarden_com_account()).await;
1502        client1
1503            .km_state_bridge()
1504            .register_bridge(Box::new(InMemoryStateBridge::default()));
1505
1506        PinLockSystem::with_client(&client1)
1507            .set_pin("1234".into(), PinLockType::BeforeFirstUnlock)
1508            .await
1509            .expect("set_pin succeeds");
1510
1511        let persistent_envelope = client1
1512            .km_state_bridge()
1513            .get_persistent_pin_envelope()
1514            .await
1515            .expect("persistent pin envelope present after BFU set_pin");
1516        let encrypted_pin = client1
1517            .km_state_bridge()
1518            .get_encrypted_pin()
1519            .await
1520            .expect("encrypted pin present after set_pin");
1521
1522        // Fresh client simulating an app restart with the same persisted PIN state.
1523        let client2 = Client::init_test_account(test_bitwarden_com_account()).await;
1524        client2
1525            .km_state_bridge()
1526            .register_bridge(Box::new(InMemoryStateBridge::default()));
1527        client2
1528            .km_state_bridge()
1529            .set_persistent_pin_envelope(&persistent_envelope)
1530            .await;
1531        client2
1532            .km_state_bridge()
1533            .set_encrypted_pin(&encrypted_pin)
1534            .await;
1535
1536        let client1_key = {
1537            let key_store = client1.internal.get_key_store();
1538            let ctx = key_store.context();
1539            #[allow(deprecated)]
1540            ctx.dangerous_get_symmetric_key(SymmetricKeySlotId::User)
1541                .unwrap()
1542                .to_owned()
1543        };
1544
1545        let client2_key = {
1546            let key_store = client2.internal.get_key_store();
1547            let ctx = key_store.context();
1548            #[allow(deprecated)]
1549            ctx.dangerous_get_symmetric_key(SymmetricKeySlotId::User)
1550                .unwrap()
1551                .to_owned()
1552        };
1553
1554        assert_eq!(client1_key, client2_key);
1555    }
1556
1557    /// A client with an AfterFirstUnlock PIN whose ephemeral envelope was dropped, as reopening
1558    /// the app does.
1559    async fn client_with_dropped_pin_envelope() -> Client {
1560        use crate::key_management::pin_lock_system::PinLockType;
1561
1562        let client = Client::init_test_account(test_bitwarden_com_account()).await;
1563        client
1564            .km_state_bridge()
1565            .register_bridge(Box::new(InMemoryStateBridge::default()));
1566        PinLockSystem::with_client(&client)
1567            .set_pin("1234".into(), PinLockType::AfterFirstUnlock)
1568            .await
1569            .expect("set_pin succeeds");
1570        client
1571            .km_state_bridge()
1572            .clear_ephemeral_pin_envelope()
1573            .await;
1574        client
1575    }
1576
1577    #[tokio::test]
1578    async fn test_on_unlock_handler_reseals_pin_envelope() {
1579        let client = client_with_dropped_pin_envelope().await;
1580
1581        on_unlock_handler(&client).await.unwrap();
1582
1583        assert!(
1584            client
1585                .km_state_bridge()
1586                .get_ephemeral_pin_envelope()
1587                .await
1588                .is_some()
1589        );
1590    }
1591
1592    #[tokio::test]
1593    async fn test_on_unlock_handler_without_migrations_leaves_pin_envelope() {
1594        let client = client_with_dropped_pin_envelope().await;
1595        client.crypto().disable_local_unlock_migrations();
1596
1597        on_unlock_handler(&client).await.unwrap();
1598
1599        assert!(
1600            client
1601                .km_state_bridge()
1602                .get_ephemeral_pin_envelope()
1603                .await
1604                .is_none()
1605        );
1606    }
1607
1608    #[tokio::test]
1609    async fn test_initialize_user_crypto_pin_state_without_envelope() {
1610        // No PIN envelope in state, as after an app restart with an AfterFirstUnlock PIN
1611        let client = Client::new_test(None);
1612        client
1613            .km_state_bridge()
1614            .register_bridge(Box::new(InMemoryStateBridge::default()));
1615
1616        let result = initialize_user_crypto(
1617            &client,
1618            InitUserCryptoRequest {
1619                user_id: Some(UserId::new_v4()),
1620                kdf_params: Kdf::default_pbkdf2(),
1621                email: "[email protected]".into(),
1622                account_cryptographic_state: {
1623                    let store: KeyStore<KeySlotIds> = KeyStore::default();
1624                    let mut ctx = store.context_mut();
1625                    WrappedAccountCryptographicState::make_v1(&mut ctx)
1626                        .unwrap()
1627                        .1
1628                },
1629                method: InitUserCryptoMethod::PinState {
1630                    pin: "1234".to_string(),
1631                },
1632                upgrade_token: None,
1633            },
1634        )
1635        .await;
1636
1637        assert!(matches!(
1638            result,
1639            Err(EncryptionSettingsError::PinUnlockNotAvailable)
1640        ));
1641    }
1642
1643    #[test]
1644    fn test_enroll_admin_password_reset() {
1645        let client = Client::new(None);
1646
1647        let user_key = "2.Q/2PhzcC7GdeiMHhWguYAQ==|GpqzVdr0go0ug5cZh1n+uixeBC3oC90CIe0hd/HWA/pTRDZ8ane4fmsEIcuc8eMKUt55Y2q/fbNzsYu41YTZzzsJUSeqVjT8/iTQtgnNdpo=|dwI+uyvZ1h/iZ03VQ+/wrGEFYVewBUUl/syYgjsNMbE=".parse().unwrap();
1648        let private_key = "2.yN7l00BOlUE0Sb0M//Q53w==|EwKG/BduQRQ33Izqc/ogoBROIoI5dmgrxSo82sgzgAMIBt3A2FZ9vPRMY+GWT85JiqytDitGR3TqwnFUBhKUpRRAq4x7rA6A1arHrFp5Tp1p21O3SfjtvB3quiOKbqWk6ZaU1Np9HwqwAecddFcB0YyBEiRX3VwF2pgpAdiPbSMuvo2qIgyob0CUoC/h4Bz1be7Qa7B0Xw9/fMKkB1LpOm925lzqosyMQM62YpMGkjMsbZz0uPopu32fxzDWSPr+kekNNyLt9InGhTpxLmq1go/pXR2uw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3qeWRrF8ftrI6xQnFjHBGWD/JWSvd6YMcQED0aVuQkuNW9ST/DzQThPzRfPUoiL10yAmV7Ytu4fR3x2sF0Yfi87YhHFuCMpV/DsqxmUizyiJuD938eRcH8hzR/VO53Qo3UIsqOLcyXtTv6THjSlTopQ+JOLOnHm1w8dzYbLN44OG44rRsbihMUQp+wUZ6bsI8rrOnm9WErzkbQFbrfAINdoCiNa6cimYIjvvnMTaFWNymqY1vZxGztQiMiHiHYwTfwHTXrb9j0uPM=|09J28iXv9oWzYtzK2LBT6Yht4IT4MijEkk0fwFdrVQ4=".parse().unwrap();
1649        client
1650            .internal
1651            .initialize_user_crypto_master_password_unlock(
1652                "asdfasdfasdf".to_string(),
1653                MasterPasswordUnlockData {
1654                    kdf: Kdf::PBKDF2 {
1655                        iterations: NonZeroU32::new(600_000).unwrap(),
1656                    },
1657                    master_key_wrapped_user_key: user_key,
1658                    salt: "[email protected]".to_string(),
1659                    contained_key_id: None,
1660                },
1661                WrappedAccountCryptographicState::V1 { private_key },
1662                &None,
1663            )
1664            .unwrap();
1665
1666        let public_key: B64 = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsy7RFHcX3C8Q4/OMmhhbFReYWfB45W9PDTEA8tUZwZmtOiN2RErIS2M1c+K/4HoDJ/TjpbX1f2MZcr4nWvKFuqnZXyewFc+jmvKVewYi+NAu2++vqKq2kKcmMNhwoQDQdQIVy/Uqlp4Cpi2cIwO6ogq5nHNJGR3jm+CpyrafYlbz1bPvL3hbyoGDuG2tgADhyhXUdFuef2oF3wMvn1lAJAvJnPYpMiXUFmj1ejmbwtlxZDrHgUJvUcp7nYdwUKaFoi+sOttHn3u7eZPtNvxMjhSS/X/1xBIzP/mKNLdywH5LoRxniokUk+fV3PYUxJsiU3lV0Trc/tH46jqd8ZGjmwIDAQAB".parse().unwrap();
1667
1668        let encrypted = enroll_admin_password_reset(&client, public_key).unwrap();
1669
1670        let private_key: B64 = "MIIEvQIBADANBgkq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LqPq8fKAp3XfhHLfUjREDVoiLyQa/YI9U42IOz9LdxKNLo6p8rgVthpvmnRDGnpUuS+KOWjhdqDVANjF6G3t3DG7WNl8Rh5Gk2H4NhFswfSkgQrjebFLlBy9gjQVCWXt8KSmjvPbiY6q52Aaa8IUjA0YJAregvXxfopxO+/7BAoGARicvEtDp7WWnSc1OPoj6N14VIxgYcI7SyrzE0d/1x3ffKzB5e7qomNpxKzvqrVP8DzG7ydh8jaKPmv1MfF8tpYRy3AhmN3/GYwCnPqT75YYrhcrWcVdax5gmQVqHkFtIQkRSCIftzPLlpMGKha/YBV8c1fvC4LD0NPh/Ynv0gtECgYEAyOZg95/kte0jpgUEgwuMrzkhY/AaUJULFuR5MkyvReEbtSBQwV5tx60+T95PHNiFooWWVXiLMsAgyI2IbkxVR1Pzdri3gWK5CTfqb7kLuaj/B7SGvBa2Sxo478KS5K8tBBBWkITqo+wLC0mn3uZi1dyMWO1zopTA+KtEGF2dtGQ=".parse().unwrap();
1671
1672        let private_key = Pkcs8PrivateKeyBytes::from(private_key.as_bytes());
1673        let private_key = PrivateKey::from_der(&private_key).unwrap();
1674        #[expect(deprecated)]
1675        let decrypted: SymmetricCryptoKey =
1676            encrypted.decapsulate_key_unsigned(&private_key).unwrap();
1677
1678        let key_store = client.internal.get_key_store();
1679        let ctx = key_store.context();
1680        #[allow(deprecated)]
1681        let expected = ctx
1682            .dangerous_get_symmetric_key(SymmetricKeySlotId::User)
1683            .unwrap();
1684
1685        assert_eq!(decrypted, *expected);
1686    }
1687
1688    #[test]
1689    fn test_derive_key_connector() {
1690        let request = DeriveKeyConnectorRequest {
1691            password: "asdfasdfasdf".to_string(),
1692            email: "[email protected]".to_string(),
1693            kdf: Kdf::PBKDF2 {
1694                iterations: NonZeroU32::new(600_000).unwrap(),
1695            },
1696            user_key_encrypted: "2.Q/2PhzcC7GdeiMHhWguYAQ==|GpqzVdr0go0ug5cZh1n+uixeBC3oC90CIe0hd/HWA/pTRDZ8ane4fmsEIcuc8eMKUt55Y2q/fbNzsYu41YTZzzsJUSeqVjT8/iTQtgnNdpo=|dwI+uyvZ1h/iZ03VQ+/wrGEFYVewBUUl/syYgjsNMbE=".parse().unwrap(),
1697        };
1698
1699        let result = derive_key_connector(request).unwrap();
1700
1701        assert_eq!(
1702            result.to_string(),
1703            "ySXq1RVLKEaV1eoQE/ui9aFKIvXTl9PAXwp1MljfF50="
1704        );
1705    }
1706
1707    #[tokio::test]
1708    async fn test_initialize_user_crypto_master_password_unlock() {
1709        let client = Client::new_test(None);
1710
1711        initialize_user_crypto(
1712            &client,
1713            InitUserCryptoRequest {
1714                user_id: Some(UserId::new_v4()),
1715                kdf_params: Kdf::PBKDF2 {
1716                    iterations: 600_000.try_into().unwrap(),
1717                },
1718                email: TEST_USER_EMAIL.to_string(),
1719                account_cryptographic_state: WrappedAccountCryptographicState::V1 {
1720                    private_key: TEST_ACCOUNT_PRIVATE_KEY.parse().unwrap(),
1721                },
1722                method: InitUserCryptoMethod::MasterPasswordUnlock {
1723                    password: TEST_USER_PASSWORD.to_string(),
1724                    master_password_unlock: MasterPasswordUnlockData {
1725                        kdf: Kdf::PBKDF2 {
1726                            iterations: 600_000.try_into().unwrap(),
1727                        },
1728                        master_key_wrapped_user_key: TEST_ACCOUNT_USER_KEY.parse().unwrap(),
1729                        salt: TEST_USER_EMAIL.to_string(),
1730                        contained_key_id: None,
1731                    },
1732                },
1733                upgrade_token: None,
1734            },
1735        )
1736        .await
1737        .unwrap();
1738
1739        let key_store = client.internal.get_key_store();
1740        {
1741            let context = key_store.context();
1742            assert!(context.has_symmetric_key(SymmetricKeySlotId::User));
1743            assert!(context.has_private_key(PrivateKeySlotId::UserPrivateKey));
1744        }
1745        let login_method = client.internal.get_login_method().await.unwrap();
1746        if let UserLoginMethod::Username {
1747            email,
1748            kdf,
1749            client_id,
1750            ..
1751        } = login_method
1752        {
1753            assert_eq!(&email, TEST_USER_EMAIL);
1754            assert_eq!(
1755                kdf,
1756                Kdf::PBKDF2 {
1757                    iterations: 600_000.try_into().unwrap(),
1758                }
1759            );
1760            assert_eq!(&client_id, "");
1761        } else {
1762            panic!("Expected username login method");
1763        }
1764    }
1765
1766    #[tokio::test]
1767    async fn test_make_user_tde_registration() {
1768        let user_id = UserId::new_v4();
1769        let email = "[email protected]";
1770        let kdf = Kdf::PBKDF2 {
1771            iterations: NonZeroU32::new(600_000).expect("valid iteration count"),
1772        };
1773
1774        // Generate a mock organization public key for TDE enrollment
1775        let org_key = PrivateKey::make(PublicKeyEncryptionAlgorithm::RsaOaepSha1);
1776        let org_public_key_der = org_key
1777            .to_public_key()
1778            .to_der()
1779            .expect("valid public key DER");
1780        let org_public_key = B64::from(org_public_key_der.as_ref().to_vec());
1781
1782        // Create a client and generate TDE registration keys
1783        let registration_client = Client::new_test(None);
1784        let make_keys_response = registration_client
1785            .crypto()
1786            .make_user_tde_registration(org_public_key)
1787            .expect("TDE registration should succeed");
1788
1789        // Initialize a new client using the TDE device key
1790        let unlock_client = Client::new_test(None);
1791        unlock_client
1792            .crypto()
1793            .initialize_user_crypto(InitUserCryptoRequest {
1794                user_id: Some(user_id),
1795                kdf_params: kdf,
1796                email: email.to_owned(),
1797                account_cryptographic_state: make_keys_response.account_cryptographic_state,
1798                method: InitUserCryptoMethod::DeviceKey {
1799                    device_key: make_keys_response
1800                        .trusted_device_keys
1801                        .device_key
1802                        .to_string(),
1803                    protected_device_private_key: make_keys_response
1804                        .trusted_device_keys
1805                        .protected_device_private_key,
1806                    device_protected_user_key: make_keys_response
1807                        .trusted_device_keys
1808                        .protected_user_key,
1809                },
1810                upgrade_token: None,
1811            })
1812            .await
1813            .expect("initializing user crypto with TDE device key should succeed");
1814
1815        // Verify we can retrieve the user encryption key
1816        let retrieved_key = unlock_client
1817            .crypto()
1818            .get_user_encryption_key()
1819            .await
1820            .expect("should be able to get user encryption key");
1821
1822        // The retrieved key should be a valid symmetric key
1823        let retrieved_symmetric_key = SymmetricCryptoKey::try_from(retrieved_key)
1824            .expect("retrieved key should be valid symmetric key");
1825
1826        // Verify that the org key can decrypt the admin_reset_key UnsignedSharedKey
1827        // and that the decrypted key matches the user's encryption key
1828        #[expect(deprecated)]
1829        let decrypted_user_key = make_keys_response
1830            .reset_password_key
1831            .decapsulate_key_unsigned(&org_key)
1832            .expect("org key should be able to decrypt admin reset key");
1833        assert_eq!(
1834            retrieved_symmetric_key, decrypted_user_key,
1835            "decrypted admin reset key should match the user's encryption key"
1836        );
1837    }
1838
1839    #[tokio::test]
1840    async fn test_make_user_key_connector_registration_success() {
1841        let user_id = UserId::new_v4();
1842        let email = "[email protected]";
1843        let registration_client = Client::new(None);
1844
1845        let make_keys_response = make_user_key_connector_registration(&registration_client);
1846        assert!(make_keys_response.is_ok());
1847        let make_keys_response = make_keys_response.unwrap();
1848
1849        // Initialize a new client using the key connector key
1850        let unlock_client = Client::new_test(None);
1851        unlock_client
1852            .crypto()
1853            .initialize_user_crypto(InitUserCryptoRequest {
1854                user_id: Some(user_id),
1855                kdf_params: Kdf::default_argon2(),
1856                email: email.to_owned(),
1857                account_cryptographic_state: make_keys_response.account_cryptographic_state,
1858                method: InitUserCryptoMethod::KeyConnector {
1859                    user_key: make_keys_response
1860                        .key_connector_key_wrapped_user_key
1861                        .clone(),
1862                    master_key: make_keys_response.key_connector_key.clone().into(),
1863                },
1864                upgrade_token: None,
1865            })
1866            .await
1867            .expect("initializing user crypto with key connector key should succeed");
1868
1869        // Verify we can retrieve the user encryption key
1870        let retrieved_key = unlock_client
1871            .crypto()
1872            .get_user_encryption_key()
1873            .await
1874            .expect("should be able to get user encryption key");
1875
1876        // The retrieved key should be a valid symmetric key
1877        let retrieved_symmetric_key = SymmetricCryptoKey::try_from(retrieved_key)
1878            .expect("retrieved key should be valid symmetric key");
1879
1880        assert_eq!(retrieved_symmetric_key, make_keys_response.user_key);
1881
1882        let decrypted_user_key = make_keys_response
1883            .key_connector_key
1884            .decrypt_user_key(make_keys_response.key_connector_key_wrapped_user_key);
1885        assert_eq!(retrieved_symmetric_key, decrypted_user_key.unwrap());
1886    }
1887
1888    #[tokio::test]
1889    async fn test_initialize_user_crypto_with_upgrade_token_upgrades_v1_to_v2() {
1890        let client1 = Client::init_test_account(test_bitwarden_com_account()).await;
1891
1892        let expected_v2_key =
1893            SymmetricCryptoKey::try_from(TEST_VECTOR_USER_KEY_V2_B64.to_string()).unwrap();
1894        let upgrade_token = {
1895            let mut ctx = client1.internal.get_key_store().context_mut();
1896            let v2_key_id = ctx.add_local_symmetric_key(expected_v2_key.clone());
1897            V2UpgradeToken::create(SymmetricKeySlotId::User, v2_key_id, &ctx).unwrap()
1898        };
1899
1900        let client2 = Client::new_test(None);
1901        init_v2_account_with_master_password_and_upgrade_token(
1902            &client2,
1903            UserId::new_v4(),
1904            upgrade_token,
1905        )
1906        .await;
1907
1908        // The active user key must now be V2 and match the test-vector V2 key.
1909        let result_key =
1910            SymmetricCryptoKey::try_from(get_user_encryption_key(&client2).await.unwrap()).unwrap();
1911        assert!(
1912            matches!(result_key, SymmetricCryptoKey::XAes256GcmKey(_)),
1913            "User key should be upgraded to V2 after initialization with upgrade token"
1914        );
1915        assert_eq!(result_key, expected_v2_key);
1916    }
1917
1918    #[tokio::test]
1919    async fn test_initialize_user_crypto_with_upgrade_token_ignored_for_v2_key() {
1920        let dummy_token = {
1921            let key_store = KeyStore::<KeySlotIds>::default();
1922            let mut ctx = key_store.context_mut();
1923            let v1_id = ctx.make_symmetric_key(SymmetricKeyAlgorithm::Aes256CbcHmac);
1924            let v2_id = ctx.make_symmetric_key(SymmetricKeyAlgorithm::XAes256Gcm);
1925            V2UpgradeToken::create(v1_id, v2_id, &ctx).unwrap()
1926        };
1927
1928        let client = Client::new_test(None);
1929        initialize_user_crypto(
1930            &client,
1931            InitUserCryptoRequest {
1932                user_id: Some(UserId::new_v4()),
1933                kdf_params: Kdf::PBKDF2 {
1934                    iterations: 100_000.try_into().unwrap(),
1935                },
1936                email: "[email protected]".into(),
1937                account_cryptographic_state: WrappedAccountCryptographicState::V2 {
1938                    private_key: TEST_VECTOR_PRIVATE_KEY_V2.parse().unwrap(),
1939                    signing_key: TEST_VECTOR_SIGNING_KEY_V2.parse().unwrap(),
1940                    security_state: TEST_VECTOR_SECURITY_STATE_V2.parse().unwrap(),
1941                    signed_public_key: TEST_VECTOR_SIGNED_PUBLIC_KEY_V2.parse().unwrap(),
1942                },
1943                method: InitUserCryptoMethod::DecryptedKey {
1944                    decrypted_user_key: TEST_VECTOR_USER_KEY_V2_B64.to_string(),
1945                },
1946                upgrade_token: Some(dummy_token),
1947            },
1948        )
1949        .await
1950        .unwrap();
1951
1952        // The upgrade token must have been ignored; the original V2 key must still be active
1953        let result_key =
1954            SymmetricCryptoKey::try_from(get_user_encryption_key(&client).await.unwrap()).unwrap();
1955        assert!(
1956            matches!(result_key, SymmetricCryptoKey::XAes256GcmKey(_)),
1957            "Upgrade token must be ignored for a V2 user key"
1958        );
1959        let expected_key =
1960            SymmetricCryptoKey::try_from(TEST_VECTOR_USER_KEY_V2_B64.to_string()).unwrap();
1961        assert_eq!(result_key, expected_key);
1962    }
1963
1964    #[tokio::test]
1965    async fn test_initialize_user_crypto_with_invalid_upgrade_token_fails() {
1966        // Token built with a different V1 key — decryption with the test account's V1 key fails.
1967        let mismatched_token = {
1968            let key_store = KeyStore::<KeySlotIds>::default();
1969            let mut ctx = key_store.context_mut();
1970            let wrong_v1_id = ctx.generate_symmetric_key();
1971            let v2_id = ctx.make_symmetric_key(SymmetricKeyAlgorithm::XAes256Gcm);
1972            V2UpgradeToken::create(wrong_v1_id, v2_id, &ctx).unwrap()
1973        };
1974
1975        let client = Client::new_test(None);
1976        let result = initialize_user_crypto(
1977            &client,
1978            InitUserCryptoRequest {
1979                user_id: Some(UserId::new_v4()),
1980                kdf_params: Kdf::PBKDF2 {
1981                    iterations: 600_000.try_into().unwrap(),
1982                },
1983                email: "[email protected]".into(),
1984                account_cryptographic_state: WrappedAccountCryptographicState::V1 {
1985                    // The private key is never decrypted because the token fails first.
1986                    private_key: TEST_ACCOUNT_PRIVATE_KEY.parse().unwrap(),
1987                },
1988                method: InitUserCryptoMethod::MasterPasswordUnlock {
1989                    password: "asdfasdfasdf".into(),
1990                    master_password_unlock: MasterPasswordUnlockData {
1991                        kdf: Kdf::PBKDF2 {
1992                            iterations: 600_000.try_into().unwrap(),
1993                        },
1994                        master_key_wrapped_user_key: TEST_ACCOUNT_USER_KEY.parse().unwrap(),
1995                        salt: "[email protected]".to_string(),
1996                        contained_key_id: None,
1997                    },
1998                },
1999                upgrade_token: Some(mismatched_token),
2000            },
2001        )
2002        .await;
2003
2004        assert!(
2005            matches!(result, Err(EncryptionSettingsError::InvalidUpgradeToken)),
2006            "Initialization with a mismatched upgrade token should fail"
2007        );
2008    }
2009
2010    #[tokio::test]
2011    async fn test_initialize_user_local_data_key_sets_local_user_data_key_equal_to_user_key() {
2012        let client = Client::init_test_account(test_bitwarden_com_account_v2()).await;
2013        initialize_user_local_data_key(&client)
2014            .await
2015            .expect("initialize_user_local_data_key should succeed");
2016
2017        // Verify LocalUserData key equals the User key: data encrypted with User
2018        // must be decryptable with LocalUserData.
2019        let key_store = client.internal.get_key_store();
2020        let mut ctx = key_store.context_mut();
2021        let plaintext = "test";
2022        let ciphertext = plaintext
2023            .encrypt(&mut ctx, SymmetricKeySlotId::User)
2024            .expect("encryption with user key should succeed");
2025        let decrypted: String = ciphertext
2026            .decrypt(&mut ctx, SymmetricKeySlotId::LocalUserData)
2027            .expect("decryption with local user data key should succeed");
2028        assert_eq!(decrypted, plaintext);
2029    }
2030
2031    #[tokio::test]
2032    async fn test_initialize_org_crypto_persists_org_keys() {
2033        use crate::{OrganizationId, client::persisted_state::OrganizationSharedKey};
2034
2035        let client = Client::init_test_account(test_bitwarden_com_account()).await;
2036
2037        let org_id: OrganizationId = "1bc9ac1e-f5aa-45f2-94bf-b181009709b8".parse().unwrap();
2038
2039        let repo = client
2040            .internal
2041            .state_registry
2042            .get::<OrganizationSharedKey>()
2043            .expect("OrganizationSharedKey repository should be available");
2044
2045        let persisted = repo
2046            .get(org_id)
2047            .await
2048            .expect("repository get should not fail");
2049
2050        let entry = persisted.expect("org key should be persisted after initialize_org_crypto");
2051        assert_eq!(entry.org_id, org_id);
2052    }
2053
2054    #[tokio::test]
2055    async fn test_initialize_user_crypto_persists_account_crypto_state() {
2056        use crate::client::persisted_state::ACCOUNT_CRYPTO_STATE;
2057
2058        let account_crypto_state = WrappedAccountCryptographicState::V1 {
2059            private_key: TEST_ACCOUNT_PRIVATE_KEY.parse().unwrap(),
2060        };
2061
2062        let client = Client::new_test(None);
2063        initialize_user_crypto(
2064            &client,
2065            InitUserCryptoRequest {
2066                user_id: Some(UserId::new_v4()),
2067                kdf_params: Kdf::PBKDF2 {
2068                    iterations: 600_000.try_into().unwrap(),
2069                },
2070                email: TEST_USER_EMAIL.into(),
2071                account_cryptographic_state: account_crypto_state.clone(),
2072                method: InitUserCryptoMethod::MasterPasswordUnlock {
2073                    password: TEST_USER_PASSWORD.into(),
2074                    master_password_unlock: MasterPasswordUnlockData {
2075                        kdf: Kdf::PBKDF2 {
2076                            iterations: 600_000.try_into().unwrap(),
2077                        },
2078                        master_key_wrapped_user_key: TEST_ACCOUNT_USER_KEY.parse().unwrap(),
2079                        salt: TEST_USER_EMAIL.to_string(),
2080                        contained_key_id: None,
2081                    },
2082                },
2083                upgrade_token: None,
2084            },
2085        )
2086        .await
2087        .unwrap();
2088
2089        let persisted = client
2090            .internal
2091            .state_registry
2092            .value::<ACCOUNT_CRYPTO_STATE>()
2093            .get()
2094            .await
2095            .expect("account crypto state should be persisted");
2096
2097        assert_eq!(persisted, account_crypto_state);
2098    }
2099
2100    #[tokio::test]
2101    async fn test_initialize_user_local_data_key_idempotent() {
2102        let client = Client::init_test_account(test_bitwarden_com_account_v2()).await;
2103        initialize_user_local_data_key(&client)
2104            .await
2105            .expect("first initialization should succeed");
2106
2107        // Encrypt something with the key established on the first call.
2108        let ciphertext = {
2109            let key_store = client.internal.get_key_store();
2110            let mut ctx = key_store.context_mut();
2111            "test"
2112                .encrypt(&mut ctx, SymmetricKeySlotId::LocalUserData)
2113                .expect("encryption should succeed")
2114        };
2115
2116        initialize_user_local_data_key(&client)
2117            .await
2118            .expect("second initialization should succeed");
2119
2120        // The key must not have changed: data encrypted before the second call
2121        // must still be decryptable.
2122        let key_store = client.internal.get_key_store();
2123        let mut ctx = key_store.context_mut();
2124        let decrypted: String = ciphertext
2125            .decrypt(&mut ctx, SymmetricKeySlotId::LocalUserData)
2126            .expect("decryption after second initialization should succeed");
2127        assert_eq!(decrypted, "test");
2128    }
2129
2130    #[tokio::test]
2131    async fn test_initialize_user_crypto_rewraps_local_user_data_key_on_v1_to_v2_upgrade() {
2132        use crate::key_management::LocalUserDataKeyState;
2133
2134        // Bootstrap a V1 client to materialize a V1-wrapped LocalUserDataKey state.
2135        let client_v1 = Client::init_test_account(test_bitwarden_com_account()).await;
2136        let user_id = UserId::new(uuid::uuid!("060000fb-0922-4dd3-b170-6e15cb5df8c8"));
2137
2138        let v1_user_data_key = client_v1
2139            .platform()
2140            .state()
2141            .get::<LocalUserDataKeyState>()
2142            .unwrap()
2143            .get(user_id)
2144            .await
2145            .unwrap()
2146            .expect("V1 init should plant a LocalUserDataKey state");
2147        assert!(
2148            matches!(
2149                v1_user_data_key.wrapped_key,
2150                EncString::Aes256Cbc_HmacSha256_B64 { .. }
2151            ),
2152            "Initial local user data key should use be wrapped with a V1 user key"
2153        );
2154
2155        // Encrypt a payload with the V1-derived LocalUserData key.
2156        let ciphertext = {
2157            let mut ctx = client_v1.internal.get_key_store().context_mut();
2158            "preserved data"
2159                .encrypt(&mut ctx, SymmetricKeySlotId::LocalUserData)
2160                .unwrap()
2161        };
2162
2163        // Build an upgrade token from the V1 user key to a fresh V2 key.
2164        let v2_key = SymmetricCryptoKey::try_from(TEST_VECTOR_USER_KEY_V2_B64.to_string()).unwrap();
2165        let upgrade_token = {
2166            let mut ctx = client_v1.internal.get_key_store().context_mut();
2167            let v2_key_id = ctx.add_local_symmetric_key(v2_key.clone());
2168            V2UpgradeToken::create(SymmetricKeySlotId::User, v2_key_id, &ctx).unwrap()
2169        };
2170
2171        // Plant the V1-wrapped state into a fresh client and run init with the upgrade token.
2172        let client_v2 = Client::new_test(None);
2173        let repo = client_v2
2174            .platform()
2175            .state()
2176            .get::<LocalUserDataKeyState>()
2177            .unwrap();
2178        repo.set(user_id, v1_user_data_key.clone()).await.unwrap();
2179        client_v2
2180            .km_state_bridge()
2181            .register_bridge(Box::new(InMemoryStateBridge::default()));
2182        client_v2
2183            .km_state_bridge()
2184            .set_v2_upgrade_token(&upgrade_token.clone())
2185            .await;
2186
2187        init_v2_account_with_master_password_and_upgrade_token(&client_v2, user_id, upgrade_token)
2188            .await;
2189
2190        // The persisted wrapped key must be sealed with the V2 user key.
2191        let rewrapped_state = repo
2192            .get(user_id)
2193            .await
2194            .unwrap()
2195            .expect("LocalUserDataKey state must remain present");
2196        assert!(
2197            matches!(
2198                rewrapped_state.wrapped_key,
2199                EncString::Cose_Encrypt0_B64 { .. }
2200            ),
2201            "Rewrapped key should be sealed with the V2 user key"
2202        );
2203        assert_ne!(rewrapped_state.wrapped_key, v1_user_data_key.wrapped_key);
2204
2205        // Data encrypted before the upgrade must remain decryptable.
2206        let mut ctx = client_v2.internal.get_key_store().context_mut();
2207        let decrypted: String = ciphertext
2208            .decrypt(&mut ctx, SymmetricKeySlotId::LocalUserData)
2209            .expect("data encrypted before the upgrade should decrypt after rewrap");
2210        assert_eq!(decrypted, "preserved data");
2211    }
2212
2213    #[tokio::test]
2214    async fn test_initialize_user_crypto_creates_new_local_user_data_key_with_upgrade_token_and_no_existing_state()
2215     {
2216        use crate::key_management::LocalUserDataKeyState;
2217
2218        // Build an upgrade token from a separate V1 client (no state will be planted from it).
2219        let helper = Client::init_test_account(test_bitwarden_com_account()).await;
2220        let v2_key = SymmetricCryptoKey::try_from(TEST_VECTOR_USER_KEY_V2_B64.to_string()).unwrap();
2221        let upgrade_token = {
2222            let mut ctx = helper.internal.get_key_store().context_mut();
2223            let v2_key_id = ctx.add_local_symmetric_key(v2_key.clone());
2224            V2UpgradeToken::create(SymmetricKeySlotId::User, v2_key_id, &ctx).unwrap()
2225        };
2226
2227        // Fresh client with no planted LocalUserDataKey state.
2228        let user_id = UserId::new_v4();
2229        let client = Client::new_test(None);
2230        client
2231            .km_state_bridge()
2232            .register_bridge(Box::new(InMemoryStateBridge::default()));
2233        client
2234            .km_state_bridge()
2235            .set_v2_upgrade_token(&upgrade_token.clone())
2236            .await;
2237
2238        init_v2_account_with_master_password_and_upgrade_token(&client, user_id, upgrade_token)
2239            .await;
2240
2241        // No existing state → standard fresh-init path: a new wrapped key sealed with V2.
2242        let new_state = client
2243            .platform()
2244            .state()
2245            .get::<LocalUserDataKeyState>()
2246            .unwrap()
2247            .get(user_id)
2248            .await
2249            .unwrap()
2250            .expect("LocalUserDataKey should be created on init");
2251        assert!(matches!(
2252            new_state.wrapped_key,
2253            EncString::Cose_Encrypt0_B64 { .. }
2254        ));
2255    }
2256
2257    #[tokio::test]
2258    async fn test_initialize_user_crypto_leaves_local_user_data_key_unchanged_without_upgrade_token()
2259     {
2260        use crate::key_management::LocalUserDataKeyState;
2261
2262        // First V1 init plants a V1-wrapped state.
2263        let client = Client::init_test_account(test_bitwarden_com_account()).await;
2264        let user_id = UserId::new(uuid::uuid!("060000fb-0922-4dd3-b170-6e15cb5df8c8"));
2265        client
2266            .km_state_bridge()
2267            .register_bridge(Box::new(InMemoryStateBridge::default()));
2268
2269        let repo = client
2270            .platform()
2271            .state()
2272            .get::<LocalUserDataKeyState>()
2273            .unwrap();
2274        let before = repo.get(user_id).await.unwrap().unwrap();
2275
2276        // Re-run initialize_local_user_data_key_into_state; must skip idempotently.
2277        initialize_local_user_data_key_into_state(&client, user_id)
2278            .await
2279            .map_err(|_| "should succeed")
2280            .unwrap();
2281
2282        let after = repo.get(user_id).await.unwrap().unwrap();
2283        assert_eq!(
2284            after.wrapped_key, before.wrapped_key,
2285            "without an upgrade token the wrapped key must not change"
2286        );
2287    }
2288
2289    #[tokio::test]
2290    async fn test_initialize_user_crypto_does_not_rewrap_when_already_v2() {
2291        use crate::key_management::LocalUserDataKeyState;
2292
2293        // V2 init plants a V2-wrapped state.
2294        let client = Client::init_test_account(test_bitwarden_com_account_v2()).await;
2295        let user_id = UserId::new(uuid::uuid!("060000fb-0922-4dd3-b170-6e15cb5df8c8"));
2296        client
2297            .km_state_bridge()
2298            .register_bridge(Box::new(InMemoryStateBridge::default()));
2299
2300        let repo = client
2301            .platform()
2302            .state()
2303            .get::<LocalUserDataKeyState>()
2304            .unwrap();
2305        let before = repo.get(user_id).await.unwrap().unwrap();
2306        assert!(matches!(
2307            before.wrapped_key,
2308            EncString::Cose_Encrypt0_B64 { .. }
2309        ));
2310
2311        migrate_local_user_data_key_for_user_key_upgrade(&client, user_id)
2312            .await
2313            .map_err(|_| "should succeed")
2314            .unwrap();
2315
2316        let after = repo.get(user_id).await.unwrap().unwrap();
2317        assert_eq!(
2318            after.wrapped_key, before.wrapped_key,
2319            "an already-V2-wrapped key must not be rewrapped"
2320        );
2321    }
2322
2323    #[tokio::test]
2324    async fn test_make_user_password_registration() {
2325        let user_id = UserId::new_v4();
2326        let registration_client = Client::new(None);
2327
2328        let make_keys_response = registration_client
2329            .crypto()
2330            .make_user_password_registration(
2331                TEST_USER_PASSWORD.to_string(),
2332                TEST_USER_EMAIL.to_string(),
2333            )
2334            .expect("user password registration should succeed");
2335
2336        let unlock_client = Client::new_test(None);
2337        unlock_client
2338            .crypto()
2339            .initialize_user_crypto(InitUserCryptoRequest {
2340                user_id: Some(user_id),
2341                kdf_params: Kdf::default_argon2(),
2342                email: TEST_USER_EMAIL.to_string(),
2343                account_cryptographic_state: make_keys_response.account_cryptographic_state,
2344                method: InitUserCryptoMethod::MasterPasswordUnlock {
2345                    password: TEST_USER_PASSWORD.to_string(),
2346                    master_password_unlock: make_keys_response.master_password_unlock_data.clone(),
2347                },
2348                upgrade_token: None,
2349            })
2350            .await
2351            .expect("initializing user crypto with master password should succeed");
2352
2353        let retrieved_key = unlock_client
2354            .crypto()
2355            .get_user_encryption_key()
2356            .await
2357            .expect("should be able to get user encryption key");
2358
2359        let retrieved_symmetric_key = SymmetricCryptoKey::try_from(retrieved_key)
2360            .expect("retrieved key should be valid symmetric key");
2361
2362        let master_key = MasterKey::derive(
2363            TEST_USER_PASSWORD,
2364            TEST_USER_EMAIL,
2365            &make_keys_response.master_password_unlock_data.kdf,
2366        )
2367        .expect("master key should derive");
2368
2369        let decrypted_user_key = master_key
2370            .decrypt_user_key(
2371                make_keys_response
2372                    .master_password_unlock_data
2373                    .master_key_wrapped_user_key
2374                    .clone(),
2375            )
2376            .expect("should decrypt user key");
2377
2378        assert_eq!(retrieved_symmetric_key, decrypted_user_key);
2379    }
2380}