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    async fn prepare_encrypted_ciphers_for_bulk_share(
225        &self,
226        cipher_views: Vec<CipherView>,
227        organization_id: OrganizationId,
228        collection_ids: Vec<CollectionId>,
229    ) -> Result<Vec<EncryptionContext>, CipherError> {
230        let mut encrypted_ciphers: Vec<EncryptionContext> = Vec::new();
231        for mut cv in cipher_views {
232            cv = self.update_organization_and_collections(
233                cv,
234                organization_id,
235                collection_ids.clone(),
236            )?;
237            self.update_password_history(&mut cv, None).await?;
238            encrypted_ciphers.push(self.encrypt(cv)?);
239        }
240        Ok(encrypted_ciphers)
241    }
242
243    #[cfg(feature = "uniffi")]
244    /// Prepares ciphers for bulk sharing by assigning them to an organization, adding them to
245    /// collections, updating password history, and encrypting them. This method is exposed for
246    /// UniFFI bindings. Can be removed once Mobile supports authenticated API calls via the SDK.
247    pub async fn prepare_ciphers_for_bulk_share(
248        &self,
249        cipher_views: Vec<CipherView>,
250        organization_id: OrganizationId,
251        collection_ids: Vec<CollectionId>,
252    ) -> Result<Vec<EncryptionContext>, CipherError> {
253        self.prepare_encrypted_ciphers_for_bulk_share(cipher_views, organization_id, collection_ids)
254            .await
255    }
256
257    /// Moves a group of ciphers into an organization, adds them to collections, and calls the
258    /// share_ciphers API.
259    pub async fn share_ciphers_bulk(
260        &self,
261        cipher_views: Vec<CipherView>,
262        organization_id: OrganizationId,
263        collection_ids: Vec<CollectionId>,
264    ) -> Result<Vec<Cipher>, CipherError> {
265        let encrypted_ciphers = self
266            .prepare_encrypted_ciphers_for_bulk_share(
267                cipher_views,
268                organization_id,
269                collection_ids.clone(),
270            )
271            .await?;
272
273        let api_client = &self
274            .client
275            .internal
276            .get_api_configurations()
277            .await
278            .api_client;
279
280        share_ciphers_bulk(
281            api_client.ciphers_api(),
282            &*self.get_repository()?,
283            encrypted_ciphers,
284            collection_ids,
285        )
286        .await
287    }
288}
289
290#[cfg(test)]
291mod tests {
292    use bitwarden_api_api::{
293        apis::ApiClient,
294        models::{CipherMiniResponseModelListResponseModel, CipherResponseModel},
295    };
296    use bitwarden_core::{
297        Client,
298        client::test_accounts::test_bitwarden_com_account,
299        key_management::{
300            MasterPasswordUnlockData, account_cryptographic_state::WrappedAccountCryptographicState,
301        },
302    };
303    use bitwarden_test::{MemoryRepository, start_api_mock};
304    use wiremock::{
305        Mock, ResponseTemplate,
306        matchers::{method, path},
307    };
308
309    use super::*;
310    use crate::{CipherRepromptType, CipherType, LoginView, VaultClientExt};
311
312    const TEST_CIPHER_ID: &str = "5faa9684-c793-4a2d-8a12-b33900187097";
313    const TEST_ORG_ID: &str = "1bc9ac1e-f5aa-45f2-94bf-b181009709b8";
314    const TEST_COLLECTION_ID_1: &str = "c1111111-1111-1111-1111-111111111111";
315    const TEST_COLLECTION_ID_2: &str = "c2222222-2222-2222-2222-222222222222";
316
317    fn test_cipher_view_without_org() -> CipherView {
318        CipherView {
319            r#type: CipherType::Login,
320            login: Some(LoginView {
321                username: Some("[email protected]".to_string()),
322                password: Some("password123".to_string()),
323                password_revision_date: None,
324                uris: None,
325                totp: None,
326                autofill_on_page_load: None,
327                fido2_credentials: None,
328            }),
329            id: Some(TEST_CIPHER_ID.parse().unwrap()),
330            organization_id: None,
331            folder_id: None,
332            collection_ids: vec![],
333            key: None,
334            name: "My test login".to_string(),
335            notes: Some("Test notes".to_string()),
336            identity: None,
337            card: None,
338            secure_note: None,
339            ssh_key: None,
340            favorite: false,
341            reprompt: CipherRepromptType::None,
342            organization_use_totp: true,
343            edit: true,
344            permissions: None,
345            view_password: true,
346            local_data: None,
347            attachments: None,
348            fields: None,
349            password_history: None,
350            creation_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
351            deleted_date: None,
352            revision_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
353            archived_date: None,
354        }
355    }
356
357    #[tokio::test]
358    async fn test_move_to_collections_success() {
359        let client = Client::init_test_account(test_bitwarden_com_account()).await;
360
361        let cipher_client = client.vault().ciphers();
362        let cipher_view = test_cipher_view_without_org();
363        let organization_id: OrganizationId = TEST_ORG_ID.parse().unwrap();
364        let collection_ids: Vec<CollectionId> = vec![
365            TEST_COLLECTION_ID_1.parse().unwrap(),
366            TEST_COLLECTION_ID_2.parse().unwrap(),
367        ];
368
369        let result = cipher_client
370            .update_organization_and_collections(
371                cipher_view,
372                organization_id,
373                collection_ids.clone(),
374            )
375            .unwrap();
376
377        assert_eq!(result.organization_id, Some(organization_id));
378        assert_eq!(result.collection_ids, collection_ids);
379    }
380
381    #[tokio::test]
382    async fn test_move_to_collections_already_in_org() {
383        let client = Client::init_test_account(test_bitwarden_com_account()).await;
384
385        let cipher_client = client.vault().ciphers();
386        let mut cipher_view = test_cipher_view_without_org();
387        cipher_view.organization_id = Some(TEST_ORG_ID.parse().unwrap());
388
389        let organization_id: OrganizationId = TEST_ORG_ID.parse().unwrap();
390        let collection_ids: Vec<CollectionId> = vec![TEST_COLLECTION_ID_1.parse().unwrap()];
391
392        let result = cipher_client.update_organization_and_collections(
393            cipher_view,
394            organization_id,
395            collection_ids,
396        );
397
398        assert!(result.is_err());
399        assert!(matches!(
400            result.unwrap_err(),
401            CipherError::OrganizationAlreadySet
402        ));
403    }
404
405    #[tokio::test]
406    async fn test_share_ciphers_bulk_already_in_org() {
407        let client = Client::init_test_account(test_bitwarden_com_account()).await;
408
409        let cipher_client = client.vault().ciphers();
410        let mut cipher_view = test_cipher_view_without_org();
411        cipher_view.organization_id = Some(TEST_ORG_ID.parse().unwrap());
412
413        let organization_id: OrganizationId = TEST_ORG_ID.parse().unwrap();
414        let collection_ids: Vec<CollectionId> = vec![TEST_COLLECTION_ID_1.parse().unwrap()];
415
416        let result = cipher_client
417            .share_ciphers_bulk(vec![cipher_view], organization_id, collection_ids)
418            .await;
419
420        assert!(result.is_err());
421        assert!(matches!(
422            result.unwrap_err(),
423            CipherError::OrganizationAlreadySet
424        ));
425    }
426
427    #[tokio::test]
428    async fn test_move_to_collections_with_attachment_without_key_fails() {
429        let client = Client::init_test_account(test_bitwarden_com_account()).await;
430
431        let cipher_client = client.vault().ciphers();
432        let mut cipher_view = test_cipher_view_without_org();
433
434        // Add an attachment WITHOUT a key - this should cause an error
435        cipher_view.attachments = Some(vec![crate::AttachmentView {
436            id: Some("attachment-456".to_string()),
437            url: Some("https://example.com/attachment".to_string()),
438            size: Some("2048".to_string()),
439            size_name: Some("2 KB".to_string()),
440            file_name: Some("test2.txt".to_string()),
441            key: None, // No key!
442            #[cfg(feature = "wasm")]
443            decrypted_key: None,
444        }]);
445
446        let organization_id: OrganizationId = TEST_ORG_ID.parse().unwrap();
447        let collection_ids: Vec<CollectionId> = vec![TEST_COLLECTION_ID_1.parse().unwrap()];
448
449        let result = cipher_client.update_organization_and_collections(
450            cipher_view,
451            organization_id,
452            collection_ids,
453        );
454
455        // Should fail because attachment is missing a key
456        assert!(result.is_err());
457        assert!(matches!(
458            result.unwrap_err(),
459            CipherError::AttachmentsWithoutKeys
460        ));
461    }
462
463    #[tokio::test]
464    async fn test_share_ciphers_bulk_multiple_validation() {
465        let client = Client::init_test_account(test_bitwarden_com_account()).await;
466
467        // Register a repository with the client so get_repository() works
468        let repository = MemoryRepository::<Cipher>::default();
469        client
470            .platform()
471            .state()
472            .register_client_managed(std::sync::Arc::new(repository));
473
474        let cipher_client = client.vault().ciphers();
475
476        // Create multiple ciphers with IDs, one already in org
477        let cipher_view_1 = test_cipher_view_without_org();
478        let mut cipher_view_2 = test_cipher_view_without_org();
479        cipher_view_2.organization_id = Some(TEST_ORG_ID.parse().unwrap());
480
481        // Encrypt and store cipher_view_1 in repository for password history lookup
482        let encrypted_1 = cipher_client.encrypt(cipher_view_1.clone()).unwrap();
483        let repository = cipher_client.get_repository().unwrap();
484        repository
485            .set(TEST_CIPHER_ID.to_string(), encrypted_1.cipher.clone())
486            .await
487            .unwrap();
488
489        let organization_id: OrganizationId = TEST_ORG_ID.parse().unwrap();
490        let collection_ids: Vec<CollectionId> = vec![TEST_COLLECTION_ID_1.parse().unwrap()];
491
492        // Should fail because one cipher already has an organization
493        let result = cipher_client
494            .share_ciphers_bulk(
495                vec![cipher_view_1, cipher_view_2],
496                organization_id,
497                collection_ids,
498            )
499            .await;
500
501        assert!(result.is_err());
502        assert!(matches!(
503            result.unwrap_err(),
504            CipherError::OrganizationAlreadySet
505        ));
506    }
507
508    fn create_encryption_context() -> EncryptionContext {
509        use bitwarden_core::UserId;
510
511        use crate::cipher::Login;
512
513        // Create a minimal encrypted cipher for testing the API logic
514        let cipher = Cipher {
515                r#type: CipherType::Login,
516                login: Some(Login {
517                    username: Some("2.EI9Km5BfrIqBa1W+WCccfA==|laWxNnx+9H3MZww4zm7cBSLisjpi81zreaQntRhegVI=|x42+qKFf5ga6DIL0OW5pxCdLrC/gm8CXJvf3UASGteI=".parse().unwrap()),
518                    password: Some("2.EI9Km5BfrIqBa1W+WCccfA==|laWxNnx+9H3MZww4zm7cBSLisjpi81zreaQntRhegVI=|x42+qKFf5ga6DIL0OW5pxCdLrC/gm8CXJvf3UASGteI=".parse().unwrap()),
519                    password_revision_date: None,
520                    uris: None,
521                    totp: None,
522                    autofill_on_page_load: None,
523                    fido2_credentials: None,
524                }),
525                id: Some(TEST_CIPHER_ID.parse().unwrap()),
526                organization_id: Some(TEST_ORG_ID.parse().unwrap()),
527                folder_id: None,
528                collection_ids: vec![TEST_COLLECTION_ID_1.parse().unwrap()],
529                key: None,
530                name: "2.EI9Km5BfrIqBa1W+WCccfA==|laWxNnx+9H3MZww4zm7cBSLisjpi81zreaQntRhegVI=|x42+qKFf5ga6DIL0OW5pxCdLrC/gm8CXJvf3UASGteI=".parse().unwrap(),
531                notes: Some("2.EI9Km5BfrIqBa1W+WCccfA==|laWxNnx+9H3MZww4zm7cBSLisjpi81zreaQntRhegVI=|x42+qKFf5ga6DIL0OW5pxCdLrC/gm8CXJvf3UASGteI=".parse().unwrap()),
532                identity: None,
533                card: None,
534                secure_note: None,
535                ssh_key: None,
536                favorite: false,
537                reprompt: CipherRepromptType::None,
538                organization_use_totp: true,
539                edit: true,
540                permissions: None,
541                view_password: true,
542                local_data: None,
543                attachments: None,
544                fields: None,
545                password_history: None,
546                creation_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
547                deleted_date: None,
548                revision_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
549                archived_date: None,
550                data: None,
551            };
552
553        // Use a test user ID from the test accounts
554        let user_id: UserId = "00000000-0000-0000-0000-000000000000".parse().unwrap();
555
556        EncryptionContext {
557            cipher,
558            encrypted_for: user_id,
559        }
560    }
561
562    #[tokio::test]
563    async fn test_share_cipher_api_success() {
564        let cipher_id: CipherId = TEST_CIPHER_ID.parse().unwrap();
565        let org_id: OrganizationId = TEST_ORG_ID.parse().unwrap();
566        let collection_id: CollectionId = TEST_COLLECTION_ID_1.parse().unwrap();
567
568        let api_client = ApiClient::new_mocked(move |mock| {
569            mock.ciphers_api.expect_put_share().returning(move |_id, _body| {
570                Ok(CipherResponseModel {
571                    object: Some("cipher".to_string()),
572                    id: Some(cipher_id.into()),
573                    organization_id: Some(org_id.into()),
574                    r#type: Some(bitwarden_api_api::models::CipherType::Login),
575                    name: Some("2.EI9Km5BfrIqBa1W+WCccfA==|laWxNnx+9H3MZww4zm7cBSLisjpi81zreaQntRhegVI=|x42+qKFf5ga6DIL0OW5pxCdLrC/gm8CXJvf3UASGteI=".to_string()),
576                    notes: Some("2.EI9Km5BfrIqBa1W+WCccfA==|laWxNnx+9H3MZww4zm7cBSLisjpi81zreaQntRhegVI=|x42+qKFf5ga6DIL0OW5pxCdLrC/gm8CXJvf3UASGteI=".to_string()),
577                    login: Some(Box::new(bitwarden_api_api::models::CipherLoginModel {
578                        username: Some("2.EI9Km5BfrIqBa1W+WCccfA==|laWxNnx+9H3MZww4zm7cBSLisjpi81zreaQntRhegVI=|x42+qKFf5ga6DIL0OW5pxCdLrC/gm8CXJvf3UASGteI=".to_string()),
579                        password: Some("2.EI9Km5BfrIqBa1W+WCccfA==|laWxNnx+9H3MZww4zm7cBSLisjpi81zreaQntRhegVI=|x42+qKFf5ga6DIL0OW5pxCdLrC/gm8CXJvf3UASGteI=".to_string()),
580                        ..Default::default()
581                    })),
582                    reprompt: Some(bitwarden_api_api::models::CipherRepromptType::None),
583                    revision_date: Some("2024-01-30T17:55:36.150Z".to_string()),
584                    creation_date: Some("2024-01-30T17:55:36.150Z".to_string()),
585                    edit: Some(true),
586                    view_password: Some(true),
587                    organization_use_totp: Some(true),
588                    favorite: Some(false),
589                    ..Default::default()
590                })
591            });
592        });
593
594        let repository = MemoryRepository::<Cipher>::default();
595        let encryption_context = create_encryption_context();
596        let collection_ids: Vec<CollectionId> = vec![collection_id];
597
598        let result = share_cipher(
599            api_client.ciphers_api(),
600            &repository,
601            encryption_context,
602            collection_ids.clone(),
603        )
604        .await;
605
606        assert!(result.is_ok());
607        let shared_cipher = result.unwrap();
608
609        // Verify the cipher was stored in repository
610        let stored_cipher = repository
611            .get(TEST_CIPHER_ID.to_string())
612            .await
613            .unwrap()
614            .expect("Cipher should be stored");
615
616        assert_eq!(stored_cipher.id, shared_cipher.id);
617        assert_eq!(
618            stored_cipher
619                .organization_id
620                .as_ref()
621                .map(ToString::to_string),
622            Some(TEST_ORG_ID.to_string())
623        );
624        assert_eq!(stored_cipher.collection_ids, collection_ids);
625    }
626
627    #[tokio::test]
628    async fn test_share_cipher_api_handles_404() {
629        let api_client = ApiClient::new_mocked(|mock| {
630            mock.ciphers_api.expect_put_share().returning(|_id, _body| {
631                Err(bitwarden_api_api::apis::Error::Io(std::io::Error::other(
632                    "Not found",
633                )))
634            });
635        });
636
637        let repository = MemoryRepository::<Cipher>::default();
638        let encryption_context = create_encryption_context();
639        let collection_ids: Vec<CollectionId> = vec![TEST_COLLECTION_ID_1.parse().unwrap()];
640
641        let result = share_cipher(
642            api_client.ciphers_api(),
643            &repository,
644            encryption_context,
645            collection_ids,
646        )
647        .await;
648
649        assert!(result.is_err());
650    }
651
652    #[tokio::test]
653    async fn test_share_ciphers_bulk_api_success() {
654        let cipher_id: CipherId = TEST_CIPHER_ID.parse().unwrap();
655        let org_id: OrganizationId = TEST_ORG_ID.parse().unwrap();
656
657        let api_client = ApiClient::new_mocked(move |mock| {
658            mock.ciphers_api.expect_put_share_many().returning(move |_body| {
659                Ok(CipherMiniResponseModelListResponseModel {
660                    object: Some("list".to_string()),
661                    data: Some(vec![bitwarden_api_api::models::CipherMiniResponseModel {
662                        object: Some("cipherMini".to_string()),
663                        id: Some(cipher_id.into()),
664                        organization_id: Some(org_id.into()),
665                        r#type: Some(bitwarden_api_api::models::CipherType::Login),
666                        name: Some("2.EI9Km5BfrIqBa1W+WCccfA==|laWxNnx+9H3MZww4zm7cBSLisjpi81zreaQntRhegVI=|x42+qKFf5ga6DIL0OW5pxCdLrC/gm8CXJvf3UASGteI=".to_string()),
667                        revision_date: Some("2024-01-30T17:55:36.150Z".to_string()),
668                        creation_date: Some("2024-01-30T17:55:36.150Z".to_string()),
669                        ..Default::default()
670                    }]),
671                    continuation_token: None,
672                })
673            });
674        });
675
676        let repository = MemoryRepository::<Cipher>::default();
677
678        // Pre-populate repository with original cipher data that will be used for missing fields
679        let original_cipher = Cipher {
680                r#type: CipherType::Login,
681                login: Some(crate::cipher::Login {
682                    username: Some("2.EI9Km5BfrIqBa1W+WCccfA==|laWxNnx+9H3MZww4zm7cBSLisjpi81zreaQntRhegVI=|x42+qKFf5ga6DIL0OW5pxCdLrC/gm8CXJvf3UASGteI=".parse().unwrap()),
683                    password: Some("2.EI9Km5BfrIqBa1W+WCccfA==|laWxNnx+9H3MZww4zm7cBSLisjpi81zreaQntRhegVI=|x42+qKFf5ga6DIL0OW5pxCdLrC/gm8CXJvf3UASGteI=".parse().unwrap()),
684                    password_revision_date: None,
685                    uris: None,
686                    totp: None,
687                    autofill_on_page_load: None,
688                    fido2_credentials: None,
689                }),
690                id: Some(TEST_CIPHER_ID.parse().unwrap()),
691                organization_id: None,
692                folder_id: None,
693                collection_ids: vec![],
694                key: None,
695                name: "2.EI9Km5BfrIqBa1W+WCccfA==|laWxNnx+9H3MZww4zm7cBSLisjpi81zreaQntRhegVI=|x42+qKFf5ga6DIL0OW5pxCdLrC/gm8CXJvf3UASGteI=".parse().unwrap(),
696                notes: Some("2.EI9Km5BfrIqBa1W+WCccfA==|laWxNnx+9H3MZww4zm7cBSLisjpi81zreaQntRhegVI=|x42+qKFf5ga6DIL0OW5pxCdLrC/gm8CXJvf3UASGteI=".parse().unwrap()),
697                identity: None,
698                card: None,
699                secure_note: None,
700                ssh_key: None,
701                favorite: true,
702                reprompt: CipherRepromptType::None,
703                organization_use_totp: true,
704                edit: true,
705                permissions: None,
706                view_password: true,
707                local_data: None,
708                attachments: None,
709                fields: None,
710                password_history: None,
711                creation_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
712                deleted_date: None,
713                revision_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
714                archived_date: None,
715                data: None,
716            };
717
718        repository
719            .set(TEST_CIPHER_ID.to_string(), original_cipher)
720            .await
721            .unwrap();
722
723        let encryption_context = create_encryption_context();
724        let collection_ids: Vec<CollectionId> = vec![
725            TEST_COLLECTION_ID_1.parse().unwrap(),
726            TEST_COLLECTION_ID_2.parse().unwrap(),
727        ];
728
729        let result = share_ciphers_bulk(
730            api_client.ciphers_api(),
731            &repository,
732            vec![encryption_context],
733            collection_ids.clone(),
734        )
735        .await;
736
737        assert!(result.is_ok());
738        let shared_ciphers = result.unwrap();
739        assert_eq!(shared_ciphers.len(), 1);
740
741        let shared_cipher = &shared_ciphers[0];
742        assert_eq!(
743            shared_cipher
744                .organization_id
745                .as_ref()
746                .map(ToString::to_string),
747            Some(TEST_ORG_ID.to_string())
748        );
749        assert_eq!(shared_cipher.collection_ids, collection_ids);
750
751        // Verify the cipher was updated in repository
752        let stored_cipher = repository
753            .get(TEST_CIPHER_ID.to_string())
754            .await
755            .unwrap()
756            .expect("Cipher should be stored");
757
758        assert_eq!(stored_cipher.id, shared_cipher.id);
759        assert!(stored_cipher.favorite); // Should preserve from original
760    }
761
762    #[tokio::test]
763    async fn test_share_ciphers_bulk_api_handles_error() {
764        let api_client = ApiClient::new_mocked(|mock| {
765            mock.ciphers_api.expect_put_share_many().returning(|_body| {
766                Err(bitwarden_api_api::apis::Error::Io(std::io::Error::other(
767                    "Server error",
768                )))
769            });
770        });
771
772        let repository = MemoryRepository::<Cipher>::default();
773        let encryption_context = create_encryption_context();
774        let collection_ids: Vec<CollectionId> = vec![TEST_COLLECTION_ID_1.parse().unwrap()];
775
776        let result = share_ciphers_bulk(
777            api_client.ciphers_api(),
778            &repository,
779            vec![encryption_context],
780            collection_ids,
781        )
782        .await;
783
784        assert!(result.is_err());
785    }
786
787    async fn make_test_client_with_wiremock(mock_server: &wiremock::MockServer) -> Client {
788        use bitwarden_core::{
789            ClientSettings, DeviceType, UserId,
790            key_management::crypto::{
791                InitOrgCryptoRequest, InitUserCryptoMethod, InitUserCryptoRequest,
792            },
793        };
794        use bitwarden_crypto::{EncString, Kdf};
795
796        let settings = ClientSettings {
797            identity_url: format!("http://{}", mock_server.address()),
798            api_url: format!("http://{}", mock_server.address()),
799            user_agent: "Bitwarden Test".into(),
800            device_type: DeviceType::SDK,
801            device_identifier: None,
802            bitwarden_client_version: None,
803            bitwarden_package_type: None,
804        };
805
806        let client = Client::new(Some(settings));
807
808        client
809            .internal
810            .load_flags(std::collections::HashMap::from([(
811                "enableCipherKeyEncryption".to_owned(),
812                true,
813            )]));
814
815        let user_request = InitUserCryptoRequest {
816            user_id: Some(UserId::new(uuid::uuid!("060000fb-0922-4dd3-b170-6e15cb5df8c8"))),
817            kdf_params: Kdf::PBKDF2 {
818                iterations: 600_000.try_into().unwrap(),
819            },
820            email: "[email protected]".to_owned(),
821            account_cryptographic_state: WrappedAccountCryptographicState::V1 {
822                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(),
823            },
824            method: InitUserCryptoMethod::MasterPasswordUnlock {
825                password: "asdfasdfasdf".to_owned(),
826                master_password_unlock: MasterPasswordUnlockData {
827                    kdf: Kdf::PBKDF2 {
828                        iterations: 600_000.try_into().unwrap(),
829                    },
830                    master_key_wrapped_user_key: "2.Q/2PhzcC7GdeiMHhWguYAQ==|GpqzVdr0go0ug5cZh1n+uixeBC3oC90CIe0hd/HWA/pTRDZ8ane4fmsEIcuc8eMKUt55Y2q/fbNzsYu41YTZzzsJUSeqVjT8/iTQtgnNdpo=|dwI+uyvZ1h/iZ03VQ+/wrGEFYVewBUUl/syYgjsNMbE=".parse().unwrap(),
831                    salt: "[email protected]".to_owned(),
832                },
833            },
834        };
835
836        let org_request = InitOrgCryptoRequest {
837            organization_keys: std::collections::HashMap::from([(
838                TEST_ORG_ID.parse().unwrap(),
839                "4.rY01mZFXHOsBAg5Fq4gyXuklWfm6mQASm42DJpx05a+e2mmp+P5W6r54WU2hlREX0uoTxyP91bKKwickSPdCQQ58J45LXHdr9t2uzOYyjVzpzebFcdMw1eElR9W2DW8wEk9+mvtWvKwu7yTebzND+46y1nRMoFydi5zPVLSlJEf81qZZ4Uh1UUMLwXz+NRWfixnGXgq2wRq1bH0n3mqDhayiG4LJKgGdDjWXC8W8MMXDYx24SIJrJu9KiNEMprJE+XVF9nQVNijNAjlWBqkDpsfaWTUfeVLRLctfAqW1blsmIv4RQ91PupYJZDNc8nO9ZTF3TEVM+2KHoxzDJrLs2Q==".parse().unwrap()
840            )])
841        };
842
843        client
844            .crypto()
845            .initialize_user_crypto(user_request)
846            .await
847            .unwrap();
848        client
849            .crypto()
850            .initialize_org_crypto(org_request)
851            .await
852            .unwrap();
853
854        client
855    }
856
857    #[tokio::test]
858    async fn test_share_cipher_with_password_history() {
859        use bitwarden_test::start_api_mock;
860        use wiremock::{
861            Mock, ResponseTemplate,
862            matchers::{method, path_regex},
863        };
864        let cipher_id: CipherId = TEST_CIPHER_ID.parse().unwrap();
865        let org_id: OrganizationId = TEST_ORG_ID.parse().unwrap();
866        let collection_id: CollectionId = TEST_COLLECTION_ID_1.parse().unwrap();
867
868        let mut cipher_view = test_cipher_view_without_org();
869        if let Some(ref mut login) = cipher_view.login {
870            login.password = Some("original_password_123".to_string());
871        }
872
873        // Set up wiremock server with mock that echoes back the request data
874        let mock = Mock::given(method("PUT"))
875            .and(path_regex(r"/ciphers/[a-f0-9-]+/share"))
876            .and(wiremock::matchers::body_string_contains("passwordHistory"))
877            .respond_with(move |req: &wiremock::Request| {
878                let body_bytes = req.body.as_slice();
879                let request_body: bitwarden_api_api::models::CipherShareRequestModel =
880                    serde_json::from_slice(body_bytes).expect("Failed to parse request body");
881
882                // Echo back the cipher data
883                let response = CipherResponseModel {
884                    object: Some("cipher".to_string()),
885                    id: Some(cipher_id.into()),
886                    organization_id: Some(
887                        request_body
888                            .cipher
889                            .organization_id
890                            .unwrap()
891                            .parse()
892                            .unwrap(),
893                    ),
894                    r#type: request_body.cipher.r#type,
895                    name: Some(request_body.cipher.name),
896                    notes: request_body.cipher.notes,
897                    login: request_body.cipher.login,
898                    reprompt: request_body.cipher.reprompt,
899                    password_history: request_body.cipher.password_history,
900                    revision_date: Some("2024-01-30T17:55:36.150Z".to_string()),
901                    creation_date: Some("2024-01-30T17:55:36.150Z".to_string()),
902                    edit: Some(true),
903                    view_password: Some(true),
904                    organization_use_totp: Some(true),
905                    favorite: request_body.cipher.favorite,
906                    fields: request_body.cipher.fields,
907                    key: request_body.cipher.key,
908                    ..Default::default()
909                };
910
911                ResponseTemplate::new(200).set_body_json(&response)
912            });
913
914        // Set up the client with mocked server and repository.
915        let (mock_server, _config) = start_api_mock(vec![mock]).await;
916        let client = make_test_client_with_wiremock(&mock_server).await;
917        let repository = std::sync::Arc::new(MemoryRepository::<Cipher>::default());
918        let cipher_client = client.vault().ciphers();
919        let encrypted_original = cipher_client.encrypt(cipher_view.clone()).unwrap();
920        repository
921            .set(
922                TEST_CIPHER_ID.to_string(),
923                encrypted_original.cipher.clone(),
924            )
925            .await
926            .unwrap();
927
928        client
929            .platform()
930            .state()
931            .register_client_managed(repository.clone());
932
933        // Change the password to make sure password_history is updated.
934        if let Some(ref mut login) = cipher_view.login {
935            login.password = Some("new_password_456".to_string());
936        }
937
938        let result = cipher_client
939            .share_cipher(
940                cipher_view.clone(),
941                org_id,
942                vec![collection_id],
943                Some(encrypted_original.cipher),
944            )
945            .await;
946
947        let shared_cipher = result.unwrap();
948        assert_eq!(shared_cipher.organization_id, Some(org_id));
949        let decrypted_view = cipher_client.decrypt(shared_cipher.clone()).unwrap();
950        let history = decrypted_view.password_history.unwrap();
951        assert_eq!(
952            history.len(),
953            1,
954            "Password history should have 1 entry for the changed password"
955        );
956        assert_eq!(
957            history[0].password, "original_password_123",
958            "Password history should contain the original password"
959        );
960        assert_eq!(
961            decrypted_view.login.as_ref().unwrap().password,
962            Some("new_password_456".to_string()),
963            "New password should be set"
964        );
965    }
966
967    #[tokio::test]
968    async fn test_share_ciphers_bulk_with_password_history() {
969        let org_id: OrganizationId = TEST_ORG_ID.parse().unwrap();
970        let collection_id: CollectionId = TEST_COLLECTION_ID_1.parse().unwrap();
971
972        let mut cipher_view1 = test_cipher_view_without_org();
973        cipher_view1.id = Some(TEST_CIPHER_ID.parse().unwrap());
974        if let Some(ref mut login) = cipher_view1.login {
975            login.password = Some("original_password_1".to_string());
976        }
977
978        let mut cipher_view2 = test_cipher_view_without_org();
979        cipher_view2.id = Some("11111111-2222-3333-4444-555555555555".parse().unwrap());
980        if let Some(ref mut login) = cipher_view2.login {
981            login.password = Some("original_password_2".to_string());
982        }
983
984        // Set up wiremock server with mock that echoes back the request data
985        let mock = Mock::given(method("PUT"))
986            .and(path("/ciphers/share"))
987            .and(wiremock::matchers::body_string_contains("passwordHistory"))
988            .respond_with(move |req: &wiremock::Request| {
989                let body_bytes = req.body.as_slice();
990                let request_body: bitwarden_api_api::models::CipherBulkShareRequestModel =
991                    serde_json::from_slice(body_bytes).expect("Failed to parse request body");
992
993                // Echo back the cipher data
994                let ciphers: Vec<_> = request_body
995                    .ciphers
996                    .into_iter()
997                    .map(
998                        |cipher| bitwarden_api_api::models::CipherMiniResponseModel {
999                            object: Some("cipherMini".to_string()),
1000                            id: Some(cipher.id),
1001                            organization_id: cipher.organization_id.and_then(|id| id.parse().ok()),
1002                            r#type: cipher.r#type,
1003                            name: Some(cipher.name),
1004                            notes: cipher.notes,
1005                            login: cipher.login,
1006                            reprompt: cipher.reprompt,
1007                            password_history: cipher.password_history,
1008                            revision_date: Some("2024-01-30T17:55:36.150Z".to_string()),
1009                            creation_date: Some("2024-01-30T17:55:36.150Z".to_string()),
1010                            organization_use_totp: Some(true),
1011                            fields: cipher.fields,
1012                            key: cipher.key,
1013                            ..Default::default()
1014                        },
1015                    )
1016                    .collect();
1017
1018                let response =
1019                    bitwarden_api_api::models::CipherMiniResponseModelListResponseModel {
1020                        object: Some("list".to_string()),
1021                        data: Some(ciphers),
1022                        continuation_token: None,
1023                    };
1024
1025                ResponseTemplate::new(200).set_body_json(&response)
1026            });
1027
1028        // Set up the client with mocked server and repository.
1029        let (mock_server, _config) = start_api_mock(vec![mock]).await;
1030        let client = make_test_client_with_wiremock(&mock_server).await;
1031        let repository = std::sync::Arc::new(MemoryRepository::<Cipher>::default());
1032        let cipher_client = client.vault().ciphers();
1033
1034        let encrypted_original1 = cipher_client.encrypt(cipher_view1.clone()).unwrap();
1035        repository
1036            .set(
1037                encrypted_original1.cipher.id.unwrap().to_string(),
1038                encrypted_original1.cipher.clone(),
1039            )
1040            .await
1041            .unwrap();
1042
1043        let encrypted_original2 = cipher_client.encrypt(cipher_view2.clone()).unwrap();
1044        repository
1045            .set(
1046                encrypted_original2.cipher.id.unwrap().to_string(),
1047                encrypted_original2.cipher.clone(),
1048            )
1049            .await
1050            .unwrap();
1051
1052        client
1053            .platform()
1054            .state()
1055            .register_client_managed(repository.clone());
1056
1057        // Change the passwords to make sure password_history is updated.
1058        if let Some(ref mut login) = cipher_view1.login {
1059            login.password = Some("new_password_1".to_string());
1060        }
1061        if let Some(ref mut login) = cipher_view2.login {
1062            login.password = Some("new_password_2".to_string());
1063        }
1064
1065        let result = cipher_client
1066            .share_ciphers_bulk(
1067                vec![cipher_view1, cipher_view2],
1068                org_id,
1069                vec![collection_id],
1070            )
1071            .await;
1072
1073        let shared_ciphers = result.unwrap();
1074        assert_eq!(shared_ciphers.len(), 2);
1075
1076        let decrypted_view1 = cipher_client.decrypt(shared_ciphers[0].clone()).unwrap();
1077        assert_eq!(
1078            decrypted_view1.password_history.unwrap()[0].password,
1079            "original_password_1"
1080        );
1081        assert_eq!(
1082            decrypted_view1.login.unwrap().password,
1083            Some("new_password_1".to_string())
1084        );
1085
1086        let decrypted_view2 = cipher_client.decrypt(shared_ciphers[1].clone()).unwrap();
1087        assert_eq!(
1088            decrypted_view2.password_history.unwrap()[0].password,
1089            "original_password_2"
1090        );
1091        assert_eq!(
1092            decrypted_view2.login.unwrap().password,
1093            Some("new_password_2".to_string())
1094        );
1095    }
1096}