bitwarden_vault/cipher/cipher_client/
share_cipher.rs

1use bitwarden_api_api::{
2    apis::ciphers_api::CiphersApi,
3    models::{CipherBulkShareRequestModel, CipherShareRequestModel},
4};
5use bitwarden_collections::collection::CollectionId;
6use bitwarden_core::{MissingFieldError, OrganizationId, require};
7use bitwarden_crypto::EncString;
8use bitwarden_state::repository::Repository;
9#[cfg(feature = "wasm")]
10use wasm_bindgen::prelude::wasm_bindgen;
11
12use crate::{
13    Cipher, CipherError, CipherId, CipherRepromptType, CipherView, CiphersClient,
14    EncryptionContext, VaultParseError,
15};
16
17/// Standalone function that shares a cipher to an organization via API call.
18/// This function is extracted to allow for easier testing with mocked dependencies.
19async fn share_cipher(
20    api_client: &dyn CiphersApi,
21    repository: &dyn Repository<Cipher>,
22    encrypted_cipher: EncryptionContext,
23    collection_ids: Vec<CollectionId>,
24) -> Result<Cipher, CipherError> {
25    let cipher_id: uuid::Uuid = require!(encrypted_cipher.cipher.id).into();
26
27    let req = CipherShareRequestModel::new(
28        collection_ids
29            .iter()
30            .map(<CollectionId as ToString>::to_string)
31            .collect(),
32        encrypted_cipher.into(),
33    );
34
35    let response = api_client.put_share(cipher_id, Some(req)).await?;
36
37    let mut new_cipher: Cipher = response.try_into()?;
38    new_cipher.collection_ids = collection_ids;
39
40    repository
41        .set(cipher_id.to_string(), new_cipher.clone())
42        .await?;
43
44    Ok(new_cipher)
45}
46
47/// Standalone function that shares multiple ciphers to an organization via API call.
48/// This function is extracted to allow for easier testing with mocked dependencies.
49async fn share_ciphers_bulk(
50    api_client: &dyn CiphersApi,
51    repository: &dyn Repository<Cipher>,
52    encrypted_ciphers: Vec<EncryptionContext>,
53    collection_ids: Vec<CollectionId>,
54) -> Result<Vec<Cipher>, CipherError> {
55    let request = CipherBulkShareRequestModel::new(
56        collection_ids
57            .iter()
58            .map(<CollectionId as ToString>::to_string)
59            .collect(),
60        encrypted_ciphers
61            .into_iter()
62            .map(|ec| ec.try_into())
63            .collect::<Result<Vec<_>, _>>()?,
64    );
65
66    let response = api_client.put_share_many(Some(request)).await?;
67
68    let cipher_minis = response.data.unwrap_or_default();
69    let mut results = Vec::new();
70
71    for cipher_mini in cipher_minis {
72        // The server does not return the full Cipher object, so we pull the details from the
73        // current local version to fill in those missing values.
74        let orig_cipher = repository
75            .get(cipher_mini.id.ok_or(MissingFieldError("id"))?.to_string())
76            .await?;
77
78        let cipher: Cipher = Cipher {
79            id: cipher_mini.id.map(CipherId::new),
80            organization_id: cipher_mini.organization_id.map(OrganizationId::new),
81            key: EncString::try_from_optional(cipher_mini.key)?,
82            name: require!(EncString::try_from_optional(cipher_mini.name)?),
83            notes: EncString::try_from_optional(cipher_mini.notes)?,
84            r#type: require!(cipher_mini.r#type).into(),
85            login: cipher_mini.login.map(|l| (*l).try_into()).transpose()?,
86            identity: cipher_mini.identity.map(|i| (*i).try_into()).transpose()?,
87            card: cipher_mini.card.map(|c| (*c).try_into()).transpose()?,
88            secure_note: cipher_mini
89                .secure_note
90                .map(|s| (*s).try_into())
91                .transpose()?,
92            ssh_key: cipher_mini.ssh_key.map(|s| (*s).try_into()).transpose()?,
93            reprompt: cipher_mini
94                .reprompt
95                .map(|r| r.into())
96                .unwrap_or(CipherRepromptType::None),
97            organization_use_totp: cipher_mini.organization_use_totp.unwrap_or(true),
98            attachments: cipher_mini
99                .attachments
100                .map(|a| a.into_iter().map(|a| a.try_into()).collect())
101                .transpose()?,
102            fields: cipher_mini
103                .fields
104                .map(|f| f.into_iter().map(|f| f.try_into()).collect())
105                .transpose()?,
106            password_history: cipher_mini
107                .password_history
108                .map(|p| p.into_iter().map(|p| p.try_into()).collect())
109                .transpose()?,
110            creation_date: require!(cipher_mini.creation_date)
111                .parse()
112                .map_err(Into::<VaultParseError>::into)?,
113            deleted_date: cipher_mini
114                .deleted_date
115                .map(|d| d.parse())
116                .transpose()
117                .map_err(Into::<VaultParseError>::into)?,
118            revision_date: require!(cipher_mini.revision_date)
119                .parse()
120                .map_err(Into::<VaultParseError>::into)?,
121            archived_date: cipher_mini
122                .archived_date
123                .map(|d| d.parse())
124                .transpose()
125                .map_err(Into::<VaultParseError>::into)?,
126            edit: orig_cipher.as_ref().map(|c| c.edit).unwrap_or_default(),
127            favorite: orig_cipher.as_ref().map(|c| c.favorite).unwrap_or_default(),
128            folder_id: orig_cipher
129                .as_ref()
130                .map(|c| c.folder_id)
131                .unwrap_or_default(),
132            permissions: orig_cipher
133                .as_ref()
134                .map(|c| c.permissions)
135                .unwrap_or_default(),
136            view_password: orig_cipher
137                .as_ref()
138                .map(|c| c.view_password)
139                .unwrap_or_default(),
140            local_data: orig_cipher.map(|c| c.local_data).unwrap_or_default(),
141            collection_ids: collection_ids.clone(),
142            data: None,
143        };
144
145        repository
146            .set(require!(cipher.id).to_string(), cipher.clone())
147            .await?;
148        results.push(cipher)
149    }
150
151    Ok(results)
152}
153
154#[cfg_attr(feature = "wasm", wasm_bindgen)]
155impl CiphersClient {
156    fn update_organization_and_collections(
157        &self,
158        mut cipher_view: CipherView,
159        organization_id: OrganizationId,
160        collection_ids: Vec<CollectionId>,
161    ) -> Result<CipherView, CipherError> {
162        let organization_id = &organization_id;
163        if cipher_view.organization_id.is_some() {
164            return Err(CipherError::OrganizationAlreadySet);
165        }
166
167        cipher_view = self.move_to_organization(cipher_view, *organization_id)?;
168        cipher_view.collection_ids = collection_ids;
169        Ok(cipher_view)
170    }
171
172    /// Moves a cipher into an organization, adds it to collections, and calls the share_cipher API.
173    pub async fn share_cipher(
174        &self,
175        mut cipher_view: CipherView,
176        organization_id: OrganizationId,
177        collection_ids: Vec<CollectionId>,
178        original_cipher: Option<Cipher>,
179    ) -> Result<Cipher, CipherError> {
180        cipher_view = self.update_organization_and_collections(
181            cipher_view,
182            organization_id,
183            collection_ids.clone(),
184        )?;
185
186        self.update_password_history(&mut cipher_view, original_cipher)
187            .await?;
188
189        let encrypted_cipher = self.encrypt(cipher_view)?;
190
191        let api_client = &self
192            .client
193            .internal
194            .get_api_configurations()
195            .await
196            .api_client;
197
198        share_cipher(
199            api_client.ciphers_api(),
200            &*self.get_repository()?,
201            encrypted_cipher,
202            collection_ids,
203        )
204        .await
205    }
206
207    async fn update_password_history(
208        &self,
209        cipher_view: &mut CipherView,
210        mut original_cipher: Option<Cipher>,
211    ) -> Result<(), CipherError> {
212        if let (Some(cipher_id), None) = (cipher_view.id, &original_cipher) {
213            original_cipher = self.get_repository()?.get(cipher_id.to_string()).await?;
214        }
215        if let Some(original_cipher_view) = original_cipher
216            .map(|cipher| self.decrypt(cipher))
217            .transpose()?
218        {
219            cipher_view.update_password_history(&original_cipher_view);
220        }
221        Ok(())
222    }
223
224    /// Moves a group of ciphers into an organization, adds them to collections, and calls the
225    /// share_ciphers API.
226    pub async fn share_ciphers_bulk(
227        &self,
228        cipher_views: Vec<CipherView>,
229        organization_id: OrganizationId,
230        collection_ids: Vec<CollectionId>,
231    ) -> Result<Vec<Cipher>, CipherError> {
232        let mut encrypted_ciphers: Vec<EncryptionContext> = Vec::new();
233        for mut cv in cipher_views {
234            cv = self.update_organization_and_collections(
235                cv,
236                organization_id,
237                collection_ids.clone(),
238            )?;
239            self.update_password_history(&mut cv, None).await?;
240            encrypted_ciphers.push(self.encrypt(cv)?);
241        }
242
243        let api_client = &self
244            .client
245            .internal
246            .get_api_configurations()
247            .await
248            .api_client;
249
250        share_ciphers_bulk(
251            api_client.ciphers_api(),
252            &*self.get_repository()?,
253            encrypted_ciphers,
254            collection_ids,
255        )
256        .await
257    }
258}
259
260#[cfg(test)]
261mod tests {
262    use bitwarden_api_api::{
263        apis::ApiClient,
264        models::{CipherMiniResponseModelListResponseModel, CipherResponseModel},
265    };
266    use bitwarden_core::{Client, client::test_accounts::test_bitwarden_com_account};
267    use bitwarden_test::{MemoryRepository, start_api_mock};
268    use wiremock::{
269        Mock, ResponseTemplate,
270        matchers::{method, path},
271    };
272
273    use super::*;
274    use crate::{CipherRepromptType, CipherType, LoginView, VaultClientExt};
275
276    const TEST_CIPHER_ID: &str = "5faa9684-c793-4a2d-8a12-b33900187097";
277    const TEST_ORG_ID: &str = "1bc9ac1e-f5aa-45f2-94bf-b181009709b8";
278    const TEST_COLLECTION_ID_1: &str = "c1111111-1111-1111-1111-111111111111";
279    const TEST_COLLECTION_ID_2: &str = "c2222222-2222-2222-2222-222222222222";
280
281    fn test_cipher_view_without_org() -> CipherView {
282        CipherView {
283            r#type: CipherType::Login,
284            login: Some(LoginView {
285                username: Some("[email protected]".to_string()),
286                password: Some("password123".to_string()),
287                password_revision_date: None,
288                uris: None,
289                totp: None,
290                autofill_on_page_load: None,
291                fido2_credentials: None,
292            }),
293            id: Some(TEST_CIPHER_ID.parse().unwrap()),
294            organization_id: None,
295            folder_id: None,
296            collection_ids: vec![],
297            key: None,
298            name: "My test login".to_string(),
299            notes: Some("Test notes".to_string()),
300            identity: None,
301            card: None,
302            secure_note: None,
303            ssh_key: None,
304            favorite: false,
305            reprompt: CipherRepromptType::None,
306            organization_use_totp: true,
307            edit: true,
308            permissions: None,
309            view_password: true,
310            local_data: None,
311            attachments: None,
312            fields: None,
313            password_history: None,
314            creation_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
315            deleted_date: None,
316            revision_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
317            archived_date: None,
318        }
319    }
320
321    #[tokio::test]
322    async fn test_move_to_collections_success() {
323        let client = Client::init_test_account(test_bitwarden_com_account()).await;
324
325        let cipher_client = client.vault().ciphers();
326        let cipher_view = test_cipher_view_without_org();
327        let organization_id: OrganizationId = TEST_ORG_ID.parse().unwrap();
328        let collection_ids: Vec<CollectionId> = vec![
329            TEST_COLLECTION_ID_1.parse().unwrap(),
330            TEST_COLLECTION_ID_2.parse().unwrap(),
331        ];
332
333        let result = cipher_client
334            .update_organization_and_collections(
335                cipher_view,
336                organization_id,
337                collection_ids.clone(),
338            )
339            .unwrap();
340
341        assert_eq!(result.organization_id, Some(organization_id));
342        assert_eq!(result.collection_ids, collection_ids);
343    }
344
345    #[tokio::test]
346    async fn test_move_to_collections_already_in_org() {
347        let client = Client::init_test_account(test_bitwarden_com_account()).await;
348
349        let cipher_client = client.vault().ciphers();
350        let mut cipher_view = test_cipher_view_without_org();
351        cipher_view.organization_id = Some(TEST_ORG_ID.parse().unwrap());
352
353        let organization_id: OrganizationId = TEST_ORG_ID.parse().unwrap();
354        let collection_ids: Vec<CollectionId> = vec![TEST_COLLECTION_ID_1.parse().unwrap()];
355
356        let result = cipher_client.update_organization_and_collections(
357            cipher_view,
358            organization_id,
359            collection_ids,
360        );
361
362        assert!(result.is_err());
363        assert!(matches!(
364            result.unwrap_err(),
365            CipherError::OrganizationAlreadySet
366        ));
367    }
368
369    #[tokio::test]
370    async fn test_share_ciphers_bulk_already_in_org() {
371        let client = Client::init_test_account(test_bitwarden_com_account()).await;
372
373        let cipher_client = client.vault().ciphers();
374        let mut cipher_view = test_cipher_view_without_org();
375        cipher_view.organization_id = Some(TEST_ORG_ID.parse().unwrap());
376
377        let organization_id: OrganizationId = TEST_ORG_ID.parse().unwrap();
378        let collection_ids: Vec<CollectionId> = vec![TEST_COLLECTION_ID_1.parse().unwrap()];
379
380        let result = cipher_client
381            .share_ciphers_bulk(vec![cipher_view], organization_id, collection_ids)
382            .await;
383
384        assert!(result.is_err());
385        assert!(matches!(
386            result.unwrap_err(),
387            CipherError::OrganizationAlreadySet
388        ));
389    }
390
391    #[tokio::test]
392    async fn test_move_to_collections_with_attachment_without_key_fails() {
393        let client = Client::init_test_account(test_bitwarden_com_account()).await;
394
395        let cipher_client = client.vault().ciphers();
396        let mut cipher_view = test_cipher_view_without_org();
397
398        // Add an attachment WITHOUT a key - this should cause an error
399        cipher_view.attachments = Some(vec![crate::AttachmentView {
400            id: Some("attachment-456".to_string()),
401            url: Some("https://example.com/attachment".to_string()),
402            size: Some("2048".to_string()),
403            size_name: Some("2 KB".to_string()),
404            file_name: Some("test2.txt".to_string()),
405            key: None, // No key!
406            #[cfg(feature = "wasm")]
407            decrypted_key: None,
408        }]);
409
410        let organization_id: OrganizationId = TEST_ORG_ID.parse().unwrap();
411        let collection_ids: Vec<CollectionId> = vec![TEST_COLLECTION_ID_1.parse().unwrap()];
412
413        let result = cipher_client.update_organization_and_collections(
414            cipher_view,
415            organization_id,
416            collection_ids,
417        );
418
419        // Should fail because attachment is missing a key
420        assert!(result.is_err());
421        assert!(matches!(
422            result.unwrap_err(),
423            CipherError::AttachmentsWithoutKeys
424        ));
425    }
426
427    #[tokio::test]
428    async fn test_share_ciphers_bulk_multiple_validation() {
429        let client = Client::init_test_account(test_bitwarden_com_account()).await;
430
431        // Register a repository with the client so get_repository() works
432        let repository = MemoryRepository::<Cipher>::default();
433        client
434            .platform()
435            .state()
436            .register_client_managed(std::sync::Arc::new(repository));
437
438        let cipher_client = client.vault().ciphers();
439
440        // Create multiple ciphers with IDs, one already in org
441        let cipher_view_1 = test_cipher_view_without_org();
442        let mut cipher_view_2 = test_cipher_view_without_org();
443        cipher_view_2.organization_id = Some(TEST_ORG_ID.parse().unwrap());
444
445        // Encrypt and store cipher_view_1 in repository for password history lookup
446        let encrypted_1 = cipher_client.encrypt(cipher_view_1.clone()).unwrap();
447        let repository = cipher_client.get_repository().unwrap();
448        repository
449            .set(TEST_CIPHER_ID.to_string(), encrypted_1.cipher.clone())
450            .await
451            .unwrap();
452
453        let organization_id: OrganizationId = TEST_ORG_ID.parse().unwrap();
454        let collection_ids: Vec<CollectionId> = vec![TEST_COLLECTION_ID_1.parse().unwrap()];
455
456        // Should fail because one cipher already has an organization
457        let result = cipher_client
458            .share_ciphers_bulk(
459                vec![cipher_view_1, cipher_view_2],
460                organization_id,
461                collection_ids,
462            )
463            .await;
464
465        assert!(result.is_err());
466        assert!(matches!(
467            result.unwrap_err(),
468            CipherError::OrganizationAlreadySet
469        ));
470    }
471
472    fn create_encryption_context() -> EncryptionContext {
473        use bitwarden_core::UserId;
474
475        use crate::cipher::Login;
476
477        // Create a minimal encrypted cipher for testing the API logic
478        let cipher = Cipher {
479                r#type: CipherType::Login,
480                login: Some(Login {
481                    username: Some("2.EI9Km5BfrIqBa1W+WCccfA==|laWxNnx+9H3MZww4zm7cBSLisjpi81zreaQntRhegVI=|x42+qKFf5ga6DIL0OW5pxCdLrC/gm8CXJvf3UASGteI=".parse().unwrap()),
482                    password: Some("2.EI9Km5BfrIqBa1W+WCccfA==|laWxNnx+9H3MZww4zm7cBSLisjpi81zreaQntRhegVI=|x42+qKFf5ga6DIL0OW5pxCdLrC/gm8CXJvf3UASGteI=".parse().unwrap()),
483                    password_revision_date: None,
484                    uris: None,
485                    totp: None,
486                    autofill_on_page_load: None,
487                    fido2_credentials: None,
488                }),
489                id: Some(TEST_CIPHER_ID.parse().unwrap()),
490                organization_id: Some(TEST_ORG_ID.parse().unwrap()),
491                folder_id: None,
492                collection_ids: vec![TEST_COLLECTION_ID_1.parse().unwrap()],
493                key: None,
494                name: "2.EI9Km5BfrIqBa1W+WCccfA==|laWxNnx+9H3MZww4zm7cBSLisjpi81zreaQntRhegVI=|x42+qKFf5ga6DIL0OW5pxCdLrC/gm8CXJvf3UASGteI=".parse().unwrap(),
495                notes: Some("2.EI9Km5BfrIqBa1W+WCccfA==|laWxNnx+9H3MZww4zm7cBSLisjpi81zreaQntRhegVI=|x42+qKFf5ga6DIL0OW5pxCdLrC/gm8CXJvf3UASGteI=".parse().unwrap()),
496                identity: None,
497                card: None,
498                secure_note: None,
499                ssh_key: None,
500                favorite: false,
501                reprompt: CipherRepromptType::None,
502                organization_use_totp: true,
503                edit: true,
504                permissions: None,
505                view_password: true,
506                local_data: None,
507                attachments: None,
508                fields: None,
509                password_history: None,
510                creation_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
511                deleted_date: None,
512                revision_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
513                archived_date: None,
514                data: None,
515            };
516
517        // Use a test user ID from the test accounts
518        let user_id: UserId = "00000000-0000-0000-0000-000000000000".parse().unwrap();
519
520        EncryptionContext {
521            cipher,
522            encrypted_for: user_id,
523        }
524    }
525
526    #[tokio::test]
527    async fn test_share_cipher_api_success() {
528        let cipher_id: CipherId = TEST_CIPHER_ID.parse().unwrap();
529        let org_id: OrganizationId = TEST_ORG_ID.parse().unwrap();
530        let collection_id: CollectionId = TEST_COLLECTION_ID_1.parse().unwrap();
531
532        let api_client = ApiClient::new_mocked(move |mock| {
533            mock.ciphers_api.expect_put_share().returning(move |_id, _body| {
534                Ok(CipherResponseModel {
535                    object: Some("cipher".to_string()),
536                    id: Some(cipher_id.into()),
537                    organization_id: Some(org_id.into()),
538                    r#type: Some(bitwarden_api_api::models::CipherType::Login),
539                    name: Some("2.EI9Km5BfrIqBa1W+WCccfA==|laWxNnx+9H3MZww4zm7cBSLisjpi81zreaQntRhegVI=|x42+qKFf5ga6DIL0OW5pxCdLrC/gm8CXJvf3UASGteI=".to_string()),
540                    notes: Some("2.EI9Km5BfrIqBa1W+WCccfA==|laWxNnx+9H3MZww4zm7cBSLisjpi81zreaQntRhegVI=|x42+qKFf5ga6DIL0OW5pxCdLrC/gm8CXJvf3UASGteI=".to_string()),
541                    login: Some(Box::new(bitwarden_api_api::models::CipherLoginModel {
542                        username: Some("2.EI9Km5BfrIqBa1W+WCccfA==|laWxNnx+9H3MZww4zm7cBSLisjpi81zreaQntRhegVI=|x42+qKFf5ga6DIL0OW5pxCdLrC/gm8CXJvf3UASGteI=".to_string()),
543                        password: Some("2.EI9Km5BfrIqBa1W+WCccfA==|laWxNnx+9H3MZww4zm7cBSLisjpi81zreaQntRhegVI=|x42+qKFf5ga6DIL0OW5pxCdLrC/gm8CXJvf3UASGteI=".to_string()),
544                        ..Default::default()
545                    })),
546                    reprompt: Some(bitwarden_api_api::models::CipherRepromptType::None),
547                    revision_date: Some("2024-01-30T17:55:36.150Z".to_string()),
548                    creation_date: Some("2024-01-30T17:55:36.150Z".to_string()),
549                    edit: Some(true),
550                    view_password: Some(true),
551                    organization_use_totp: Some(true),
552                    favorite: Some(false),
553                    ..Default::default()
554                })
555            });
556        });
557
558        let repository = MemoryRepository::<Cipher>::default();
559        let encryption_context = create_encryption_context();
560        let collection_ids: Vec<CollectionId> = vec![collection_id];
561
562        let result = share_cipher(
563            api_client.ciphers_api(),
564            &repository,
565            encryption_context,
566            collection_ids.clone(),
567        )
568        .await;
569
570        assert!(result.is_ok());
571        let shared_cipher = result.unwrap();
572
573        // Verify the cipher was stored in repository
574        let stored_cipher = repository
575            .get(TEST_CIPHER_ID.to_string())
576            .await
577            .unwrap()
578            .expect("Cipher should be stored");
579
580        assert_eq!(stored_cipher.id, shared_cipher.id);
581        assert_eq!(
582            stored_cipher
583                .organization_id
584                .as_ref()
585                .map(ToString::to_string),
586            Some(TEST_ORG_ID.to_string())
587        );
588        assert_eq!(stored_cipher.collection_ids, collection_ids);
589    }
590
591    #[tokio::test]
592    async fn test_share_cipher_api_handles_404() {
593        let api_client = ApiClient::new_mocked(|mock| {
594            mock.ciphers_api.expect_put_share().returning(|_id, _body| {
595                Err(bitwarden_api_api::apis::Error::Io(std::io::Error::other(
596                    "Not found",
597                )))
598            });
599        });
600
601        let repository = MemoryRepository::<Cipher>::default();
602        let encryption_context = create_encryption_context();
603        let collection_ids: Vec<CollectionId> = vec![TEST_COLLECTION_ID_1.parse().unwrap()];
604
605        let result = share_cipher(
606            api_client.ciphers_api(),
607            &repository,
608            encryption_context,
609            collection_ids,
610        )
611        .await;
612
613        assert!(result.is_err());
614    }
615
616    #[tokio::test]
617    async fn test_share_ciphers_bulk_api_success() {
618        let cipher_id: CipherId = TEST_CIPHER_ID.parse().unwrap();
619        let org_id: OrganizationId = TEST_ORG_ID.parse().unwrap();
620
621        let api_client = ApiClient::new_mocked(move |mock| {
622            mock.ciphers_api.expect_put_share_many().returning(move |_body| {
623                Ok(CipherMiniResponseModelListResponseModel {
624                    object: Some("list".to_string()),
625                    data: Some(vec![bitwarden_api_api::models::CipherMiniResponseModel {
626                        object: Some("cipherMini".to_string()),
627                        id: Some(cipher_id.into()),
628                        organization_id: Some(org_id.into()),
629                        r#type: Some(bitwarden_api_api::models::CipherType::Login),
630                        name: Some("2.EI9Km5BfrIqBa1W+WCccfA==|laWxNnx+9H3MZww4zm7cBSLisjpi81zreaQntRhegVI=|x42+qKFf5ga6DIL0OW5pxCdLrC/gm8CXJvf3UASGteI=".to_string()),
631                        revision_date: Some("2024-01-30T17:55:36.150Z".to_string()),
632                        creation_date: Some("2024-01-30T17:55:36.150Z".to_string()),
633                        ..Default::default()
634                    }]),
635                    continuation_token: None,
636                })
637            });
638        });
639
640        let repository = MemoryRepository::<Cipher>::default();
641
642        // Pre-populate repository with original cipher data that will be used for missing fields
643        let original_cipher = Cipher {
644                r#type: CipherType::Login,
645                login: Some(crate::cipher::Login {
646                    username: Some("2.EI9Km5BfrIqBa1W+WCccfA==|laWxNnx+9H3MZww4zm7cBSLisjpi81zreaQntRhegVI=|x42+qKFf5ga6DIL0OW5pxCdLrC/gm8CXJvf3UASGteI=".parse().unwrap()),
647                    password: Some("2.EI9Km5BfrIqBa1W+WCccfA==|laWxNnx+9H3MZww4zm7cBSLisjpi81zreaQntRhegVI=|x42+qKFf5ga6DIL0OW5pxCdLrC/gm8CXJvf3UASGteI=".parse().unwrap()),
648                    password_revision_date: None,
649                    uris: None,
650                    totp: None,
651                    autofill_on_page_load: None,
652                    fido2_credentials: None,
653                }),
654                id: Some(TEST_CIPHER_ID.parse().unwrap()),
655                organization_id: None,
656                folder_id: None,
657                collection_ids: vec![],
658                key: None,
659                name: "2.EI9Km5BfrIqBa1W+WCccfA==|laWxNnx+9H3MZww4zm7cBSLisjpi81zreaQntRhegVI=|x42+qKFf5ga6DIL0OW5pxCdLrC/gm8CXJvf3UASGteI=".parse().unwrap(),
660                notes: Some("2.EI9Km5BfrIqBa1W+WCccfA==|laWxNnx+9H3MZww4zm7cBSLisjpi81zreaQntRhegVI=|x42+qKFf5ga6DIL0OW5pxCdLrC/gm8CXJvf3UASGteI=".parse().unwrap()),
661                identity: None,
662                card: None,
663                secure_note: None,
664                ssh_key: None,
665                favorite: true,
666                reprompt: CipherRepromptType::None,
667                organization_use_totp: true,
668                edit: true,
669                permissions: None,
670                view_password: true,
671                local_data: None,
672                attachments: None,
673                fields: None,
674                password_history: None,
675                creation_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
676                deleted_date: None,
677                revision_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
678                archived_date: None,
679                data: None,
680            };
681
682        repository
683            .set(TEST_CIPHER_ID.to_string(), original_cipher)
684            .await
685            .unwrap();
686
687        let encryption_context = create_encryption_context();
688        let collection_ids: Vec<CollectionId> = vec![
689            TEST_COLLECTION_ID_1.parse().unwrap(),
690            TEST_COLLECTION_ID_2.parse().unwrap(),
691        ];
692
693        let result = share_ciphers_bulk(
694            api_client.ciphers_api(),
695            &repository,
696            vec![encryption_context],
697            collection_ids.clone(),
698        )
699        .await;
700
701        assert!(result.is_ok());
702        let shared_ciphers = result.unwrap();
703        assert_eq!(shared_ciphers.len(), 1);
704
705        let shared_cipher = &shared_ciphers[0];
706        assert_eq!(
707            shared_cipher
708                .organization_id
709                .as_ref()
710                .map(ToString::to_string),
711            Some(TEST_ORG_ID.to_string())
712        );
713        assert_eq!(shared_cipher.collection_ids, collection_ids);
714
715        // Verify the cipher was updated in repository
716        let stored_cipher = repository
717            .get(TEST_CIPHER_ID.to_string())
718            .await
719            .unwrap()
720            .expect("Cipher should be stored");
721
722        assert_eq!(stored_cipher.id, shared_cipher.id);
723        assert!(stored_cipher.favorite); // Should preserve from original
724    }
725
726    #[tokio::test]
727    async fn test_share_ciphers_bulk_api_handles_error() {
728        let api_client = ApiClient::new_mocked(|mock| {
729            mock.ciphers_api.expect_put_share_many().returning(|_body| {
730                Err(bitwarden_api_api::apis::Error::Io(std::io::Error::other(
731                    "Server error",
732                )))
733            });
734        });
735
736        let repository = MemoryRepository::<Cipher>::default();
737        let encryption_context = create_encryption_context();
738        let collection_ids: Vec<CollectionId> = vec![TEST_COLLECTION_ID_1.parse().unwrap()];
739
740        let result = share_ciphers_bulk(
741            api_client.ciphers_api(),
742            &repository,
743            vec![encryption_context],
744            collection_ids,
745        )
746        .await;
747
748        assert!(result.is_err());
749    }
750
751    async fn make_test_client_with_wiremock(mock_server: &wiremock::MockServer) -> Client {
752        use bitwarden_core::{
753            ClientSettings, DeviceType, UserId,
754            key_management::crypto::{
755                InitOrgCryptoRequest, InitUserCryptoMethod, InitUserCryptoRequest,
756            },
757        };
758        use bitwarden_crypto::{EncString, Kdf};
759
760        let settings = ClientSettings {
761            identity_url: format!("http://{}", mock_server.address()),
762            api_url: format!("http://{}", mock_server.address()),
763            user_agent: "Bitwarden Test".into(),
764            device_type: DeviceType::SDK,
765            bitwarden_client_version: None,
766        };
767
768        let client = Client::new(Some(settings));
769
770        client
771            .internal
772            .load_flags(std::collections::HashMap::from([(
773                "enableCipherKeyEncryption".to_owned(),
774                true,
775            )]));
776
777        let user_request = InitUserCryptoRequest {
778            user_id: Some(UserId::new(uuid::uuid!("060000fb-0922-4dd3-b170-6e15cb5df8c8"))),
779            kdf_params: Kdf::PBKDF2 {
780                iterations: 600_000.try_into().unwrap(),
781            },
782            email: "[email protected]".to_owned(),
783            private_key: "2.yN7l00BOlUE0Sb0M//Q53w==|EwKG/BduQRQ33Izqc/ogoBROIoI5dmgrxSo82sgzgAMIBt3A2FZ9vPRMY+GWT85JiqytDitGR3TqwnFUBhKUpRRAq4x7rA6A1arHrFp5Tp1p21O3SfjtvB3quiOKbqWk6ZaU1Np9HwqwAecddFcB0YyBEiRX3VwF2pgpAdiPbSMuvo2qIgyob0CUoC/h4Bz1be7Qa7B0Xw9/fMKkB1LpOm925lzqosyMQM62YpMGkjMsbZz0uPopu32fxzDWSPr+kekNNyLt9InGhTpxLmq1go/pXR2uw5dfpXc5yuta7DB0EGBwnQ8Vl5HPdDooqOTD9I1jE0mRyuBpWTTI3FRnu3JUh3rIyGBJhUmHqGZvw2CKdqHCIrQeQkkEYqOeJRJVdBjhv5KGJifqT3BFRwX/YFJIChAQpebNQKXe/0kPivWokHWwXlDB7S7mBZzhaAPidZvnuIhalE2qmTypDwHy22FyqV58T8MGGMchcASDi/QXI6kcdpJzPXSeU9o+NC68QDlOIrMVxKFeE7w7PvVmAaxEo0YwmuAzzKy9QpdlK0aab/xEi8V4iXj4hGepqAvHkXIQd+r3FNeiLfllkb61p6WTjr5urcmDQMR94/wYoilpG5OlybHdbhsYHvIzYoLrC7fzl630gcO6t4nM24vdB6Ymg9BVpEgKRAxSbE62Tqacxqnz9AcmgItb48NiR/He3n3ydGjPYuKk/ihZMgEwAEZvSlNxYONSbYrIGDtOY+8Nbt6KiH3l06wjZW8tcmFeVlWv+tWotnTY9IqlAfvNVTjtsobqtQnvsiDjdEVtNy/s2ci5TH+NdZluca2OVEr91Wayxh70kpM6ib4UGbfdmGgCo74gtKvKSJU0rTHakQ5L9JlaSDD5FamBRyI0qfL43Ad9qOUZ8DaffDCyuaVyuqk7cz9HwmEmvWU3VQ+5t06n/5kRDXttcw8w+3qClEEdGo1KeENcnXCB32dQe3tDTFpuAIMLqwXs6FhpawfZ5kPYvLPczGWaqftIs/RXJ/EltGc0ugw2dmTLpoQhCqrcKEBDoYVk0LDZKsnzitOGdi9mOWse7Se8798ib1UsHFUjGzISEt6upestxOeupSTOh0v4+AjXbDzRUyogHww3V+Bqg71bkcMxtB+WM+pn1XNbVTyl9NR040nhP7KEf6e9ruXAtmrBC2ah5cFEpLIot77VFZ9ilLuitSz+7T8n1yAh1IEG6xxXxninAZIzi2qGbH69O5RSpOJuJTv17zTLJQIIc781JwQ2TTwTGnx5wZLbffhCasowJKd2EVcyMJyhz6ru0PvXWJ4hUdkARJs3Xu8dus9a86N8Xk6aAPzBDqzYb1vyFIfBxP0oO8xFHgd30Cgmz8UrSE3qeWRrF8ftrI6xQnFjHBGWD/JWSvd6YMcQED0aVuQkuNW9ST/DzQThPzRfPUoiL10yAmV7Ytu4fR3x2sF0Yfi87YhHFuCMpV/DsqxmUizyiJuD938eRcH8hzR/VO53Qo3UIsqOLcyXtTv6THjSlTopQ+JOLOnHm1w8dzYbLN44OG44rRsbihMUQp+wUZ6bsI8rrOnm9WErzkbQFbrfAINdoCiNa6cimYIjvvnMTaFWNymqY1vZxGztQiMiHiHYwTfwHTXrb9j0uPM=|09J28iXv9oWzYtzK2LBT6Yht4IT4MijEkk0fwFdrVQ4=".parse::<EncString>().unwrap(),
784            signing_key: None,
785            security_state: None,
786            method: InitUserCryptoMethod::Password {
787                password: "asdfasdfasdf".to_owned(),
788                user_key: "2.Q/2PhzcC7GdeiMHhWguYAQ==|GpqzVdr0go0ug5cZh1n+uixeBC3oC90CIe0hd/HWA/pTRDZ8ane4fmsEIcuc8eMKUt55Y2q/fbNzsYu41YTZzzsJUSeqVjT8/iTQtgnNdpo=|dwI+uyvZ1h/iZ03VQ+/wrGEFYVewBUUl/syYgjsNMbE=".parse().unwrap(),
789            }
790        };
791
792        let org_request = InitOrgCryptoRequest {
793            organization_keys: std::collections::HashMap::from([(
794                TEST_ORG_ID.parse().unwrap(),
795                "4.rY01mZFXHOsBAg5Fq4gyXuklWfm6mQASm42DJpx05a+e2mmp+P5W6r54WU2hlREX0uoTxyP91bKKwickSPdCQQ58J45LXHdr9t2uzOYyjVzpzebFcdMw1eElR9W2DW8wEk9+mvtWvKwu7yTebzND+46y1nRMoFydi5zPVLSlJEf81qZZ4Uh1UUMLwXz+NRWfixnGXgq2wRq1bH0n3mqDhayiG4LJKgGdDjWXC8W8MMXDYx24SIJrJu9KiNEMprJE+XVF9nQVNijNAjlWBqkDpsfaWTUfeVLRLctfAqW1blsmIv4RQ91PupYJZDNc8nO9ZTF3TEVM+2KHoxzDJrLs2Q==".parse().unwrap()
796            )])
797        };
798
799        client
800            .crypto()
801            .initialize_user_crypto(user_request)
802            .await
803            .unwrap();
804        client
805            .crypto()
806            .initialize_org_crypto(org_request)
807            .await
808            .unwrap();
809
810        client
811    }
812
813    #[tokio::test]
814    async fn test_share_cipher_with_password_history() {
815        use bitwarden_test::start_api_mock;
816        use wiremock::{
817            Mock, ResponseTemplate,
818            matchers::{method, path_regex},
819        };
820        let cipher_id: CipherId = TEST_CIPHER_ID.parse().unwrap();
821        let org_id: OrganizationId = TEST_ORG_ID.parse().unwrap();
822        let collection_id: CollectionId = TEST_COLLECTION_ID_1.parse().unwrap();
823
824        let mut cipher_view = test_cipher_view_without_org();
825        if let Some(ref mut login) = cipher_view.login {
826            login.password = Some("original_password_123".to_string());
827        }
828
829        // Set up wiremock server with mock that echoes back the request data
830        let mock = Mock::given(method("PUT"))
831            .and(path_regex(r"/ciphers/[a-f0-9-]+/share"))
832            .and(wiremock::matchers::body_string_contains("passwordHistory"))
833            .respond_with(move |req: &wiremock::Request| {
834                let body_bytes = req.body.as_slice();
835                let request_body: bitwarden_api_api::models::CipherShareRequestModel =
836                    serde_json::from_slice(body_bytes).expect("Failed to parse request body");
837
838                // Echo back the cipher data
839                let response = CipherResponseModel {
840                    object: Some("cipher".to_string()),
841                    id: Some(cipher_id.into()),
842                    organization_id: Some(
843                        request_body
844                            .cipher
845                            .organization_id
846                            .unwrap()
847                            .parse()
848                            .unwrap(),
849                    ),
850                    r#type: request_body.cipher.r#type,
851                    name: Some(request_body.cipher.name),
852                    notes: request_body.cipher.notes,
853                    login: request_body.cipher.login,
854                    reprompt: request_body.cipher.reprompt,
855                    password_history: request_body.cipher.password_history,
856                    revision_date: Some("2024-01-30T17:55:36.150Z".to_string()),
857                    creation_date: Some("2024-01-30T17:55:36.150Z".to_string()),
858                    edit: Some(true),
859                    view_password: Some(true),
860                    organization_use_totp: Some(true),
861                    favorite: request_body.cipher.favorite,
862                    fields: request_body.cipher.fields,
863                    key: request_body.cipher.key,
864                    ..Default::default()
865                };
866
867                ResponseTemplate::new(200).set_body_json(&response)
868            });
869
870        // Set up the client with mocked server and repository.
871        let (mock_server, _config) = start_api_mock(vec![mock]).await;
872        let client = make_test_client_with_wiremock(&mock_server).await;
873        let repository = std::sync::Arc::new(MemoryRepository::<Cipher>::default());
874        let cipher_client = client.vault().ciphers();
875        let encrypted_original = cipher_client.encrypt(cipher_view.clone()).unwrap();
876        repository
877            .set(
878                TEST_CIPHER_ID.to_string(),
879                encrypted_original.cipher.clone(),
880            )
881            .await
882            .unwrap();
883
884        client
885            .platform()
886            .state()
887            .register_client_managed(repository.clone());
888
889        // Change the password to make sure password_history is updated.
890        if let Some(ref mut login) = cipher_view.login {
891            login.password = Some("new_password_456".to_string());
892        }
893
894        let result = cipher_client
895            .share_cipher(
896                cipher_view.clone(),
897                org_id,
898                vec![collection_id],
899                Some(encrypted_original.cipher),
900            )
901            .await;
902
903        let shared_cipher = result.unwrap();
904        assert_eq!(shared_cipher.organization_id, Some(org_id));
905        let decrypted_view = cipher_client.decrypt(shared_cipher.clone()).unwrap();
906        let history = decrypted_view.password_history.unwrap();
907        assert_eq!(
908            history.len(),
909            1,
910            "Password history should have 1 entry for the changed password"
911        );
912        assert_eq!(
913            history[0].password, "original_password_123",
914            "Password history should contain the original password"
915        );
916        assert_eq!(
917            decrypted_view.login.as_ref().unwrap().password,
918            Some("new_password_456".to_string()),
919            "New password should be set"
920        );
921    }
922
923    #[tokio::test]
924    async fn test_share_ciphers_bulk_with_password_history() {
925        let org_id: OrganizationId = TEST_ORG_ID.parse().unwrap();
926        let collection_id: CollectionId = TEST_COLLECTION_ID_1.parse().unwrap();
927
928        let mut cipher_view1 = test_cipher_view_without_org();
929        cipher_view1.id = Some(TEST_CIPHER_ID.parse().unwrap());
930        if let Some(ref mut login) = cipher_view1.login {
931            login.password = Some("original_password_1".to_string());
932        }
933
934        let mut cipher_view2 = test_cipher_view_without_org();
935        cipher_view2.id = Some("11111111-2222-3333-4444-555555555555".parse().unwrap());
936        if let Some(ref mut login) = cipher_view2.login {
937            login.password = Some("original_password_2".to_string());
938        }
939
940        // Set up wiremock server with mock that echoes back the request data
941        let mock = Mock::given(method("PUT"))
942            .and(path("/ciphers/share"))
943            .and(wiremock::matchers::body_string_contains("passwordHistory"))
944            .respond_with(move |req: &wiremock::Request| {
945                let body_bytes = req.body.as_slice();
946                let request_body: bitwarden_api_api::models::CipherBulkShareRequestModel =
947                    serde_json::from_slice(body_bytes).expect("Failed to parse request body");
948
949                // Echo back the cipher data
950                let ciphers: Vec<_> = request_body
951                    .ciphers
952                    .into_iter()
953                    .map(
954                        |cipher| bitwarden_api_api::models::CipherMiniResponseModel {
955                            object: Some("cipherMini".to_string()),
956                            id: Some(cipher.id),
957                            organization_id: cipher.organization_id.and_then(|id| id.parse().ok()),
958                            r#type: cipher.r#type,
959                            name: Some(cipher.name),
960                            notes: cipher.notes,
961                            login: cipher.login,
962                            reprompt: cipher.reprompt,
963                            password_history: cipher.password_history,
964                            revision_date: Some("2024-01-30T17:55:36.150Z".to_string()),
965                            creation_date: Some("2024-01-30T17:55:36.150Z".to_string()),
966                            organization_use_totp: Some(true),
967                            fields: cipher.fields,
968                            key: cipher.key,
969                            ..Default::default()
970                        },
971                    )
972                    .collect();
973
974                let response =
975                    bitwarden_api_api::models::CipherMiniResponseModelListResponseModel {
976                        object: Some("list".to_string()),
977                        data: Some(ciphers),
978                        continuation_token: None,
979                    };
980
981                ResponseTemplate::new(200).set_body_json(&response)
982            });
983
984        // Set up the client with mocked server and repository.
985        let (mock_server, _config) = start_api_mock(vec![mock]).await;
986        let client = make_test_client_with_wiremock(&mock_server).await;
987        let repository = std::sync::Arc::new(MemoryRepository::<Cipher>::default());
988        let cipher_client = client.vault().ciphers();
989
990        let encrypted_original1 = cipher_client.encrypt(cipher_view1.clone()).unwrap();
991        repository
992            .set(
993                encrypted_original1.cipher.id.unwrap().to_string(),
994                encrypted_original1.cipher.clone(),
995            )
996            .await
997            .unwrap();
998
999        let encrypted_original2 = cipher_client.encrypt(cipher_view2.clone()).unwrap();
1000        repository
1001            .set(
1002                encrypted_original2.cipher.id.unwrap().to_string(),
1003                encrypted_original2.cipher.clone(),
1004            )
1005            .await
1006            .unwrap();
1007
1008        client
1009            .platform()
1010            .state()
1011            .register_client_managed(repository.clone());
1012
1013        // Change the passwords to make sure password_history is updated.
1014        if let Some(ref mut login) = cipher_view1.login {
1015            login.password = Some("new_password_1".to_string());
1016        }
1017        if let Some(ref mut login) = cipher_view2.login {
1018            login.password = Some("new_password_2".to_string());
1019        }
1020
1021        let result = cipher_client
1022            .share_ciphers_bulk(
1023                vec![cipher_view1, cipher_view2],
1024                org_id,
1025                vec![collection_id],
1026            )
1027            .await;
1028
1029        let shared_ciphers = result.unwrap();
1030        assert_eq!(shared_ciphers.len(), 2);
1031
1032        let decrypted_view1 = cipher_client.decrypt(shared_ciphers[0].clone()).unwrap();
1033        assert_eq!(
1034            decrypted_view1.password_history.unwrap()[0].password,
1035            "original_password_1"
1036        );
1037        assert_eq!(
1038            decrypted_view1.login.unwrap().password,
1039            Some("new_password_1".to_string())
1040        );
1041
1042        let decrypted_view2 = cipher_client.decrypt(shared_ciphers[1].clone()).unwrap();
1043        assert_eq!(
1044            decrypted_view2.password_history.unwrap()[0].password,
1045            "original_password_2"
1046        );
1047        assert_eq!(
1048            decrypted_view2.login.unwrap().password,
1049            Some("new_password_2".to_string())
1050        );
1051    }
1052}