Skip to main content

bitwarden_vault/cipher/cipher_client/
mod.rs

1use std::sync::Arc;
2
3use bitwarden_core::{
4    Client, FromClient, OrganizationId,
5    client::{ApiConfigurations, FromClientPart},
6    key_management::{BLOB_SECURITY_VERSION, KeySlotIds, SymmetricKeySlotId},
7};
8#[cfg(feature = "wasm")]
9use bitwarden_crypto::{CompositeEncryptable, SymmetricCryptoKey};
10use bitwarden_crypto::{Decryptable, IdentifyKey, KeyStore, KeyStoreContext};
11#[cfg(feature = "wasm")]
12use bitwarden_encoding::B64;
13use bitwarden_ffi::LargeVec;
14use bitwarden_state::repository::{Repository, RepositoryError};
15
16use super::EncryptionContext;
17#[cfg(feature = "wasm")]
18use crate::Fido2CredentialFullView;
19use crate::{
20    Cipher, CipherError, CipherListView, CipherView, DecryptError, DecryptListError, EncryptError,
21    cipher::cipher::{DecryptCipherListResult, DecryptCipherResult, EncryptMode, StrictDecrypt},
22    cipher_client::admin::CipherAdminClient,
23};
24
25mod admin;
26mod bulk_update_collections;
27
28pub use admin::{GetAssignedOrgCiphersAdminError, GetOrganizationCiphersAdminError};
29pub use bulk_update_collections::BulkUpdateCollectionsCipherError;
30mod create;
31pub use create::{CipherCreateRequest, CreateCipherError};
32mod delete;
33pub use delete::DeleteCipherError;
34mod edit;
35pub use edit::{CipherEditRequest, CipherPartialEditRequest, EditCipherError};
36mod get;
37pub use get::GetCipherError;
38mod move_many;
39pub use move_many::MoveCipherError;
40mod restore;
41pub use restore::RestoreCipherError;
42mod share_cipher;
43
44/// Returns `true` when cipher data for the given scope should be written in the blob-encrypted
45/// format, based on the current security state version. Individual-vault ciphers qualify once the
46/// security state has reached [`BLOB_SECURITY_VERSION`]. Organization-vault support is tracked in
47/// PM-32430.
48pub fn should_use_blob_encryption(
49    ctx: &KeyStoreContext<KeySlotIds>,
50    organization_id: Option<OrganizationId>,
51) -> bool {
52    organization_id.is_none() && ctx.get_security_state_version() >= BLOB_SECURITY_VERSION
53}
54
55#[allow(missing_docs)]
56#[bitwarden_ffi::wasm_object]
57pub struct CiphersClient {
58    #[allow(dead_code)]
59    pub(crate) key_store: KeyStore<KeySlotIds>,
60    pub(crate) api_configurations: Arc<ApiConfigurations>,
61    pub(crate) repository: Option<Arc<dyn Repository<Cipher>>>,
62    #[deprecated(
63        note = "Use the component fields (key_store, api_configurations, repository) for new operations"
64    )]
65    pub(crate) client: Client,
66}
67
68impl FromClient for CiphersClient {
69    fn from_client(client: &Client) -> Self {
70        #[allow(deprecated)]
71        Self {
72            key_store: client.get_part(),
73            api_configurations: client.get_part(),
74            repository: client.get_part(),
75            client: client.clone(),
76        }
77    }
78}
79
80#[allow(deprecated)]
81#[bitwarden_ffi::wasm_export]
82impl CiphersClient {
83    pub(crate) fn should_use_blob_encryption(
84        &self,
85        organization_id: Option<OrganizationId>,
86    ) -> bool {
87        let key_store = self.client.internal.get_key_store();
88        should_use_blob_encryption(&key_store.context(), organization_id)
89    }
90
91    #[allow(missing_docs)]
92    // The signature is part of the UniFFI and wasm public surface; keep it `async`.
93    #[allow(clippy::unused_async)]
94    pub async fn encrypt(
95        &self,
96        cipher_view: CipherView,
97    ) -> Result<EncryptionContext, EncryptError> {
98        let user_id = self
99            .client
100            .internal
101            .get_user_id()
102            .ok_or(EncryptError::MissingUserId)?;
103        let key_store = self.client.internal.get_key_store();
104
105        let encrypted_by_key_id = key_store
106            .context()
107            .get_symmetric_key_id(cipher_view.key_identifier())
108            .map(|id| id.to_string());
109
110        let mode = if self.should_use_blob_encryption(cipher_view.organization_id) {
111            EncryptMode::Blob(cipher_view)
112        } else {
113            EncryptMode::Legacy(cipher_view)
114        };
115        let cipher = key_store.encrypt(mode)?;
116        Ok(EncryptionContext {
117            cipher,
118            encrypted_for: user_id,
119            encrypted_by_key_id,
120        })
121    }
122
123    /// Encrypt a cipher with the provided key. This should only be used when rotating encryption
124    /// keys in the Web client.
125    ///
126    /// Until key rotation is fully implemented in the SDK, this method must be provided the new
127    /// symmetric key in base64 format. See PM-23084
128    ///
129    /// The cipher key is wrapped with the new key. A cipher key is generated if the cipher
130    /// does not already have one.
131    ///
132    /// Returns [`CipherError::AttachmentsWithoutKeys`] if any attachment lacks its own key.
133    #[cfg(feature = "wasm")]
134    // The signature is part of the wasm public surface; keep it `async`.
135    #[allow(clippy::unused_async)]
136    pub async fn encrypt_cipher_for_rotation(
137        &self,
138        mut cipher_view: CipherView,
139        new_key: B64,
140    ) -> Result<EncryptionContext, CipherError> {
141        let new_key = SymmetricCryptoKey::try_from(new_key)?;
142
143        let user_id = self
144            .client
145            .internal
146            .get_user_id()
147            .ok_or(EncryptError::MissingUserId)?;
148
149        let key_store = self.client.internal.get_key_store();
150        let mut ctx = key_store.context();
151
152        // Set the new key in the key store context
153        let new_key_id = ctx.add_local_symmetric_key(new_key);
154
155        cipher_view.validate_attachment_keys()?;
156
157        // Rotation installs the new key under a `Local` slot id (`new_key_id`), not the view's
158        // natural `User`/`Organization` slot — so pass it explicitly to `encrypt_composite` rather
159        // than going through `key_store.encrypt`, which uses the view's natural key identifier.
160        let mode = if self.should_use_blob_encryption(cipher_view.organization_id) {
161            EncryptMode::Blob(cipher_view)
162        } else {
163            EncryptMode::Legacy(cipher_view)
164        };
165        let cipher = mode.encrypt_composite(&mut ctx, new_key_id)?;
166
167        // Rotation encrypts under the new key, so that - not the view's natural slot - is what the
168        // server needs to validate this write against.
169        let encrypted_by_key_id = ctx
170            .get_symmetric_key_id(new_key_id)
171            .map(|id| id.to_string());
172
173        Ok(EncryptionContext {
174            cipher,
175            encrypted_for: user_id,
176            encrypted_by_key_id,
177        })
178    }
179
180    /// Encrypt a list of cipher views.
181    ///
182    /// This method attempts to encrypt all ciphers in the list. If any cipher
183    /// fails to encrypt, the entire operation fails and an error is returned.
184    // The signature is part of the UniFFI and wasm public surface; keep it `async`.
185    #[allow(clippy::unused_async)]
186    pub async fn encrypt_list(
187        &self,
188        cipher_views: Vec<CipherView>,
189    ) -> Result<Vec<EncryptionContext>, EncryptError> {
190        let user_id = self
191            .client
192            .internal
193            .get_user_id()
194            .ok_or(EncryptError::MissingUserId)?;
195        let key_store = self.client.internal.get_key_store();
196        let ctx = key_store.context();
197
198        // Each cipher may be wrapped under a different key (organization vs. user), so the key id
199        // is captured per cipher and zipped back up after the batch encrypt.
200        let prepared: Vec<(EncryptMode<CipherView>, Option<String>)> = cipher_views
201            .into_iter()
202            .map(|cv| {
203                let encrypted_by_key_id = ctx
204                    .get_symmetric_key_id(cv.key_identifier())
205                    .map(|id| id.to_string());
206                let mode = if self.should_use_blob_encryption(cv.organization_id) {
207                    EncryptMode::Blob(cv)
208                } else {
209                    EncryptMode::Legacy(cv)
210                };
211                (mode, encrypted_by_key_id)
212            })
213            .collect();
214
215        let (prepared_modes, key_ids): (Vec<_>, Vec<_>) = prepared.into_iter().unzip();
216
217        let ciphers: Vec<Cipher> = key_store.encrypt_list(&prepared_modes)?;
218
219        Ok(ciphers
220            .into_iter()
221            .zip(key_ids)
222            .map(|(cipher, encrypted_by_key_id)| EncryptionContext {
223                cipher,
224                encrypted_for: user_id,
225                encrypted_by_key_id,
226            })
227            .collect())
228    }
229
230    #[allow(missing_docs)]
231    pub async fn decrypt(&self, cipher: Cipher) -> Result<CipherView, DecryptError> {
232        let key_store = self.client.internal.get_key_store();
233        Ok(if self.is_strict_decrypt().await {
234            key_store.decrypt(&StrictDecrypt(cipher))?
235        } else {
236            key_store.decrypt(&cipher)?
237        })
238    }
239
240    /// Decrypt cipher list. Fails if any cipher fails to decrypt.
241    pub async fn decrypt_list(
242        &self,
243        ciphers: LargeVec<Cipher>,
244    ) -> Result<Vec<CipherListView>, DecryptListError> {
245        let key_store = self.client.internal.get_key_store();
246        let strict = self.is_strict_decrypt().await;
247        // The room for every cipher is reserved up front: growing by doubling holds the old and the
248        // new buffer at once.
249        let mut views = Vec::with_capacity(ciphers.len());
250        for result in decrypt_ciphers(key_store, ciphers, strict) {
251            views.push(result?.map_err(|failure| failure.1)?);
252        }
253        Ok(views)
254    }
255
256    /// Decrypt cipher list with failures
257    /// Returns both successfully decrypted ciphers and any that failed to decrypt
258    pub async fn decrypt_list_with_failures(
259        &self,
260        ciphers: LargeVec<Cipher>,
261    ) -> Result<DecryptCipherListResult, DecryptListError> {
262        let (successes, failures) = self.decrypt_ciphers_with_failures(ciphers).await?;
263        Ok(DecryptCipherListResult {
264            successes,
265            failures,
266        })
267    }
268
269    /// Decrypt full cipher list
270    /// Returns both successfully fully decrypted ciphers and any that failed to decrypt
271    pub async fn decrypt_list_full_with_failures(
272        &self,
273        ciphers: LargeVec<Cipher>,
274    ) -> Result<DecryptCipherResult, DecryptListError> {
275        let (successes, failures) = self.decrypt_ciphers_with_failures(ciphers).await?;
276        Ok(DecryptCipherResult {
277            successes,
278            failures,
279        })
280    }
281
282    /// Temporary method used to re-encrypt FIDO2 credentials for a cipher view.
283    /// Necessary until the TS clients utilize the SDK entirely for FIDO2 credentials management.
284    /// TS clients create decrypted FIDO2 credentials that need to be encrypted manually when
285    /// encrypting the rest of the CipherView.
286    /// TODO: Remove once TS passkey provider implementation uses SDK - PM-8313
287    #[cfg(feature = "wasm")]
288    pub fn set_fido2_credentials(
289        &self,
290        mut cipher_view: CipherView,
291        fido2_credentials: Vec<Fido2CredentialFullView>,
292    ) -> Result<CipherView, CipherError> {
293        cipher_view.set_new_fido2_credentials(fido2_credentials)?;
294
295        Ok(cipher_view)
296    }
297
298    #[allow(missing_docs)]
299    pub fn move_to_organization(
300        &self,
301        mut cipher_view: CipherView,
302        organization_id: OrganizationId,
303    ) -> Result<CipherView, CipherError> {
304        cipher_view.move_to_organization(organization_id)?;
305        Ok(cipher_view)
306    }
307
308    /// Returns a new client for performing admin operations.
309    /// Uses the admin server API endpoints and does not modify local state.
310    pub fn admin(&self) -> CipherAdminClient {
311        CipherAdminClient::from_client(&self.client)
312    }
313}
314
315#[allow(deprecated)]
316impl CiphersClient {
317    fn get_repository(&self) -> Result<Arc<dyn Repository<Cipher>>, RepositoryError> {
318        Ok(self.client.platform().state().get::<Cipher>()?)
319    }
320
321    async fn is_strict_decrypt(&self) -> bool {
322        self.client.flags().get().await.strict_cipher_decryption
323    }
324
325    /// Decrypts `ciphers`, returning the decrypted ciphers and the ciphers that failed, each in
326    /// their original order.
327    async fn decrypt_ciphers_with_failures<Output>(
328        &self,
329        ciphers: LargeVec<Cipher>,
330    ) -> Result<(Vec<Output>, Vec<Cipher>), DecryptListError>
331    where
332        Cipher: Decryptable<KeySlotIds, SymmetricKeySlotId, Output>,
333        StrictDecrypt<Cipher>: Decryptable<KeySlotIds, SymmetricKeySlotId, Output>,
334        Output: Send + Sync,
335    {
336        let key_store = self.client.internal.get_key_store();
337        let strict = self.is_strict_decrypt().await;
338        // The room for every cipher is reserved up front: growing by doubling holds the old and the
339        // new buffer at once.
340        let mut successes = Vec::with_capacity(ciphers.len());
341        let mut failures = Vec::new();
342        for result in decrypt_ciphers(key_store, ciphers, strict) {
343            match result? {
344                Ok(output) => successes.push(output),
345                Err(failure) => failures.push(failure.0),
346            }
347        }
348        Ok((successes, failures))
349    }
350}
351
352/// The result of decrypting one cipher of a list: the decrypted cipher, or the cipher that failed
353/// along with its error, or an input item that is not a cipher.
354type DecryptedCipher<Output> = Result<
355    Result<Output, Box<(Cipher, bitwarden_crypto::CryptoError)>>,
356    bitwarden_ffi::LargeVecError,
357>;
358
359/// Decrypts `ciphers` in order with [`KeyStore::decrypt_large_vec`], with [`StrictDecrypt`] when
360/// `strict` is set. An input item that is not a cipher comes as an `Err`; callers fail the call
361/// there.
362fn decrypt_ciphers<'a, Output>(
363    key_store: &'a KeyStore<KeySlotIds>,
364    ciphers: LargeVec<Cipher>,
365    strict: bool,
366) -> Box<dyn Iterator<Item = DecryptedCipher<Output>> + 'a>
367where
368    Cipher: Decryptable<KeySlotIds, SymmetricKeySlotId, Output>,
369    StrictDecrypt<Cipher>: Decryptable<KeySlotIds, SymmetricKeySlotId, Output>,
370    Output: Send + 'a,
371{
372    if strict {
373        Box::new(
374            key_store
375                .decrypt_large_vec(ciphers.map(StrictDecrypt))
376                .map(|result| Ok(result?.map_err(unwrap_strict_failure))),
377        )
378    } else {
379        Box::new(key_store.decrypt_large_vec(ciphers))
380    }
381}
382
383/// The cipher in a failed strict decrypt, without its [`StrictDecrypt`] wrapper.
384fn unwrap_strict_failure(
385    failure: Box<(StrictDecrypt<Cipher>, bitwarden_crypto::CryptoError)>,
386) -> Box<(Cipher, bitwarden_crypto::CryptoError)> {
387    let (StrictDecrypt(cipher), error) = *failure;
388    Box::new((cipher, error))
389}
390
391#[cfg(test)]
392mod tests {
393
394    use bitwarden_core::{
395        client::test_accounts::{test_bitwarden_com_account, test_bitwarden_com_account_v2},
396        key_management::SymmetricKeySlotId,
397    };
398    #[cfg(feature = "wasm")]
399    use bitwarden_crypto::{CryptoError, SymmetricKeyAlgorithm};
400
401    use super::*;
402    #[cfg(feature = "wasm")]
403    use crate::AttachmentView;
404    use crate::{
405        Attachment, CipherRepromptType, CipherType, Login, VaultClientExt,
406        cipher::blob::try_parse_blob,
407    };
408
409    fn test_cipher() -> Cipher {
410        Cipher {
411            partial_data: None,
412            id: Some("358f2b2b-9326-4e5e-94a8-b18100bb0908".parse().unwrap()),
413            organization_id: None,
414            folder_id: None,
415            collection_ids: vec![],
416            key: None,
417            name: Some("2.+oPT8B4xJhyhQRe1VkIx0A==|PBtC/bZkggXR+fSnL/pG7g==|UkjRD0VpnUYkjRC/05ZLdEBAmRbr3qWRyJey2bUvR9w=".parse().unwrap()),
418            notes: None,
419            r#type: CipherType::Login,
420            login: Some(Login{
421                username: None,
422                password: None,
423                password_revision_date: None,
424                uris:None,
425                totp: None,
426                autofill_on_page_load: None,
427                http_authentication_enabled: None,
428                fido2_credentials: None,
429            }),
430            identity: None,
431            card: None,
432            secure_note: None,
433            ssh_key: None,
434            bank_account: None,
435            drivers_license: None,
436            passport: None,
437            favorite: false,
438            reprompt: CipherRepromptType::None,
439            organization_use_totp: true,
440            edit: true,
441            permissions: None,
442            view_password: true,
443            local_data: None,
444            attachments: None,
445            fields:  None,
446            password_history: None,
447            creation_date: "2024-05-31T11:20:58.4566667Z".parse().unwrap(),
448            deleted_date: None,
449            revision_date: "2024-05-31T11:20:58.4566667Z".parse().unwrap(),
450            archived_date: None,
451            data: None,
452        }
453    }
454
455    fn test_cipher_view() -> CipherView {
456        let test_id = "fd411a1a-fec8-4070-985d-0e6560860e69".parse().unwrap();
457        CipherView {
458            partial: false,
459            r#type: CipherType::Login,
460            login: Some(crate::LoginView {
461                username: Some("test_username".to_string()),
462                password: Some("test_password".to_string()),
463                password_revision_date: None,
464                uris: None,
465                totp: None,
466                autofill_on_page_load: None,
467                http_authentication_enabled: None,
468                fido2_credentials: None,
469            }),
470            id: Some(test_id),
471            organization_id: None,
472            folder_id: None,
473            collection_ids: vec![],
474            key: None,
475            name: "My test login".to_string(),
476            notes: None,
477            identity: None,
478            card: None,
479            secure_note: None,
480            ssh_key: None,
481            bank_account: None,
482            drivers_license: None,
483            passport: None,
484            favorite: false,
485            reprompt: CipherRepromptType::None,
486            organization_use_totp: true,
487            edit: true,
488            permissions: None,
489            view_password: true,
490            local_data: None,
491            attachments: None,
492            attachment_decryption_failures: None,
493            fields: None,
494            password_history: None,
495            creation_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
496            deleted_date: None,
497            revision_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
498            archived_date: None,
499        }
500    }
501
502    fn test_attachment_legacy() -> Attachment {
503        Attachment {
504            id: Some("uf7bkexzag04d3cw04jsbqqkbpbwhxs0".to_string()),
505            url: Some("http://localhost:4000/attachments//358f2b2b-9326-4e5e-94a8-b18100bb0908/uf7bkexzag04d3cw04jsbqqkbpbwhxs0".to_string()),
506            file_name: Some("2.mV50WiLq6duhwGbhM1TO0A==|dTufWNH8YTPP0EMlNLIpFA==|QHp+7OM8xHtEmCfc9QPXJ0Ro2BeakzvLgxJZ7NdLuDc=".parse().unwrap()),
507            key: None,
508            size: Some("65".to_string()),
509            size_name: Some("65 Bytes".to_string()),
510        }
511    }
512
513    fn test_attachment_v2() -> Attachment {
514        Attachment {
515            id: Some("a77m56oerrz5b92jm05lq5qoyj1xh2t9".to_string()),
516            url: Some("http://localhost:4000/attachments//358f2b2b-9326-4e5e-94a8-b18100bb0908/uf7bkexzag04d3cw04jsbqqkbpbwhxs0".to_string()),
517            file_name: Some("2.GhazFdCYQcM5v+AtVwceQA==|98bMUToqC61VdVsSuXWRwA==|bsLByMht9Hy5QO9pPMRz0K4d0aqBiYnnROGM5YGbNu4=".parse().unwrap()),
518            key: Some("2.6TPEiYULFg/4+3CpDRwCqw==|6swweBHCJcd5CHdwBBWuRN33XRV22VoroDFDUmiM4OzjPEAhgZK57IZS1KkBlCcFvT+t+YbsmDcdv+Lqr+iJ3MmzfJ40MCB5TfYy+22HVRA=|rkgFDh2IWTfPC1Y66h68Diiab/deyi1p/X0Fwkva0NQ=".parse().unwrap()),
519            size: Some("65".to_string()),
520            size_name: Some("65 Bytes".to_string()),
521        }
522    }
523
524    #[tokio::test]
525    async fn test_decrypt_list() {
526        let client = Client::init_test_account(test_bitwarden_com_account()).await;
527
528        let dec = client
529            .vault()
530            .ciphers()
531            .decrypt_list(vec![Cipher {
532                partial_data: None,
533                id: Some("a1569f46-0797-4d3f-b859-b181009e2e49".parse().unwrap()),
534                organization_id: Some("1bc9ac1e-f5aa-45f2-94bf-b181009709b8".parse().unwrap()),
535                folder_id: None,
536                collection_ids: vec!["66c5ca57-0868-4c7e-902f-b181009709c0".parse().unwrap()],
537                key: None,
538                name: Some("2.RTdUGVWYl/OZHUMoy68CMg==|sCaT5qHx8i0rIvzVrtJKww==|jB8DsRws6bXBtXNfNXUmFJ0JLDlB6GON6Y87q0jgJ+0=".parse().unwrap()),
539                notes: None,
540                r#type: CipherType::Login,
541                login: Some(Login{
542                    username: Some("2.ouEYEk+SViUtqncesfe9Ag==|iXzEJq1zBeNdDbumFO1dUA==|RqMoo9soSwz/yB99g6YPqk8+ASWRcSdXsKjbwWzyy9U=".parse().unwrap()),
543                    password: Some("2.6yXnOz31o20Z2kiYDnXueA==|rBxTb6NK9lkbfdhrArmacw==|ogZir8Z8nLgiqlaLjHH+8qweAtItS4P2iPv1TELo5a0=".parse().unwrap()),
544                    password_revision_date: None, uris:None, totp: None, autofill_on_page_load: None, http_authentication_enabled: None, fido2_credentials: None }),
545                identity: None,
546                card: None,
547                secure_note: None,
548                ssh_key: None,
549                bank_account: None,
550                drivers_license: None,
551                passport: None,
552                favorite: false,
553                reprompt: CipherRepromptType::None,
554                organization_use_totp: true,
555                edit: true,
556                permissions: None,
557                view_password: true,
558                local_data: None,
559                attachments: None,
560                fields:  None,
561                password_history: None,
562                creation_date: "2024-05-31T09:35:55.12Z".parse().unwrap(),
563                deleted_date: None,
564                revision_date: "2024-05-31T09:35:55.12Z".parse().unwrap(),
565                archived_date: None,
566                data: None,
567            }].into())
568            .await
569            .unwrap();
570
571        assert_eq!(dec[0].name, "Test item");
572    }
573
574    #[tokio::test]
575    async fn test_decrypt_list_with_failures_all_success() {
576        let client = Client::init_test_account(test_bitwarden_com_account()).await;
577
578        let valid_cipher = test_cipher();
579
580        let result = client
581            .vault()
582            .ciphers()
583            .decrypt_list_with_failures(vec![valid_cipher].into())
584            .await
585            .unwrap();
586
587        assert_eq!(result.successes.len(), 1);
588        assert!(result.failures.is_empty());
589        assert_eq!(result.successes[0].name, "234234");
590    }
591
592    #[tokio::test]
593    async fn test_decrypt_list_with_failures_mixed_results() {
594        let client = Client::init_test_account(test_bitwarden_com_account()).await;
595        let valid_cipher = test_cipher();
596        let mut invalid_cipher = test_cipher();
597        // Set an invalid encryptedkey to cause decryption failure
598        invalid_cipher.key = Some("2.Gg8yCM4IIgykCZyq0O4+cA==|GJLBtfvSJTDJh/F7X4cJPkzI6ccnzJm5DYl3yxOW2iUn7DgkkmzoOe61sUhC5dgVdV0kFqsZPcQ0yehlN1DDsFIFtrb4x7LwzJNIkMgxNyg=|1rGkGJ8zcM5o5D0aIIwAyLsjMLrPsP3EWm3CctBO3Fw=".parse().unwrap());
599
600        let ciphers = vec![valid_cipher, invalid_cipher.clone()];
601
602        let result = client
603            .vault()
604            .ciphers()
605            .decrypt_list_with_failures(ciphers.into())
606            .await
607            .unwrap();
608
609        assert_eq!(result.successes.len(), 1);
610        assert_eq!(result.failures.len(), 1);
611
612        assert_eq!(result.successes[0].name, "234234");
613    }
614
615    #[tokio::test]
616    async fn test_move_user_cipher_with_attachment_without_key_to_org_fails() {
617        let client = Client::init_test_account(test_bitwarden_com_account()).await;
618
619        let mut cipher = test_cipher();
620        cipher.attachments = Some(vec![test_attachment_legacy()]);
621
622        let view = client
623            .vault()
624            .ciphers()
625            .decrypt(cipher.clone())
626            .await
627            .unwrap();
628
629        //  Move cipher to organization
630        let res = client.vault().ciphers().move_to_organization(
631            view,
632            "1bc9ac1e-f5aa-45f2-94bf-b181009709b8".parse().unwrap(),
633        );
634
635        assert!(res.is_err());
636    }
637
638    /// End-to-end check that `encrypt` captures the wrapping key's id into the returned context.
639    /// The V2 test account holds an XAES-256-GCM user key, which carries a key id.
640    #[tokio::test]
641    async fn test_encrypt_captures_encrypted_by_key_id() {
642        let client = Client::init_test_account(test_bitwarden_com_account_v2()).await;
643
644        let expected = client
645            .internal
646            .get_key_store()
647            .context()
648            .get_symmetric_key_id(SymmetricKeySlotId::User)
649            .expect("the V2 account's user key has a key id")
650            .to_string();
651
652        let encrypted = client
653            .vault()
654            .ciphers()
655            .encrypt(test_cipher_view())
656            .await
657            .unwrap();
658
659        assert_eq!(
660            encrypted.encrypted_by_key_id.as_deref(),
661            Some(expected.as_str())
662        );
663    }
664
665    /// The V1 test account's AES-CBC-HMAC user key has no stored key id, but derives one from its
666    /// key material, so the field is populated with that derived id.
667    #[tokio::test]
668    async fn test_encrypt_captures_derived_encrypted_by_key_id_on_v1_account() {
669        let client = Client::init_test_account(test_bitwarden_com_account()).await;
670
671        let expected = client
672            .internal
673            .get_key_store()
674            .context()
675            .get_symmetric_key_id(SymmetricKeySlotId::User)
676            .expect("the V1 account's user key derives a key id")
677            .to_string();
678
679        let encrypted = client
680            .vault()
681            .ciphers()
682            .encrypt(test_cipher_view())
683            .await
684            .unwrap();
685
686        assert_eq!(
687            encrypted.encrypted_by_key_id.as_deref(),
688            Some(expected.as_str())
689        );
690    }
691
692    #[tokio::test]
693    async fn test_encrypt_cipher_with_legacy_attachment_without_key() {
694        let client = Client::init_test_account(test_bitwarden_com_account()).await;
695
696        let mut cipher = test_cipher();
697        let attachment = test_attachment_legacy();
698        cipher.attachments = Some(vec![attachment.clone()]);
699
700        let view = client
701            .vault()
702            .ciphers()
703            .decrypt(cipher.clone())
704            .await
705            .unwrap();
706
707        assert!(cipher.key.is_none());
708
709        // Assert the cipher has a key, and the attachment is still readable
710        let EncryptionContext {
711            cipher: new_cipher,
712            encrypted_for: _,
713            encrypted_by_key_id: _,
714        } = client.vault().ciphers().encrypt(view).await.unwrap();
715        assert!(new_cipher.key.is_some());
716
717        let view = client.vault().ciphers().decrypt(new_cipher).await.unwrap();
718        let attachments = view.clone().attachments.unwrap();
719        let attachment_view = attachments.first().unwrap().clone();
720        assert!(attachment_view.key.is_none());
721
722        assert_eq!(attachment_view.file_name.as_deref(), Some("h.txt"));
723
724        let buf = vec![
725            2, 100, 205, 148, 152, 77, 184, 77, 53, 80, 38, 240, 83, 217, 251, 118, 254, 27, 117,
726            41, 148, 244, 216, 110, 216, 255, 104, 215, 23, 15, 176, 239, 208, 114, 95, 159, 23,
727            211, 98, 24, 145, 166, 60, 197, 42, 204, 131, 144, 253, 204, 195, 154, 27, 201, 215,
728            43, 10, 244, 107, 226, 152, 85, 167, 66, 185,
729        ];
730
731        let content = client
732            .vault()
733            .attachments()
734            .decrypt_buffer(cipher, attachment_view.clone(), buf.as_slice())
735            .unwrap();
736
737        assert_eq!(content, b"Hello");
738    }
739
740    #[tokio::test]
741    async fn test_encrypt_cipher_with_v1_attachment_without_key() {
742        let client = Client::init_test_account(test_bitwarden_com_account()).await;
743
744        let mut cipher = test_cipher();
745        let attachment = test_attachment_v2();
746        cipher.attachments = Some(vec![attachment.clone()]);
747
748        let view = client
749            .vault()
750            .ciphers()
751            .decrypt(cipher.clone())
752            .await
753            .unwrap();
754
755        assert!(cipher.key.is_none());
756
757        // Assert the cipher has a key, and the attachment is still readable
758        let EncryptionContext {
759            cipher: new_cipher,
760            encrypted_for: _,
761            encrypted_by_key_id: _,
762        } = client.vault().ciphers().encrypt(view).await.unwrap();
763        assert!(new_cipher.key.is_some());
764
765        let view = client
766            .vault()
767            .ciphers()
768            .decrypt(new_cipher.clone())
769            .await
770            .unwrap();
771        let attachments = view.clone().attachments.unwrap();
772        let attachment_view = attachments.first().unwrap().clone();
773        assert!(attachment_view.key.is_some());
774
775        assert_eq!(attachment_view.file_name.as_deref(), Some("h.txt"));
776
777        let buf = vec![
778            2, 114, 53, 72, 20, 82, 18, 46, 48, 137, 97, 1, 100, 142, 120, 187, 28, 36, 180, 46,
779            189, 254, 133, 23, 169, 58, 73, 212, 172, 116, 185, 127, 111, 92, 112, 145, 99, 28,
780            158, 198, 48, 241, 121, 218, 66, 37, 152, 197, 122, 241, 110, 82, 245, 72, 47, 230, 95,
781            188, 196, 170, 127, 67, 44, 129, 90,
782        ];
783
784        let content = client
785            .vault()
786            .attachments()
787            .decrypt_buffer(new_cipher.clone(), attachment_view.clone(), buf.as_slice())
788            .unwrap();
789
790        assert_eq!(content, b"Hello");
791
792        // Move cipher to organization
793        let new_view = client
794            .vault()
795            .ciphers()
796            .move_to_organization(
797                view,
798                "1bc9ac1e-f5aa-45f2-94bf-b181009709b8".parse().unwrap(),
799            )
800            .unwrap();
801        let EncryptionContext {
802            cipher: new_cipher,
803            encrypted_for: _,
804            encrypted_by_key_id: _,
805        } = client.vault().ciphers().encrypt(new_view).await.unwrap();
806
807        let attachment = new_cipher
808            .clone()
809            .attachments
810            .unwrap()
811            .first()
812            .unwrap()
813            .clone();
814
815        // The attachment key (raw bytes) is unchanged; it's re-wrapped under the cipher key at
816        // encrypt time with a fresh IV, so EncString ≠ raw base64 — verify via round-trip instead.
817        assert!(attachment.key.is_some());
818
819        let content = client
820            .vault()
821            .attachments()
822            .decrypt_buffer(new_cipher, attachment_view, buf.as_slice())
823            .unwrap();
824
825        assert_eq!(content, b"Hello");
826    }
827
828    #[tokio::test]
829    async fn test_decrypt_list_full_with_failures_all_success() {
830        let client = Client::init_test_account(test_bitwarden_com_account()).await;
831
832        let valid_cipher = test_cipher();
833
834        let result = client
835            .vault()
836            .ciphers()
837            .decrypt_list_full_with_failures(vec![valid_cipher].into())
838            .await
839            .unwrap();
840
841        assert_eq!(result.successes.len(), 1);
842        assert!(result.failures.is_empty());
843        assert_eq!(result.successes[0].name, "234234");
844    }
845
846    #[tokio::test]
847    async fn test_decrypt_list_full_with_failures_mixed_results() {
848        let client = Client::init_test_account(test_bitwarden_com_account()).await;
849        let valid_cipher = test_cipher();
850        let mut invalid_cipher = test_cipher();
851        // Set an invalid encrypted key to cause decryption failure
852        invalid_cipher.key = Some("2.Gg8yCM4IIgykCZyq0O4+cA==|GJLBtfvSJTDJh/F7X4cJPkzI6ccnzJm5DYl3yxOW2iUn7DgkkmzoOe61sUhC5dgVdV0kFqsZPcQ0yehlN1DDsFIFtrb4x7LwzJNIkMgxNyg=|1rGkGJ8zcM5o5D0aIIwAyLsjMLrPsP3EWm3CctBO3Fw=".parse().unwrap());
853
854        let ciphers = vec![valid_cipher, invalid_cipher.clone()];
855
856        let result = client
857            .vault()
858            .ciphers()
859            .decrypt_list_full_with_failures(ciphers.into())
860            .await
861            .unwrap();
862
863        assert_eq!(result.successes.len(), 1);
864        assert_eq!(result.failures.len(), 1);
865
866        assert_eq!(result.successes[0].name, "234234");
867    }
868
869    #[tokio::test]
870    async fn test_decrypt_list_full_with_failures_all_failures() {
871        let client = Client::init_test_account(test_bitwarden_com_account()).await;
872        let mut invalid_cipher1 = test_cipher();
873        let mut invalid_cipher2 = test_cipher();
874        // Set invalid encrypted keys to cause decryption failures
875        invalid_cipher1.key = Some("2.Gg8yCM4IIgykCZyq0O4+cA==|GJLBtfvSJTDJh/F7X4cJPkzI6ccnzJm5DYl3yxOW2iUn7DgkkmzoOe61sUhC5dgVdV0kFqsZPcQ0yehlN1DDsFIFtrb4x7LwzJNIkMgxNyg=|1rGkGJ8zcM5o5D0aIIwAyLsjMLrPsP3EWm3CctBO3Fw=".parse().unwrap());
876        invalid_cipher2.key = Some("2.Gg8yCM4IIgykCZyq0O4+cA==|GJLBtfvSJTDJh/F7X4cJPkzI6ccnzJm5DYl3yxOW2iUn7DgkkmzoOe61sUhC5dgVdV0kFqsZPcQ0yehlN1DDsFIFtrb4x7LwzJNIkMgxNyg=|1rGkGJ8zcM5o5D0aIIwAyLsjMLrPsP3EWm3CctBO3Fw=".parse().unwrap());
877
878        let ciphers = vec![invalid_cipher1, invalid_cipher2];
879
880        let result = client
881            .vault()
882            .ciphers()
883            .decrypt_list_full_with_failures(ciphers.into())
884            .await
885            .unwrap();
886
887        assert!(result.successes.is_empty());
888        assert_eq!(result.failures.len(), 2);
889    }
890
891    #[tokio::test]
892    async fn test_decrypt_list_full_with_failures_empty_list() {
893        let client = Client::init_test_account(test_bitwarden_com_account()).await;
894
895        let result = client
896            .vault()
897            .ciphers()
898            .decrypt_list_full_with_failures(vec![].into())
899            .await
900            .unwrap();
901
902        assert!(result.successes.is_empty());
903        assert!(result.failures.is_empty());
904    }
905
906    #[tokio::test]
907    #[cfg(feature = "wasm")]
908    async fn test_encrypt_cipher_for_rotation() {
909        let client = Client::init_test_account(test_bitwarden_com_account()).await;
910
911        let new_key = SymmetricCryptoKey::make(SymmetricKeyAlgorithm::Aes256CbcHmac);
912
913        let cipher_view = test_cipher_view();
914        let new_key_b64 = new_key.to_base64();
915
916        let ctx = client
917            .vault()
918            .ciphers()
919            .encrypt_cipher_for_rotation(cipher_view, new_key_b64)
920            .await
921            .unwrap();
922
923        assert!(ctx.cipher.key.is_some());
924
925        // Decrypting the cipher "normally" will fail because it was encrypted with a new key
926        assert!(matches!(
927            client.vault().ciphers().decrypt(ctx.cipher).await.err(),
928            Some(DecryptError::Crypto(CryptoError::Decrypt))
929        ));
930    }
931
932    /// Attachments that carry no key of their own are encrypted under the old user key, so
933    /// rotation must reject them regardless of whether the view already has a cipher key.
934    #[tokio::test]
935    #[cfg(feature = "wasm")]
936    async fn test_encrypt_cipher_for_rotation_with_keyless_attachment_fails() {
937        let client = Client::init_test_account(test_bitwarden_com_account()).await;
938
939        for generate_key in [false, true] {
940            let mut cipher_view = test_cipher_view();
941            if generate_key {
942                let _ = cipher_view
943                    .load_cipher_key_slot(&mut client.internal.get_key_store().context())
944                    .unwrap();
945            }
946            cipher_view.attachments = Some(vec![AttachmentView {
947                id: None,
948                url: None,
949                size: None,
950                size_name: None,
951                file_name: Some("h.txt".to_string()),
952                key: None,
953            }]);
954
955            let new_key =
956                SymmetricCryptoKey::make(SymmetricKeyAlgorithm::Aes256CbcHmac).to_base64();
957
958            let result = client
959                .vault()
960                .ciphers()
961                .encrypt_cipher_for_rotation(cipher_view, new_key)
962                .await;
963
964            assert!(matches!(
965                result.err(),
966                Some(CipherError::AttachmentsWithoutKeys)
967            ));
968        }
969    }
970
971    #[tokio::test]
972    async fn test_encrypt_list() {
973        let client = Client::init_test_account(test_bitwarden_com_account()).await;
974
975        let cipher_views = vec![test_cipher_view(), test_cipher_view()];
976
977        let result = client.vault().ciphers().encrypt_list(cipher_views).await;
978
979        assert!(result.is_ok());
980        let contexts = result.unwrap();
981        assert_eq!(contexts.len(), 2);
982
983        // Every encrypted cipher gets a cipher key
984        for ctx in &contexts {
985            assert!(ctx.cipher.key.is_some());
986        }
987    }
988
989    #[tokio::test]
990    async fn test_encrypt_list_empty() {
991        let client = Client::init_test_account(test_bitwarden_com_account()).await;
992
993        let result = client.vault().ciphers().encrypt_list(vec![]).await;
994
995        assert!(result.is_ok());
996        assert!(result.unwrap().is_empty());
997    }
998
999    #[tokio::test]
1000    async fn test_encrypt_list_roundtrip() {
1001        let client = Client::init_test_account(test_bitwarden_com_account()).await;
1002
1003        let original_views = vec![test_cipher_view(), test_cipher_view()];
1004        let original_names: Vec<_> = original_views.iter().map(|v| v.name.clone()).collect();
1005
1006        let contexts = client
1007            .vault()
1008            .ciphers()
1009            .encrypt_list(original_views)
1010            .await
1011            .unwrap();
1012
1013        // Decrypt each cipher and verify the name matches
1014        for (ctx, original_name) in contexts.iter().zip(original_names.iter()) {
1015            let decrypted = client
1016                .vault()
1017                .ciphers()
1018                .decrypt(ctx.cipher.clone())
1019                .await
1020                .unwrap();
1021            assert_eq!(&decrypted.name, original_name);
1022        }
1023    }
1024
1025    #[tokio::test]
1026    async fn test_encrypt_list_preserves_user_id() {
1027        let client = Client::init_test_account(test_bitwarden_com_account()).await;
1028
1029        let expected_user_id = client.internal.get_user_id().unwrap();
1030
1031        let cipher_views = vec![test_cipher_view(), test_cipher_view(), test_cipher_view()];
1032        let contexts = client
1033            .vault()
1034            .ciphers()
1035            .encrypt_list(cipher_views)
1036            .await
1037            .unwrap();
1038
1039        for ctx in contexts {
1040            assert_eq!(ctx.encrypted_for, expected_user_id);
1041        }
1042    }
1043
1044    #[tokio::test]
1045    async fn should_use_blob_encryption_individual_above_threshold_returns_true() {
1046        let client = Client::init_test_account(test_bitwarden_com_account()).await;
1047        client
1048            .internal
1049            .get_key_store()
1050            .set_security_state_version(BLOB_SECURITY_VERSION);
1051
1052        assert!(client.vault().ciphers().should_use_blob_encryption(None));
1053    }
1054
1055    #[tokio::test]
1056    async fn should_use_blob_encryption_individual_below_threshold_returns_false() {
1057        let client = Client::init_test_account(test_bitwarden_com_account()).await;
1058        // Default KeyStore security_state_version is 1, below BLOB_SECURITY_VERSION (2).
1059
1060        assert!(!client.vault().ciphers().should_use_blob_encryption(None));
1061    }
1062
1063    #[tokio::test]
1064    async fn should_use_blob_encryption_organization_returns_false() {
1065        let client = Client::init_test_account(test_bitwarden_com_account()).await;
1066        client
1067            .internal
1068            .get_key_store()
1069            .set_security_state_version(BLOB_SECURITY_VERSION);
1070        let org_id: OrganizationId = "1bc9ac1e-f5aa-45f2-94bf-b181009709b8".parse().unwrap();
1071
1072        assert!(
1073            !client
1074                .vault()
1075                .ciphers()
1076                .should_use_blob_encryption(Some(org_id))
1077        );
1078    }
1079
1080    /// At `BLOB_SECURITY_VERSION`, personal ciphers encrypt through the blob
1081    /// path, producing a blob-shaped `Cipher`.
1082    #[tokio::test]
1083    async fn encrypt_produces_blob_shape_at_blob_version() {
1084        let client = Client::init_test_account(test_bitwarden_com_account()).await;
1085        client
1086            .internal
1087            .get_key_store()
1088            .set_security_state_version(BLOB_SECURITY_VERSION);
1089
1090        let ctx = client
1091            .vault()
1092            .ciphers()
1093            .encrypt(test_cipher_view())
1094            .await
1095            .unwrap();
1096
1097        assert!(try_parse_blob(&ctx.cipher).is_some());
1098        assert!(ctx.cipher.login.is_none());
1099    }
1100
1101    /// `encrypt_list` at blob version, mixing a personal (blob-eligible) view
1102    /// with an organization-owned (legacy-only) view
1103    #[tokio::test]
1104    async fn encrypt_list_mixed_personal_and_organization() {
1105        let client = Client::init_test_account(test_bitwarden_com_account()).await;
1106        client
1107            .internal
1108            .get_key_store()
1109            .set_security_state_version(BLOB_SECURITY_VERSION);
1110
1111        let personal_view = test_cipher_view();
1112        let mut org_view = test_cipher_view();
1113        org_view.organization_id = Some("1bc9ac1e-f5aa-45f2-94bf-b181009709b8".parse().unwrap());
1114
1115        let contexts = client
1116            .vault()
1117            .ciphers()
1118            .encrypt_list(vec![personal_view, org_view])
1119            .await
1120            .unwrap();
1121
1122        assert_eq!(contexts.len(), 2);
1123        assert!(
1124            try_parse_blob(&contexts[0].cipher).is_some(),
1125            "personal cipher at blob version should be blob-shaped",
1126        );
1127        assert!(
1128            try_parse_blob(&contexts[1].cipher).is_none(),
1129            "organization cipher should stay legacy-shaped",
1130        );
1131    }
1132
1133    /// Rotation at blob version must produce a blob-shaped cipher wrapped
1134    /// under the new key, not under the view's original scope slot.
1135    #[cfg(feature = "wasm")]
1136    #[tokio::test]
1137    async fn encrypt_cipher_for_rotation_blob_path() {
1138        let client = Client::init_test_account(test_bitwarden_com_account()).await;
1139        client
1140            .internal
1141            .get_key_store()
1142            .set_security_state_version(BLOB_SECURITY_VERSION);
1143
1144        let new_key = SymmetricCryptoKey::make(SymmetricKeyAlgorithm::Aes256CbcHmac);
1145        let new_key_b64 = new_key.to_base64();
1146
1147        let ctx = client
1148            .vault()
1149            .ciphers()
1150            .encrypt_cipher_for_rotation(test_cipher_view(), new_key_b64)
1151            .await
1152            .unwrap();
1153
1154        assert!(try_parse_blob(&ctx.cipher).is_some());
1155        assert!(ctx.cipher.key.is_some());
1156        // Decrypting with the current key store (which has the old user key)
1157        // fails because the cipher is now wrapped under the new key.
1158        assert!(client.vault().ciphers().decrypt(ctx.cipher).await.is_err());
1159    }
1160}