bitwarden-core 3.0.0

Internal crate for the bitwarden crate. Do not use.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
#[cfg(any(feature = "wasm", test))]
use bitwarden_crypto::safe::{PasswordProtectedKeyEnvelope, PasswordProtectedKeyEnvelopeNamespace};
use bitwarden_crypto::{
    BitwardenLegacyKeyBytes, CryptoError, Decryptable, Kdf, PrimitiveEncryptable, RotateableKeySet,
    SymmetricCryptoKey, SymmetricKeyAlgorithm,
};
#[cfg(feature = "internal")]
use bitwarden_crypto::{EncString, UnsignedSharedKey};
use bitwarden_encoding::B64;
#[cfg(feature = "wasm")]
use wasm_bindgen::prelude::*;

use super::crypto::{
    DeriveKeyConnectorError, DeriveKeyConnectorRequest, EnrollAdminPasswordResetError,
    MakeJitMasterPasswordRegistrationResponse, MakeKeyConnectorRegistrationResponse,
    MakeKeyPairResponse, MakeUserMasterPasswordRegistrationResponse, VerifyAsymmetricKeysRequest,
    VerifyAsymmetricKeysResponse, derive_key_connector, make_key_pair,
    make_user_jit_master_password_registration, make_user_key_connector_registration,
    make_user_password_registration, verify_asymmetric_keys,
};
use crate::key_management::V2UpgradeToken;
#[cfg(feature = "internal")]
use crate::key_management::{
    SymmetricKeySlotId,
    crypto::{
        DerivePinKeyResponse, InitOrgCryptoRequest, InitUserCryptoRequest, UpdatePasswordResponse,
        derive_pin_key, derive_pin_user_key, enroll_admin_password_reset, get_user_encryption_key,
        initialize_org_crypto, initialize_user_crypto, make_prf_user_key_set,
    },
};
#[expect(deprecated)]
use crate::{
    Client,
    client::encryption_settings::EncryptionSettingsError,
    error::{NotAuthenticatedError, StatefulCryptoError},
    key_management::crypto::{
        CryptoClientError, EnrollPinResponse, MakeKeysError, MakeTdeRegistrationResponse,
        UpdateKdfResponse, UserCryptoV2KeysResponse, enroll_pin, get_v2_rotated_account_keys,
        make_update_kdf, make_update_password, make_user_tde_registration,
        make_v2_keys_for_v1_user,
    },
};

/// A client for the crypto operations.
#[cfg_attr(feature = "wasm", wasm_bindgen)]
pub struct CryptoClient {
    pub(crate) client: crate::Client,
}

#[cfg_attr(feature = "wasm", wasm_bindgen)]
impl CryptoClient {
    /// Initialization method for the user crypto. Needs to be called before any other crypto
    /// operations.
    pub async fn initialize_user_crypto(
        &self,
        req: InitUserCryptoRequest,
    ) -> Result<(), EncryptionSettingsError> {
        initialize_user_crypto(&self.client, req).await
    }

    /// Initialization method for the organization crypto. Needs to be called after
    /// `initialize_user_crypto` but before any other crypto operations.
    pub async fn initialize_org_crypto(
        &self,
        req: InitOrgCryptoRequest,
    ) -> Result<(), EncryptionSettingsError> {
        initialize_org_crypto(&self.client, req).await
    }

    /// Generates a new key pair and encrypts the private key with the provided user key.
    /// Crypto initialization not required.
    pub fn make_key_pair(&self, user_key: B64) -> Result<MakeKeyPairResponse, CryptoError> {
        make_key_pair(user_key)
    }

    /// Verifies a user's asymmetric keys by decrypting the private key with the provided user
    /// key. Returns if the private key is decryptable and if it is a valid matching key.
    /// Crypto initialization not required.
    pub fn verify_asymmetric_keys(
        &self,
        request: VerifyAsymmetricKeysRequest,
    ) -> Result<VerifyAsymmetricKeysResponse, CryptoError> {
        verify_asymmetric_keys(request)
    }

    /// Makes a new signing key pair and signs the public key for the user
    pub fn make_keys_for_user_crypto_v2(
        &self,
    ) -> Result<UserCryptoV2KeysResponse, StatefulCryptoError> {
        #[expect(deprecated)]
        make_v2_keys_for_v1_user(&self.client)
    }

    /// Creates a rotated set of account keys for the current state
    pub fn get_v2_rotated_account_keys(
        &self,
    ) -> Result<UserCryptoV2KeysResponse, StatefulCryptoError> {
        #[expect(deprecated)]
        get_v2_rotated_account_keys(&self.client)
    }

    /// Create the data necessary to update the user's kdf settings. The user's encryption key is
    /// re-encrypted for the password under the new kdf settings. This returns the re-encrypted
    /// user key and the new password hash but does not update sdk state.
    pub async fn make_update_kdf(
        &self,
        password: String,
        kdf: Kdf,
    ) -> Result<UpdateKdfResponse, CryptoClientError> {
        make_update_kdf(&self.client, &password, &kdf).await
    }

    /// Protects the current user key with the provided PIN. The result can be stored and later
    /// used to initialize another client instance by using the PIN and the PIN key with
    /// `initialize_user_crypto`.
    pub fn enroll_pin(&self, pin: String) -> Result<EnrollPinResponse, CryptoClientError> {
        enroll_pin(&self.client, pin)
    }

    /// Protects the current user key with the provided PIN. The result can be stored and later
    /// used to initialize another client instance by using the PIN and the PIN key with
    /// `initialize_user_crypto`. The provided pin is encrypted with the user key.
    pub fn enroll_pin_with_encrypted_pin(
        &self,
        // Note: This will be replaced by `EncString` with https://bitwarden.atlassian.net/browse/PM-24775
        encrypted_pin: String,
    ) -> Result<EnrollPinResponse, CryptoClientError> {
        let encrypted_pin: EncString = encrypted_pin.parse()?;
        let pin = encrypted_pin.decrypt(
            &mut self.client.internal.get_key_store().context_mut(),
            SymmetricKeySlotId::User,
        )?;
        enroll_pin(&self.client, pin)
    }

    /// Decrypts a `PasswordProtectedKeyEnvelope`, returning the user key, if successful.
    /// This is a stop-gap solution, until initialization of the SDK is used.
    #[cfg(any(feature = "wasm", test))]
    pub fn unseal_password_protected_key_envelope(
        &self,
        pin: String,
        envelope: PasswordProtectedKeyEnvelope,
    ) -> Result<Vec<u8>, CryptoClientError> {
        let mut ctx = self.client.internal.get_key_store().context_mut();
        let key_slot = envelope.unseal(
            pin.as_str(),
            PasswordProtectedKeyEnvelopeNamespace::PinUnlock,
            &mut ctx,
        )?;
        #[allow(deprecated)]
        let key = ctx.dangerous_get_symmetric_key(key_slot)?;
        Ok(key.to_encoded().to_vec())
    }

    /// A stop gap-solution for encrypting with the local user data key, until the WASM client's
    /// password generator history encryption and email forwarders encryption is fully migrated to
    /// SDK.
    pub fn encrypt_with_local_user_data_key(
        &self,
        plaintext: String,
    ) -> Result<String, CryptoClientError> {
        let mut ctx = self.client.internal.get_key_store().context_mut();
        plaintext
            .encrypt(&mut ctx, SymmetricKeySlotId::LocalUserData)
            .map_err(CryptoClientError::Crypto)
            .map(|enc| enc.to_string())
    }

    /// A stop gap-solution for decrypting with the local user data key, until the WASM client's
    /// password generator history encryption and email forwarders encryption is fully migrated to
    /// SDK.
    pub fn decrypt_with_local_user_data_key(
        &self,
        encrypted_plaintext: String,
    ) -> Result<String, CryptoClientError> {
        let mut ctx = self.client.internal.get_key_store().context_mut();
        let encrypted: EncString = encrypted_plaintext
            .parse()
            .map_err(CryptoClientError::Crypto)?;
        encrypted
            .decrypt(&mut ctx, SymmetricKeySlotId::LocalUserData)
            .map_err(CryptoClientError::Crypto)
    }

    /// ⚠️⚠️⚠️ HAZMAT WARNING: DO NOT USE THIS ⚠️⚠️⚠️
    ///
    /// Get the uses's decrypted encryption key. Note: It's very important
    /// to keep this key safe, as it can be used to decrypt all of the user's data. It is
    /// only permitted to use for a transition period where side effects such as biometrics
    /// and never-lock are set from within the client code.
    pub async fn get_user_encryption_key(&self) -> Result<B64, CryptoClientError> {
        get_user_encryption_key(&self.client).await
    }

    /// Takes a raw key and returns the corresponding key id. This is used for the biometrics
    /// subsystem and should be removed after moving over biometric management to the SDK.
    pub fn get_key_id_for_symmetric_key(
        key: Vec<u8>,
    ) -> Result<Option<Vec<u8>>, CryptoClientError> {
        let symmetric_key = SymmetricCryptoKey::try_from(&BitwardenLegacyKeyBytes::from(key))?;
        Ok(symmetric_key.key_id().map(|id| id.as_slice().to_vec()))
    }
}

impl CryptoClient {
    /// Create the data necessary to update the user's password. The user's encryption key is
    /// re-encrypted with the new password. This returns the new encrypted user key and the new
    /// password hash but does not update sdk state.
    pub async fn make_update_password(
        &self,
        new_password: String,
    ) -> Result<UpdatePasswordResponse, CryptoClientError> {
        make_update_password(&self.client, new_password).await
    }

    /// Generates a PIN protected user key from the provided PIN. The result can be stored and later
    /// used to initialize another client instance by using the PIN and the PIN key with
    /// `initialize_user_crypto`.
    pub async fn derive_pin_key(
        &self,
        pin: String,
    ) -> Result<DerivePinKeyResponse, CryptoClientError> {
        derive_pin_key(&self.client, pin).await
    }

    /// Derives the pin protected user key from encrypted pin. Used when pin requires master
    /// password on first unlock.
    pub async fn derive_pin_user_key(
        &self,
        encrypted_pin: EncString,
    ) -> Result<EncString, CryptoClientError> {
        derive_pin_user_key(&self.client, encrypted_pin).await
    }

    /// Creates a new rotateable key set for the current user key protected
    /// by a key derived from the given PRF.
    pub fn make_prf_user_key_set(&self, prf: B64) -> Result<RotateableKeySet, CryptoClientError> {
        make_prf_user_key_set(&self.client, prf)
    }

    /// Prepares the account for being enrolled in the admin password reset feature. This encrypts
    /// the users [UserKey][bitwarden_crypto::UserKey] with the organization's public key.
    pub fn enroll_admin_password_reset(
        &self,
        public_key: B64,
    ) -> Result<UnsignedSharedKey, EnrollAdminPasswordResetError> {
        enroll_admin_password_reset(&self.client, public_key)
    }

    /// Derive the master key for migrating to the key connector
    pub fn derive_key_connector(
        &self,
        request: DeriveKeyConnectorRequest,
    ) -> Result<B64, DeriveKeyConnectorError> {
        derive_key_connector(request)
    }

    /// Creates a new V2 account cryptographic state for TDE registration.
    /// This generates fresh cryptographic keys (private key, signing key, signed public key,
    /// and security state) wrapped with a new user key.
    pub fn make_user_tde_registration(
        &self,
        org_public_key: B64,
    ) -> Result<MakeTdeRegistrationResponse, MakeKeysError> {
        make_user_tde_registration(&self.client, org_public_key)
    }

    /// Creates a new V2 account cryptographic state for Key Connector registration.
    /// This generates fresh cryptographic keys (private key, signing key, signed public key,
    /// and security state) wrapped with a new user key.
    pub fn make_user_key_connector_registration(
        &self,
    ) -> Result<MakeKeyConnectorRegistrationResponse, MakeKeysError> {
        make_user_key_connector_registration(&self.client)
    }

    /// Creates a new V2 account cryptographic state for SSO JIT master password registration.
    /// This generates fresh cryptographic keys (private key, signing key, signed public key,
    /// and security state) wrapped with a new user key.
    pub fn make_user_jit_master_password_registration(
        &self,
        master_password: String,
        salt: String,
        org_public_key: B64,
    ) -> Result<MakeJitMasterPasswordRegistrationResponse, MakeKeysError> {
        make_user_jit_master_password_registration(
            &self.client,
            master_password,
            salt,
            org_public_key,
        )
    }

    /// Creates new V2 account cryptographic state for password-based registration
    /// This generates fresh cryptographic keys (private key, signing key, signed public key,
    /// security state) wrapped with a new user key.
    pub fn make_user_password_registration(
        &self,
        master_password: String,
        salt: String,
    ) -> Result<MakeUserMasterPasswordRegistrationResponse, MakeKeysError> {
        make_user_password_registration(&self.client, master_password, salt)
    }

    /// Gets the upgraded V2 user key using an upgrade token.
    /// If the current key is already V2, returns it directly.
    /// If the current key is V1 and a token is provided, extracts the V2 key.
    pub fn get_upgraded_user_key(
        &self,
        upgrade_token: Option<V2UpgradeToken>,
    ) -> Result<B64, CryptoClientError> {
        let mut ctx = self.client.internal.get_key_store().context_mut();

        let algorithm = ctx
            .get_symmetric_key_algorithm(SymmetricKeySlotId::User)
            .map_err(|_| CryptoClientError::NotAuthenticated(NotAuthenticatedError))?;

        match (algorithm, upgrade_token) {
            // Already V2, return current key
            (SymmetricKeyAlgorithm::XChaCha20Poly1305, _) => {
                #[allow(deprecated)]
                let current_key = ctx
                    .dangerous_get_symmetric_key(SymmetricKeySlotId::User)
                    .map_err(|_| CryptoClientError::NotAuthenticated(NotAuthenticatedError))?;
                Ok(current_key.clone().to_base64())
            }
            // V1 with token, extract V2
            (SymmetricKeyAlgorithm::Aes256CbcHmac, Some(token)) => {
                let v2_key_id = token
                    .unwrap_v2(SymmetricKeySlotId::User, &mut ctx)
                    .map_err(|_| CryptoClientError::InvalidUpgradeToken)?;
                #[allow(deprecated)]
                let v2_key = ctx
                    .dangerous_get_symmetric_key(v2_key_id)
                    .map_err(|_| CryptoClientError::InvalidUpgradeToken)?;
                Ok(v2_key.clone().to_base64())
            }
            // V1 without token, error
            (SymmetricKeyAlgorithm::Aes256CbcHmac, None) => {
                Err(CryptoClientError::UpgradeTokenRequired)
            }
        }
    }
}

impl Client {
    /// Access to crypto functionality.
    pub fn crypto(&self) -> CryptoClient {
        CryptoClient {
            client: self.clone(),
        }
    }
}

#[cfg(test)]
mod tests {
    use bitwarden_crypto::{BitwardenLegacyKeyBytes, KeyStore, SymmetricCryptoKey};

    use super::*;
    use crate::{
        client::test_accounts::{test_bitwarden_com_account, test_bitwarden_com_account_v2},
        key_management::{KeySlotIds, V2UpgradeToken},
    };

    #[tokio::test]
    async fn test_enroll_pin_envelope() {
        // Initialize a test client with user crypto
        let client = Client::init_test_account(test_bitwarden_com_account()).await;
        let user_key_initial =
            SymmetricCryptoKey::try_from(client.crypto().get_user_encryption_key().await.unwrap())
                .unwrap();

        // Enroll with a PIN, then re-enroll
        let pin = "1234";
        let enroll_response = client.crypto().enroll_pin(pin.to_string()).unwrap();
        let re_enroll_response = client
            .crypto()
            .enroll_pin_with_encrypted_pin(enroll_response.user_key_encrypted_pin.to_string())
            .unwrap();

        let secret = BitwardenLegacyKeyBytes::from(
            client
                .crypto()
                .unseal_password_protected_key_envelope(
                    pin.to_string(),
                    re_enroll_response.pin_protected_user_key_envelope,
                )
                .unwrap(),
        );
        let user_key_final = SymmetricCryptoKey::try_from(&secret).expect("valid user key");
        assert_eq!(user_key_initial, user_key_final);
    }

    #[test]
    fn test_get_upgraded_user_key_not_authenticated() {
        let client = Client::new(None);
        let result = client.crypto().get_upgraded_user_key(None);
        assert!(matches!(
            result,
            Err(CryptoClientError::NotAuthenticated(_))
        ));
    }

    #[tokio::test]
    async fn test_get_upgraded_user_key_v1_no_token_returns_error() {
        let client = Client::init_test_account(test_bitwarden_com_account()).await;
        let result = client.crypto().get_upgraded_user_key(None);
        assert!(matches!(
            result,
            Err(CryptoClientError::UpgradeTokenRequired)
        ));
    }

    #[tokio::test]
    async fn test_get_upgraded_user_key_v1_with_token_returns_v2_key() {
        let client = Client::init_test_account(test_bitwarden_com_account()).await;

        // Add a fresh V2 key to the client's keystore and build a token linking it to the V1 key
        let (token, expected_v2_b64) = {
            let mut ctx = client.internal.get_key_store().context_mut();
            let v2_key_id = ctx.make_symmetric_key(SymmetricKeyAlgorithm::XChaCha20Poly1305);
            #[allow(deprecated)]
            let v2_key = ctx.dangerous_get_symmetric_key(v2_key_id).unwrap().clone();
            let token = V2UpgradeToken::create(SymmetricKeySlotId::User, v2_key_id, &ctx).unwrap();
            (token, v2_key.to_base64())
        };

        let result = client.crypto().get_upgraded_user_key(Some(token)).unwrap();
        assert_eq!(result, expected_v2_b64);
    }

    #[tokio::test]
    async fn test_get_upgraded_user_key_v1_invalid_token_returns_error() {
        let client = Client::init_test_account(test_bitwarden_com_account()).await;

        // Token built with a different V1 key — unwrapping with the client's V1 key will fail
        let mismatched_token = {
            let key_store = KeyStore::<KeySlotIds>::default();
            let mut ctx = key_store.context_mut();
            let wrong_v1_id = ctx.make_symmetric_key(SymmetricKeyAlgorithm::Aes256CbcHmac);
            let v2_id = ctx.make_symmetric_key(SymmetricKeyAlgorithm::XChaCha20Poly1305);
            V2UpgradeToken::create(wrong_v1_id, v2_id, &ctx).unwrap()
        };

        let result = client
            .crypto()
            .get_upgraded_user_key(Some(mismatched_token));
        assert!(matches!(
            result,
            Err(CryptoClientError::InvalidUpgradeToken)
        ));
    }

    #[tokio::test]
    async fn test_get_upgraded_user_key_already_v2_no_token_returns_v2_key() {
        let client = Client::init_test_account(test_bitwarden_com_account_v2()).await;

        let result = client.crypto().get_upgraded_user_key(None).unwrap();
        let result_key = SymmetricCryptoKey::try_from(result).unwrap();
        assert!(
            matches!(result_key, SymmetricCryptoKey::XChaCha20Poly1305Key(_)),
            "V2 user should receive a V2 key"
        );
    }

    #[tokio::test]
    async fn test_get_upgraded_user_key_already_v2_with_token_ignored() {
        let client = Client::init_test_account(test_bitwarden_com_account_v2()).await;

        // Build a structurally valid token with unrelated keys; it must be ignored for V2 users.
        let dummy_token = {
            let key_store = KeyStore::<KeySlotIds>::default();
            let mut ctx = key_store.context_mut();
            let v1_id = ctx.make_symmetric_key(SymmetricKeyAlgorithm::Aes256CbcHmac);
            let v2_id = ctx.make_symmetric_key(SymmetricKeyAlgorithm::XChaCha20Poly1305);
            V2UpgradeToken::create(v1_id, v2_id, &ctx).unwrap()
        };

        let result_with_token = client
            .crypto()
            .get_upgraded_user_key(Some(dummy_token))
            .unwrap();
        let result_no_token = client.crypto().get_upgraded_user_key(None).unwrap();
        assert_eq!(
            result_with_token, result_no_token,
            "Token must be ignored for a V2 user"
        );
    }
}