1use std::collections::HashSet;
2
3use bitwarden_api_api::{
4 apis::ciphers_api::CiphersApi,
5 models::{CipherBulkShareRequestModel, CipherShareRequestModel},
6};
7use bitwarden_collections::collection::CollectionId;
8use bitwarden_core::{MissingFieldError, OrganizationId, require};
9use bitwarden_state::repository::Repository;
10
11use crate::{
12 Cipher, CipherError, CipherId, CipherView, CiphersClient, EncryptionContext,
13 cipher::cipher::PartialCipher,
14};
15
16async fn share_cipher(
19 api_client: &dyn CiphersApi,
20 repository: &dyn Repository<Cipher>,
21 encrypted_cipher: EncryptionContext,
22 collection_ids: Vec<CollectionId>,
23) -> Result<Cipher, CipherError> {
24 let cipher_id = require!(encrypted_cipher.cipher.id);
25 let cipher_uuid: uuid::Uuid = 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_uuid, Some(req)).await?;
36
37 let mut new_cipher: Cipher = response.merge_with_cipher(None)?;
38 new_cipher.collection_ids = collection_ids;
39
40 repository.set(cipher_id, new_cipher.clone()).await?;
41
42 Ok(new_cipher)
43}
44
45async fn share_ciphers_bulk(
48 api_client: &dyn CiphersApi,
49 repository: &dyn Repository<Cipher>,
50 encrypted_ciphers: Vec<EncryptionContext>,
51 collection_ids: Vec<CollectionId>,
52) -> Result<Vec<Cipher>, CipherError> {
53 let mut withheld_ids: HashSet<CipherId> = encrypted_ciphers
56 .iter()
57 .map(|ec| ec.cipher.id.ok_or(MissingFieldError("id")))
58 .collect::<Result<_, _>>()?;
59
60 let request = CipherBulkShareRequestModel::new(
61 collection_ids
62 .iter()
63 .map(<CollectionId as ToString>::to_string)
64 .collect(),
65 encrypted_ciphers
66 .into_iter()
67 .map(|ec| ec.try_into())
68 .collect::<Result<Vec<_>, _>>()?,
69 );
70
71 let response = api_client.put_share_many(Some(request)).await?;
72
73 let cipher_minis = response.data.unwrap_or_default();
74 let mut results = Vec::new();
75
76 for cipher_mini in cipher_minis {
77 let cipher_id = CipherId::new(cipher_mini.id.ok_or(MissingFieldError("id"))?);
80 let orig_cipher = repository.get(cipher_id).await?;
81
82 let mut cipher: Cipher = cipher_mini.merge_with_cipher(orig_cipher)?;
83 cipher.collection_ids = collection_ids.clone();
84
85 repository.set(require!(cipher.id), cipher.clone()).await?;
86 withheld_ids.remove(&cipher_id);
87 results.push(cipher)
88 }
89
90 if !withheld_ids.is_empty() {
96 repository
97 .remove_bulk(withheld_ids.into_iter().collect())
98 .await?;
99 }
100
101 Ok(results)
102}
103
104#[allow(deprecated)]
105#[bitwarden_ffi::wasm_export]
106impl CiphersClient {
107 fn update_organization_and_collections(
108 &self,
109 mut cipher_view: CipherView,
110 organization_id: OrganizationId,
111 collection_ids: Vec<CollectionId>,
112 ) -> Result<CipherView, CipherError> {
113 let organization_id = &organization_id;
114 if cipher_view.organization_id.is_some() {
115 return Err(CipherError::OrganizationAlreadySet);
116 }
117
118 cipher_view = self.move_to_organization(cipher_view, *organization_id)?;
119 cipher_view.collection_ids = collection_ids;
120 Ok(cipher_view)
121 }
122
123 pub async fn share_cipher(
125 &self,
126 mut cipher_view: CipherView,
127 organization_id: OrganizationId,
128 collection_ids: Vec<CollectionId>,
129 original_cipher_view: Option<CipherView>,
130 ) -> Result<CipherView, CipherError> {
131 cipher_view = self.update_organization_and_collections(
132 cipher_view,
133 organization_id,
134 collection_ids.clone(),
135 )?;
136
137 self.update_password_history(&mut cipher_view, original_cipher_view)
138 .await?;
139
140 let encrypted_cipher = self.encrypt(cipher_view).await?;
141
142 let api_client = &self.client.internal.get_api_configurations().api_client;
143
144 let result_cipher = share_cipher(
145 api_client.ciphers_api(),
146 &*self.get_repository()?,
147 encrypted_cipher,
148 collection_ids,
149 )
150 .await?;
151 Ok(self.decrypt(result_cipher).await?)
152 }
153
154 async fn update_password_history(
155 &self,
156 cipher_view: &mut CipherView,
157 mut original_cipher_view: Option<CipherView>,
158 ) -> Result<(), CipherError> {
159 if let Some(cipher_id) = cipher_view.id
160 && original_cipher_view.is_none()
161 && let Some(cipher) = self.get_repository()?.get(cipher_id).await?
162 {
163 original_cipher_view = Some(self.decrypt(cipher).await?);
164 }
165 if let Some(original_cipher_view) = original_cipher_view {
166 cipher_view.update_password_history(&original_cipher_view);
167 }
168 Ok(())
169 }
170
171 async fn prepare_encrypted_ciphers_for_bulk_share(
172 &self,
173 cipher_views: Vec<CipherView>,
174 organization_id: OrganizationId,
175 collection_ids: Vec<CollectionId>,
176 ) -> Result<Vec<EncryptionContext>, CipherError> {
177 let mut encrypted_ciphers: Vec<EncryptionContext> = Vec::new();
178 for mut cv in cipher_views {
179 cv = self.update_organization_and_collections(
180 cv,
181 organization_id,
182 collection_ids.clone(),
183 )?;
184 self.update_password_history(&mut cv, None).await?;
185 encrypted_ciphers.push(self.encrypt(cv).await?);
186 }
187 Ok(encrypted_ciphers)
188 }
189
190 #[cfg(feature = "uniffi")]
191 pub async fn prepare_ciphers_for_bulk_share(
195 &self,
196 cipher_views: Vec<CipherView>,
197 organization_id: OrganizationId,
198 collection_ids: Vec<CollectionId>,
199 ) -> Result<Vec<EncryptionContext>, CipherError> {
200 self.prepare_encrypted_ciphers_for_bulk_share(cipher_views, organization_id, collection_ids)
201 .await
202 }
203
204 pub async fn share_ciphers_bulk(
207 &self,
208 cipher_views: Vec<CipherView>,
209 organization_id: OrganizationId,
210 collection_ids: Vec<CollectionId>,
211 ) -> Result<Vec<CipherView>, CipherError> {
212 let encrypted_ciphers = self
213 .prepare_encrypted_ciphers_for_bulk_share(
214 cipher_views,
215 organization_id,
216 collection_ids.clone(),
217 )
218 .await?;
219
220 let api_client = &self.client.internal.get_api_configurations().api_client;
221
222 let result_ciphers = share_ciphers_bulk(
223 api_client.ciphers_api(),
224 &*self.get_repository()?,
225 encrypted_ciphers,
226 collection_ids,
227 )
228 .await?;
229
230 Ok(
231 futures::future::try_join_all(result_ciphers.into_iter().map(|c| self.decrypt(c)))
232 .await?,
233 )
234 }
235}
236
237#[cfg(test)]
238mod tests {
239 use bitwarden_api_api::{
240 apis::ApiClient,
241 models::{CipherMiniResponseModelListResponseModel, CipherResponseModel},
242 };
243 use bitwarden_core::{
244 Client,
245 client::test_accounts::test_bitwarden_com_account,
246 key_management::{
247 MasterPasswordUnlockData, account_cryptographic_state::WrappedAccountCryptographicState,
248 },
249 };
250 use bitwarden_test::{MemoryRepository, start_api_mock};
251 use wiremock::{
252 Mock, ResponseTemplate,
253 matchers::{method, path},
254 };
255
256 use super::*;
257 use crate::{CipherRepromptType, CipherType, LoginView, VaultClientExt};
258
259 const TEST_CIPHER_ID: &str = "5faa9684-c793-4a2d-8a12-b33900187097";
260 const TEST_ORG_ID: &str = "1bc9ac1e-f5aa-45f2-94bf-b181009709b8";
261 const TEST_COLLECTION_ID_1: &str = "c1111111-1111-1111-1111-111111111111";
262 const TEST_COLLECTION_ID_2: &str = "c2222222-2222-2222-2222-222222222222";
263
264 fn test_cipher_view_without_org() -> CipherView {
265 CipherView {
266 partial: false,
267 r#type: CipherType::Login,
268 login: Some(LoginView {
269 username: Some("[email protected]".to_string()),
270 password: Some("password123".to_string()),
271 password_revision_date: None,
272 uris: None,
273 totp: None,
274 autofill_on_page_load: None,
275 http_authentication_enabled: None,
276 fido2_credentials: None,
277 }),
278 id: Some(TEST_CIPHER_ID.parse().unwrap()),
279 organization_id: None,
280 folder_id: None,
281 collection_ids: vec![],
282 key: None,
283 name: "My test login".to_string(),
284 notes: Some("Test notes".to_string()),
285 identity: None,
286 card: None,
287 secure_note: None,
288 ssh_key: None,
289 bank_account: None,
290 drivers_license: None,
291 passport: None,
292 favorite: false,
293 reprompt: CipherRepromptType::None,
294 organization_use_totp: true,
295 edit: true,
296 permissions: None,
297 view_password: true,
298 local_data: None,
299 attachments: None,
300 attachment_decryption_failures: None,
301 fields: None,
302 password_history: None,
303 creation_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
304 deleted_date: None,
305 revision_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
306 archived_date: None,
307 }
308 }
309
310 #[tokio::test]
311 async fn test_move_to_collections_success() {
312 let client = Client::init_test_account(test_bitwarden_com_account()).await;
313
314 let cipher_client = client.vault().ciphers();
315 let cipher_view = test_cipher_view_without_org();
316 let organization_id: OrganizationId = TEST_ORG_ID.parse().unwrap();
317 let collection_ids: Vec<CollectionId> = vec![
318 TEST_COLLECTION_ID_1.parse().unwrap(),
319 TEST_COLLECTION_ID_2.parse().unwrap(),
320 ];
321
322 let result = cipher_client
323 .update_organization_and_collections(
324 cipher_view,
325 organization_id,
326 collection_ids.clone(),
327 )
328 .unwrap();
329
330 assert_eq!(result.organization_id, Some(organization_id));
331 assert_eq!(result.collection_ids, collection_ids);
332 }
333
334 #[tokio::test]
335 async fn test_move_to_collections_already_in_org() {
336 let client = Client::init_test_account(test_bitwarden_com_account()).await;
337
338 let cipher_client = client.vault().ciphers();
339 let mut cipher_view = test_cipher_view_without_org();
340 cipher_view.organization_id = Some(TEST_ORG_ID.parse().unwrap());
341
342 let organization_id: OrganizationId = TEST_ORG_ID.parse().unwrap();
343 let collection_ids: Vec<CollectionId> = vec![TEST_COLLECTION_ID_1.parse().unwrap()];
344
345 let result = cipher_client.update_organization_and_collections(
346 cipher_view,
347 organization_id,
348 collection_ids,
349 );
350
351 assert!(result.is_err());
352 assert!(matches!(
353 result.unwrap_err(),
354 CipherError::OrganizationAlreadySet
355 ));
356 }
357
358 #[tokio::test]
359 async fn test_share_ciphers_bulk_already_in_org() {
360 let client = Client::init_test_account(test_bitwarden_com_account()).await;
361
362 let cipher_client = client.vault().ciphers();
363 let mut cipher_view = test_cipher_view_without_org();
364 cipher_view.organization_id = Some(TEST_ORG_ID.parse().unwrap());
365
366 let organization_id: OrganizationId = TEST_ORG_ID.parse().unwrap();
367 let collection_ids: Vec<CollectionId> = vec![TEST_COLLECTION_ID_1.parse().unwrap()];
368
369 let result = cipher_client
370 .share_ciphers_bulk(vec![cipher_view], organization_id, collection_ids)
371 .await;
372
373 assert!(result.is_err());
374 assert!(matches!(
375 result.unwrap_err(),
376 CipherError::OrganizationAlreadySet
377 ));
378 }
379
380 #[tokio::test]
381 async fn test_move_to_collections_with_attachment_without_key_fails() {
382 let client = Client::init_test_account(test_bitwarden_com_account()).await;
383
384 let cipher_client = client.vault().ciphers();
385 let mut cipher_view = test_cipher_view_without_org();
386
387 cipher_view.attachments = Some(vec![crate::AttachmentView {
389 id: Some("attachment-456".to_string()),
390 url: Some("https://example.com/attachment".to_string()),
391 size: Some("2048".to_string()),
392 size_name: Some("2 KB".to_string()),
393 file_name: Some("test2.txt".to_string()),
394 key: None, }]);
396
397 let organization_id: OrganizationId = TEST_ORG_ID.parse().unwrap();
398 let collection_ids: Vec<CollectionId> = vec![TEST_COLLECTION_ID_1.parse().unwrap()];
399
400 let result = cipher_client.update_organization_and_collections(
401 cipher_view,
402 organization_id,
403 collection_ids,
404 );
405
406 assert!(result.is_err());
408 assert!(matches!(
409 result.unwrap_err(),
410 CipherError::AttachmentsWithoutKeys
411 ));
412 }
413
414 #[tokio::test]
415 async fn test_share_ciphers_bulk_multiple_validation() {
416 let client = Client::init_test_account(test_bitwarden_com_account()).await;
417
418 let repository = MemoryRepository::<Cipher>::default();
420 client
421 .platform()
422 .state()
423 .register_client_managed(std::sync::Arc::new(repository));
424
425 let cipher_client = client.vault().ciphers();
426
427 let cipher_view_1 = test_cipher_view_without_org();
429 let mut cipher_view_2 = test_cipher_view_without_org();
430 cipher_view_2.organization_id = Some(TEST_ORG_ID.parse().unwrap());
431
432 let encrypted_1 = cipher_client.encrypt(cipher_view_1.clone()).await.unwrap();
434 let repository = cipher_client.get_repository().unwrap();
435 repository
436 .set(TEST_CIPHER_ID.parse().unwrap(), encrypted_1.cipher.clone())
437 .await
438 .unwrap();
439
440 let organization_id: OrganizationId = TEST_ORG_ID.parse().unwrap();
441 let collection_ids: Vec<CollectionId> = vec![TEST_COLLECTION_ID_1.parse().unwrap()];
442
443 let result = cipher_client
445 .share_ciphers_bulk(
446 vec![cipher_view_1, cipher_view_2],
447 organization_id,
448 collection_ids,
449 )
450 .await;
451
452 assert!(result.is_err());
453 assert!(matches!(
454 result.unwrap_err(),
455 CipherError::OrganizationAlreadySet
456 ));
457 }
458
459 fn create_encryption_context() -> EncryptionContext {
460 use bitwarden_core::UserId;
461
462 use crate::cipher::Login;
463
464 let cipher = Cipher {
466 partial_data: None,
467 r#type: CipherType::Login,
468 login: Some(Login {
469 username: Some("2.EI9Km5BfrIqBa1W+WCccfA==|laWxNnx+9H3MZww4zm7cBSLisjpi81zreaQntRhegVI=|x42+qKFf5ga6DIL0OW5pxCdLrC/gm8CXJvf3UASGteI=".parse().unwrap()),
470 password: Some("2.EI9Km5BfrIqBa1W+WCccfA==|laWxNnx+9H3MZww4zm7cBSLisjpi81zreaQntRhegVI=|x42+qKFf5ga6DIL0OW5pxCdLrC/gm8CXJvf3UASGteI=".parse().unwrap()),
471 password_revision_date: None,
472 uris: None,
473 totp: None,
474 autofill_on_page_load: None,
475 http_authentication_enabled: None,
476 fido2_credentials: None,
477 }),
478 id: Some(TEST_CIPHER_ID.parse().unwrap()),
479 organization_id: Some(TEST_ORG_ID.parse().unwrap()),
480 folder_id: None,
481 collection_ids: vec![TEST_COLLECTION_ID_1.parse().unwrap()],
482 key: None,
483 name: Some("2.EI9Km5BfrIqBa1W+WCccfA==|laWxNnx+9H3MZww4zm7cBSLisjpi81zreaQntRhegVI=|x42+qKFf5ga6DIL0OW5pxCdLrC/gm8CXJvf3UASGteI=".parse().unwrap()),
484 notes: Some("2.EI9Km5BfrIqBa1W+WCccfA==|laWxNnx+9H3MZww4zm7cBSLisjpi81zreaQntRhegVI=|x42+qKFf5ga6DIL0OW5pxCdLrC/gm8CXJvf3UASGteI=".parse().unwrap()),
485 identity: None,
486 card: None,
487 secure_note: None,
488 ssh_key: None,
489 bank_account: None,
490 drivers_license: None,
491 passport: None,
492 favorite: false,
493 reprompt: CipherRepromptType::None,
494 organization_use_totp: true,
495 edit: true,
496 permissions: None,
497 view_password: true,
498 local_data: None,
499 attachments: None,
500 fields: None,
501 password_history: None,
502 creation_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
503 deleted_date: None,
504 revision_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
505 archived_date: None,
506 data: None,
507 };
508
509 let user_id: UserId = "00000000-0000-0000-0000-000000000000".parse().unwrap();
511
512 EncryptionContext {
513 cipher,
514 encrypted_for: user_id,
515 encrypted_by_key_id: None,
516 }
517 }
518
519 #[tokio::test]
520 async fn test_share_cipher_api_success() {
521 let cipher_id: CipherId = TEST_CIPHER_ID.parse().unwrap();
522 let org_id: OrganizationId = TEST_ORG_ID.parse().unwrap();
523 let collection_id: CollectionId = TEST_COLLECTION_ID_1.parse().unwrap();
524
525 let api_client = ApiClient::new_mocked(move |mock| {
526 mock.ciphers_api.expect_put_share().returning(move |_id, _body| {
527 Ok(CipherResponseModel {
528 object: Some("cipher".to_string()),
529 id: Some(cipher_id.into()),
530 organization_id: Some(org_id.into()),
531 r#type: Some(bitwarden_api_api::models::CipherType::Login),
532 name: Some("2.EI9Km5BfrIqBa1W+WCccfA==|laWxNnx+9H3MZww4zm7cBSLisjpi81zreaQntRhegVI=|x42+qKFf5ga6DIL0OW5pxCdLrC/gm8CXJvf3UASGteI=".to_string()),
533 notes: Some("2.EI9Km5BfrIqBa1W+WCccfA==|laWxNnx+9H3MZww4zm7cBSLisjpi81zreaQntRhegVI=|x42+qKFf5ga6DIL0OW5pxCdLrC/gm8CXJvf3UASGteI=".to_string()),
534 login: Some(Box::new(bitwarden_api_api::models::CipherLoginModel {
535 username: Some("2.EI9Km5BfrIqBa1W+WCccfA==|laWxNnx+9H3MZww4zm7cBSLisjpi81zreaQntRhegVI=|x42+qKFf5ga6DIL0OW5pxCdLrC/gm8CXJvf3UASGteI=".to_string()),
536 password: Some("2.EI9Km5BfrIqBa1W+WCccfA==|laWxNnx+9H3MZww4zm7cBSLisjpi81zreaQntRhegVI=|x42+qKFf5ga6DIL0OW5pxCdLrC/gm8CXJvf3UASGteI=".to_string()),
537 ..Default::default()
538 })),
539 reprompt: Some(bitwarden_api_api::models::CipherRepromptType::None),
540 revision_date: Some("2024-01-30T17:55:36.150Z".to_string()),
541 creation_date: Some("2024-01-30T17:55:36.150Z".to_string()),
542 edit: Some(true),
543 view_password: Some(true),
544 organization_use_totp: Some(true),
545 favorite: Some(false),
546 ..Default::default()
547 })
548 });
549 });
550
551 let repository = MemoryRepository::<Cipher>::default();
552 let encryption_context = create_encryption_context();
553 let collection_ids: Vec<CollectionId> = vec![collection_id];
554
555 let result = share_cipher(
556 api_client.ciphers_api(),
557 &repository,
558 encryption_context,
559 collection_ids.clone(),
560 )
561 .await;
562
563 assert!(result.is_ok());
564 let shared_cipher = result.unwrap();
565
566 let stored_cipher = repository
568 .get(TEST_CIPHER_ID.parse().unwrap())
569 .await
570 .unwrap()
571 .expect("Cipher should be stored");
572
573 assert_eq!(stored_cipher.id, shared_cipher.id);
574 assert_eq!(
575 stored_cipher
576 .organization_id
577 .as_ref()
578 .map(ToString::to_string),
579 Some(TEST_ORG_ID.to_string())
580 );
581 assert_eq!(stored_cipher.collection_ids, collection_ids);
582 }
583
584 #[tokio::test]
585 async fn test_share_cipher_api_handles_404() {
586 let api_client = ApiClient::new_mocked(|mock| {
587 mock.ciphers_api
588 .expect_put_share()
589 .returning(|_id, _body| Err(std::io::Error::other("Not found").into()));
590 });
591
592 let repository = MemoryRepository::<Cipher>::default();
593 let encryption_context = create_encryption_context();
594 let collection_ids: Vec<CollectionId> = vec![TEST_COLLECTION_ID_1.parse().unwrap()];
595
596 let result = share_cipher(
597 api_client.ciphers_api(),
598 &repository,
599 encryption_context,
600 collection_ids,
601 )
602 .await;
603
604 assert!(result.is_err());
605 }
606
607 #[tokio::test]
608 async fn test_share_ciphers_bulk_api_success() {
609 let cipher_id: CipherId = TEST_CIPHER_ID.parse().unwrap();
610 let org_id: OrganizationId = TEST_ORG_ID.parse().unwrap();
611
612 let api_client = ApiClient::new_mocked(move |mock| {
613 mock.ciphers_api.expect_put_share_many().returning(move |_body| {
614 Ok(CipherMiniResponseModelListResponseModel {
615 object: Some("list".to_string()),
616 data: Some(vec![bitwarden_api_api::models::CipherMiniResponseModel {
617 object: Some("cipherMini".to_string()),
618 id: Some(cipher_id.into()),
619 organization_id: Some(org_id.into()),
620 r#type: Some(bitwarden_api_api::models::CipherType::Login),
621 name: Some("2.EI9Km5BfrIqBa1W+WCccfA==|laWxNnx+9H3MZww4zm7cBSLisjpi81zreaQntRhegVI=|x42+qKFf5ga6DIL0OW5pxCdLrC/gm8CXJvf3UASGteI=".to_string()),
622 revision_date: Some("2024-01-30T17:55:36.150Z".to_string()),
623 creation_date: Some("2024-01-30T17:55:36.150Z".to_string()),
624 ..Default::default()
625 }]),
626 continuation_token: None,
627 })
628 });
629 });
630
631 let repository = MemoryRepository::<Cipher>::default();
632
633 let original_cipher = Cipher {
635 partial_data: None,
636 r#type: CipherType::Login,
637 login: Some(crate::cipher::Login {
638 username: Some("2.EI9Km5BfrIqBa1W+WCccfA==|laWxNnx+9H3MZww4zm7cBSLisjpi81zreaQntRhegVI=|x42+qKFf5ga6DIL0OW5pxCdLrC/gm8CXJvf3UASGteI=".parse().unwrap()),
639 password: Some("2.EI9Km5BfrIqBa1W+WCccfA==|laWxNnx+9H3MZww4zm7cBSLisjpi81zreaQntRhegVI=|x42+qKFf5ga6DIL0OW5pxCdLrC/gm8CXJvf3UASGteI=".parse().unwrap()),
640 password_revision_date: None,
641 uris: None,
642 totp: None,
643 autofill_on_page_load: None,
644 http_authentication_enabled: None,
645 fido2_credentials: None,
646 }),
647 id: Some(TEST_CIPHER_ID.parse().unwrap()),
648 organization_id: None,
649 folder_id: None,
650 collection_ids: vec![],
651 key: None,
652 name: Some("2.EI9Km5BfrIqBa1W+WCccfA==|laWxNnx+9H3MZww4zm7cBSLisjpi81zreaQntRhegVI=|x42+qKFf5ga6DIL0OW5pxCdLrC/gm8CXJvf3UASGteI=".parse().unwrap()),
653 notes: Some("2.EI9Km5BfrIqBa1W+WCccfA==|laWxNnx+9H3MZww4zm7cBSLisjpi81zreaQntRhegVI=|x42+qKFf5ga6DIL0OW5pxCdLrC/gm8CXJvf3UASGteI=".parse().unwrap()),
654 identity: None,
655 card: None,
656 secure_note: None,
657 ssh_key: None,
658 bank_account: None,
659 drivers_license: None,
660 passport: None,
661 favorite: true,
662 reprompt: CipherRepromptType::None,
663 organization_use_totp: true,
664 edit: true,
665 permissions: None,
666 view_password: true,
667 local_data: None,
668 attachments: None,
669 fields: None,
670 password_history: None,
671 creation_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
672 deleted_date: None,
673 revision_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
674 archived_date: None,
675 data: None,
676 };
677
678 repository
679 .set(TEST_CIPHER_ID.parse().unwrap(), original_cipher)
680 .await
681 .unwrap();
682
683 let encryption_context = create_encryption_context();
684 let collection_ids: Vec<CollectionId> = vec![
685 TEST_COLLECTION_ID_1.parse().unwrap(),
686 TEST_COLLECTION_ID_2.parse().unwrap(),
687 ];
688
689 let result = share_ciphers_bulk(
690 api_client.ciphers_api(),
691 &repository,
692 vec![encryption_context],
693 collection_ids.clone(),
694 )
695 .await;
696
697 assert!(result.is_ok());
698 let shared_ciphers = result.unwrap();
699 assert_eq!(shared_ciphers.len(), 1);
700
701 let shared_cipher = &shared_ciphers[0];
702 assert_eq!(
703 shared_cipher
704 .organization_id
705 .as_ref()
706 .map(ToString::to_string),
707 Some(TEST_ORG_ID.to_string())
708 );
709 assert_eq!(shared_cipher.collection_ids, collection_ids);
710
711 let stored_cipher = repository
713 .get(TEST_CIPHER_ID.parse().unwrap())
714 .await
715 .unwrap()
716 .expect("Cipher should be stored");
717
718 assert_eq!(stored_cipher.id, shared_cipher.id);
719 assert!(stored_cipher.favorite); }
721
722 #[tokio::test]
727 async fn test_share_ciphers_bulk_persists_a_gated_write_return() {
728 let cipher_id: CipherId = TEST_CIPHER_ID.parse().unwrap();
729 let org_id: OrganizationId = TEST_ORG_ID.parse().unwrap();
730
731 let api_client = ApiClient::new_mocked(move |mock| {
732 mock.ciphers_api
733 .expect_put_share_many()
734 .returning(move |_body| {
735 Ok(CipherMiniResponseModelListResponseModel {
736 object: Some("list".to_string()),
737 data: Some(vec![bitwarden_api_api::models::CipherMiniResponseModel {
738 object: Some("cipherMini".to_string()),
739 id: Some(cipher_id.into()),
740 organization_id: Some(org_id.into()),
741 r#type: Some(bitwarden_api_api::models::CipherType::Login),
742 partial_data: Some(
743 r#"{"strippedFields":["login","name","notes"]}"#.to_string(),
744 ),
745 name: None,
746 notes: None,
747 login: None,
748 revision_date: Some("2024-01-30T17:55:36.150Z".to_string()),
749 creation_date: Some("2024-01-30T17:55:36.150Z".to_string()),
750 ..Default::default()
751 }]),
752 continuation_token: None,
753 })
754 });
755 });
756
757 let repository = MemoryRepository::<Cipher>::default();
758
759 let original_cipher = Cipher {
762 partial_data: None,
763 r#type: CipherType::Login,
764 login: Some(crate::cipher::Login {
765 username: Some("2.EI9Km5BfrIqBa1W+WCccfA==|laWxNnx+9H3MZww4zm7cBSLisjpi81zreaQntRhegVI=|x42+qKFf5ga6DIL0OW5pxCdLrC/gm8CXJvf3UASGteI=".parse().unwrap()),
766 password: Some("2.EI9Km5BfrIqBa1W+WCccfA==|laWxNnx+9H3MZww4zm7cBSLisjpi81zreaQntRhegVI=|x42+qKFf5ga6DIL0OW5pxCdLrC/gm8CXJvf3UASGteI=".parse().unwrap()),
767 password_revision_date: None,
768 uris: None,
769 totp: None,
770 autofill_on_page_load: None,
771 http_authentication_enabled: None,
772 fido2_credentials: None,
773 }),
774 id: Some(TEST_CIPHER_ID.parse().unwrap()),
775 organization_id: None,
776 folder_id: Some(crate::FolderId::new(uuid::uuid!(
777 "b1111111-1111-1111-1111-111111111111"
778 ))),
779 collection_ids: vec![],
780 key: None,
781 name: Some("2.EI9Km5BfrIqBa1W+WCccfA==|laWxNnx+9H3MZww4zm7cBSLisjpi81zreaQntRhegVI=|x42+qKFf5ga6DIL0OW5pxCdLrC/gm8CXJvf3UASGteI=".parse().unwrap()),
782 notes: Some("2.EI9Km5BfrIqBa1W+WCccfA==|laWxNnx+9H3MZww4zm7cBSLisjpi81zreaQntRhegVI=|x42+qKFf5ga6DIL0OW5pxCdLrC/gm8CXJvf3UASGteI=".parse().unwrap()),
783 identity: None,
784 card: None,
785 secure_note: None,
786 ssh_key: None,
787 bank_account: None,
788 drivers_license: None,
789 passport: None,
790 favorite: true,
791 reprompt: CipherRepromptType::None,
792 organization_use_totp: true,
793 edit: true,
794 permissions: None,
795 view_password: true,
796 local_data: None,
797 attachments: None,
798 fields: None,
799 password_history: None,
800 creation_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
801 deleted_date: None,
802 revision_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
803 archived_date: None,
804 data: None,
805 };
806 let original_folder_id = original_cipher.folder_id;
807
808 repository
809 .set(TEST_CIPHER_ID.parse().unwrap(), original_cipher)
810 .await
811 .unwrap();
812
813 let encryption_context = create_encryption_context();
814 let collection_ids: Vec<CollectionId> = vec![
815 TEST_COLLECTION_ID_1.parse().unwrap(),
816 TEST_COLLECTION_ID_2.parse().unwrap(),
817 ];
818
819 let result = share_ciphers_bulk(
820 api_client.ciphers_api(),
821 &repository,
822 vec![encryption_context],
823 collection_ids.clone(),
824 )
825 .await;
826
827 assert!(result.is_ok());
828 let shared_ciphers = result.unwrap();
829 assert_eq!(shared_ciphers.len(), 1);
830
831 let stored_cipher = repository
832 .get(TEST_CIPHER_ID.parse().unwrap())
833 .await
834 .unwrap()
835 .expect("Cipher should be stored");
836
837 assert!(
838 stored_cipher.partial_data.is_some(),
839 "gated write-return must stay gated in the repository"
840 );
841 assert!(
842 stored_cipher.login.is_none(),
843 "no secret field may reach local state"
844 );
845 assert!(stored_cipher.name.is_none());
846 assert_eq!(stored_cipher.collection_ids, collection_ids);
847 assert!(
848 stored_cipher.favorite,
849 "local-only fields must survive the merge"
850 );
851 assert_eq!(stored_cipher.folder_id, original_folder_id);
852 }
853
854 #[tokio::test]
859 async fn test_share_ciphers_bulk_evicts_a_stripped_write_return() {
860 let returned_id: CipherId = TEST_CIPHER_ID.parse().unwrap();
861 let stripped_id: CipherId = "11111111-2222-3333-4444-555555555555".parse().unwrap();
862 let org_id: OrganizationId = TEST_ORG_ID.parse().unwrap();
863
864 let api_client = ApiClient::new_mocked(move |mock| {
865 mock.ciphers_api
866 .expect_put_share_many()
867 .returning(move |_body| {
868 Ok(CipherMiniResponseModelListResponseModel {
871 object: Some("list".to_string()),
872 data: Some(vec![bitwarden_api_api::models::CipherMiniResponseModel {
873 object: Some("cipherMini".to_string()),
874 id: Some(returned_id.into()),
875 organization_id: Some(org_id.into()),
876 r#type: Some(bitwarden_api_api::models::CipherType::Login),
877 name: Some("2.EI9Km5BfrIqBa1W+WCccfA==|laWxNnx+9H3MZww4zm7cBSLisjpi81zreaQntRhegVI=|x42+qKFf5ga6DIL0OW5pxCdLrC/gm8CXJvf3UASGteI=".to_string()),
878 revision_date: Some("2024-01-30T17:55:36.150Z".to_string()),
879 creation_date: Some("2024-01-30T17:55:36.150Z".to_string()),
880 ..Default::default()
881 }]),
882 continuation_token: None,
883 })
884 });
885 });
886
887 let repository = MemoryRepository::<Cipher>::default();
888
889 let mut original_returned = create_encryption_context().cipher;
892 original_returned.organization_id = None;
893 original_returned.collection_ids = vec![];
894 repository
895 .set(returned_id, original_returned)
896 .await
897 .unwrap();
898
899 let mut original_stripped = create_encryption_context().cipher;
900 original_stripped.id = Some(stripped_id);
901 original_stripped.organization_id = None;
902 original_stripped.collection_ids = vec![];
903 repository
904 .set(stripped_id, original_stripped)
905 .await
906 .unwrap();
907
908 let mut encryption_context_returned = create_encryption_context();
909 encryption_context_returned.cipher.id = Some(returned_id);
910 let mut encryption_context_stripped = create_encryption_context();
911 encryption_context_stripped.cipher.id = Some(stripped_id);
912
913 let collection_ids: Vec<CollectionId> = vec![TEST_COLLECTION_ID_1.parse().unwrap()];
914
915 let result = share_ciphers_bulk(
916 api_client.ciphers_api(),
917 &repository,
918 vec![encryption_context_returned, encryption_context_stripped],
919 collection_ids,
920 )
921 .await;
922
923 assert!(result.is_ok());
924 let shared_ciphers = result.unwrap();
925 assert_eq!(
926 shared_ciphers.len(),
927 1,
928 "only the ciphers the server returned are reported back to the caller"
929 );
930
931 let stored_returned = repository.get(returned_id).await.unwrap();
932 assert!(
933 stored_returned
934 .and_then(|c| c.organization_id)
935 .is_some_and(|id| id == org_id),
936 "the cipher the server returned must be merged and persisted with its new org id"
937 );
938
939 let stored_stripped = repository.get(stripped_id).await.unwrap();
940 assert!(
941 stored_stripped.is_none(),
942 "a cipher omitted from the write-return must be evicted, not left as a stale \
943 pre-share copy"
944 );
945 }
946
947 #[tokio::test]
948 async fn test_share_ciphers_bulk_api_handles_error() {
949 let api_client = ApiClient::new_mocked(|mock| {
950 mock.ciphers_api
951 .expect_put_share_many()
952 .returning(|_body| Err(std::io::Error::other("Server error").into()));
953 });
954
955 let repository = MemoryRepository::<Cipher>::default();
956 let encryption_context = create_encryption_context();
957 let collection_ids: Vec<CollectionId> = vec![TEST_COLLECTION_ID_1.parse().unwrap()];
958
959 let result = share_ciphers_bulk(
960 api_client.ciphers_api(),
961 &repository,
962 vec![encryption_context],
963 collection_ids,
964 )
965 .await;
966
967 assert!(result.is_err());
968 }
969
970 async fn make_test_client_with_wiremock(mock_server: &wiremock::MockServer) -> Client {
971 use bitwarden_core::{
972 ClientSettings, DeviceType, UserId,
973 key_management::crypto::{
974 InitOrgCryptoRequest, InitUserCryptoMethod, InitUserCryptoRequest,
975 },
976 };
977 use bitwarden_crypto::{EncString, Kdf};
978
979 let settings = ClientSettings {
980 identity_url: format!("http://{}", mock_server.address()),
981 api_url: format!("http://{}", mock_server.address()),
982 user_agent: "Bitwarden Test".into(),
983 device_type: DeviceType::SDK,
984 device_identifier: None,
985 bitwarden_client_version: None,
986 bitwarden_package_type: None,
987 };
988
989 let client = Client::new_test(Some(settings));
990
991 let user_request = InitUserCryptoRequest {
992 user_id: Some(UserId::new(uuid::uuid!("060000fb-0922-4dd3-b170-6e15cb5df8c8"))),
993 kdf_params: Kdf::PBKDF2 {
994 iterations: 600_000.try_into().unwrap(),
995 },
996 email: "[email protected]".to_owned(),
997 account_cryptographic_state: WrappedAccountCryptographicState::V1 {
998 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(),
999 },
1000 method: InitUserCryptoMethod::MasterPasswordUnlock {
1001 password: "asdfasdfasdf".to_owned(),
1002 master_password_unlock: MasterPasswordUnlockData {
1003 kdf: Kdf::PBKDF2 {
1004 iterations: 600_000.try_into().unwrap(),
1005 },
1006 master_key_wrapped_user_key: "2.Q/2PhzcC7GdeiMHhWguYAQ==|GpqzVdr0go0ug5cZh1n+uixeBC3oC90CIe0hd/HWA/pTRDZ8ane4fmsEIcuc8eMKUt55Y2q/fbNzsYu41YTZzzsJUSeqVjT8/iTQtgnNdpo=|dwI+uyvZ1h/iZ03VQ+/wrGEFYVewBUUl/syYgjsNMbE=".parse().unwrap(),
1007 salt: "[email protected]".to_owned(),
1008 contained_key_id: None,
1009 },
1010 },
1011 upgrade_token: None,
1012 };
1013
1014 let org_request = InitOrgCryptoRequest {
1015 organization_keys: std::collections::HashMap::from([(
1016 TEST_ORG_ID.parse().unwrap(),
1017 "4.rY01mZFXHOsBAg5Fq4gyXuklWfm6mQASm42DJpx05a+e2mmp+P5W6r54WU2hlREX0uoTxyP91bKKwickSPdCQQ58J45LXHdr9t2uzOYyjVzpzebFcdMw1eElR9W2DW8wEk9+mvtWvKwu7yTebzND+46y1nRMoFydi5zPVLSlJEf81qZZ4Uh1UUMLwXz+NRWfixnGXgq2wRq1bH0n3mqDhayiG4LJKgGdDjWXC8W8MMXDYx24SIJrJu9KiNEMprJE+XVF9nQVNijNAjlWBqkDpsfaWTUfeVLRLctfAqW1blsmIv4RQ91PupYJZDNc8nO9ZTF3TEVM+2KHoxzDJrLs2Q==".parse().unwrap()
1018 )])
1019 };
1020
1021 client
1022 .crypto()
1023 .initialize_user_crypto(user_request)
1024 .await
1025 .unwrap();
1026 client
1027 .crypto()
1028 .initialize_org_crypto(org_request)
1029 .await
1030 .unwrap();
1031
1032 client
1033 }
1034
1035 #[tokio::test]
1036 async fn test_share_cipher_with_password_history() {
1037 use bitwarden_test::start_api_mock;
1038 use wiremock::{
1039 Mock, ResponseTemplate,
1040 matchers::{method, path_regex},
1041 };
1042 let cipher_id: CipherId = TEST_CIPHER_ID.parse().unwrap();
1043 let org_id: OrganizationId = TEST_ORG_ID.parse().unwrap();
1044 let collection_id: CollectionId = TEST_COLLECTION_ID_1.parse().unwrap();
1045
1046 let mut cipher_view = test_cipher_view_without_org();
1047 if let Some(ref mut login) = cipher_view.login {
1048 login.password = Some("original_password_123".to_string());
1049 }
1050
1051 let mock = Mock::given(method("PUT"))
1053 .and(path_regex(r"/ciphers/[a-f0-9-]+/share"))
1054 .and(wiremock::matchers::body_string_contains("passwordHistory"))
1055 .respond_with(move |req: &wiremock::Request| {
1056 let body_bytes = req.body.as_slice();
1057 let request_body: bitwarden_api_api::models::CipherShareRequestModel =
1058 serde_json::from_slice(body_bytes).expect("Failed to parse request body");
1059
1060 let response = CipherResponseModel {
1062 object: Some("cipher".to_string()),
1063 id: Some(cipher_id.into()),
1064 organization_id: Some(
1065 request_body
1066 .cipher
1067 .organization_id
1068 .unwrap()
1069 .parse()
1070 .unwrap(),
1071 ),
1072 r#type: request_body.cipher.r#type,
1073 name: request_body.cipher.name,
1074 notes: request_body.cipher.notes,
1075 login: request_body.cipher.login,
1076 reprompt: request_body.cipher.reprompt,
1077 password_history: request_body.cipher.password_history,
1078 revision_date: Some("2024-01-30T17:55:36.150Z".to_string()),
1079 creation_date: Some("2024-01-30T17:55:36.150Z".to_string()),
1080 edit: Some(true),
1081 view_password: Some(true),
1082 organization_use_totp: Some(true),
1083 favorite: request_body.cipher.favorite,
1084 fields: request_body.cipher.fields,
1085 key: request_body.cipher.key,
1086 ..Default::default()
1087 };
1088
1089 ResponseTemplate::new(200).set_body_json(&response)
1090 });
1091
1092 let (mock_server, _config) = start_api_mock(vec![mock]).await;
1094 let client = make_test_client_with_wiremock(&mock_server).await;
1095 let repository = std::sync::Arc::new(MemoryRepository::<Cipher>::default());
1096 let cipher_client = client.vault().ciphers();
1097 let original = cipher_view.clone();
1098 repository
1099 .set(
1100 TEST_CIPHER_ID.parse().unwrap(),
1101 cipher_client
1102 .encrypt(original.clone())
1103 .await
1104 .unwrap()
1105 .cipher,
1106 )
1107 .await
1108 .unwrap();
1109
1110 client
1111 .platform()
1112 .state()
1113 .register_client_managed(repository.clone());
1114
1115 if let Some(ref mut login) = cipher_view.login {
1117 login.password = Some("new_password_456".to_string());
1118 }
1119
1120 let result = cipher_client
1121 .share_cipher(
1122 cipher_view.clone(),
1123 org_id,
1124 vec![collection_id],
1125 Some(original),
1126 )
1127 .await;
1128
1129 let shared_cipher = result.unwrap();
1130 assert_eq!(shared_cipher.organization_id, Some(org_id));
1131 let history = shared_cipher.password_history.unwrap();
1132 assert_eq!(
1133 history.len(),
1134 1,
1135 "Password history should have 1 entry for the changed password"
1136 );
1137 assert_eq!(
1138 history[0].password, "original_password_123",
1139 "Password history should contain the original password"
1140 );
1141 assert_eq!(
1142 shared_cipher.login.as_ref().unwrap().password,
1143 Some("new_password_456".to_string()),
1144 "New password should be set"
1145 );
1146 }
1147
1148 #[tokio::test]
1149 async fn test_share_ciphers_bulk_with_password_history() {
1150 let org_id: OrganizationId = TEST_ORG_ID.parse().unwrap();
1151 let collection_id: CollectionId = TEST_COLLECTION_ID_1.parse().unwrap();
1152
1153 let mut cipher_view1 = test_cipher_view_without_org();
1154 cipher_view1.id = Some(TEST_CIPHER_ID.parse().unwrap());
1155 if let Some(ref mut login) = cipher_view1.login {
1156 login.password = Some("original_password_1".to_string());
1157 }
1158
1159 let mut cipher_view2 = test_cipher_view_without_org();
1160 cipher_view2.id = Some("11111111-2222-3333-4444-555555555555".parse().unwrap());
1161 if let Some(ref mut login) = cipher_view2.login {
1162 login.password = Some("original_password_2".to_string());
1163 }
1164
1165 let mock = Mock::given(method("PUT"))
1167 .and(path("/ciphers/share"))
1168 .and(wiremock::matchers::body_string_contains("passwordHistory"))
1169 .respond_with(move |req: &wiremock::Request| {
1170 let body_bytes = req.body.as_slice();
1171 let request_body: bitwarden_api_api::models::CipherBulkShareRequestModel =
1172 serde_json::from_slice(body_bytes).expect("Failed to parse request body");
1173
1174 let ciphers: Vec<_> = request_body
1176 .ciphers
1177 .into_iter()
1178 .map(
1179 |cipher| bitwarden_api_api::models::CipherMiniResponseModel {
1180 object: Some("cipherMini".to_string()),
1181 id: Some(cipher.id),
1182 organization_id: cipher.organization_id.and_then(|id| id.parse().ok()),
1183 r#type: cipher.r#type,
1184 name: cipher.name,
1185 notes: cipher.notes,
1186 login: cipher.login,
1187 reprompt: cipher.reprompt,
1188 password_history: cipher.password_history,
1189 revision_date: Some("2024-01-30T17:55:36.150Z".to_string()),
1190 creation_date: Some("2024-01-30T17:55:36.150Z".to_string()),
1191 organization_use_totp: Some(true),
1192 fields: cipher.fields,
1193 key: cipher.key,
1194 ..Default::default()
1195 },
1196 )
1197 .collect();
1198
1199 let response =
1200 bitwarden_api_api::models::CipherMiniResponseModelListResponseModel {
1201 object: Some("list".to_string()),
1202 data: Some(ciphers),
1203 continuation_token: None,
1204 };
1205
1206 ResponseTemplate::new(200).set_body_json(&response)
1207 });
1208
1209 let (mock_server, _config) = start_api_mock(vec![mock]).await;
1211 let client = make_test_client_with_wiremock(&mock_server).await;
1212 let repository = std::sync::Arc::new(MemoryRepository::<Cipher>::default());
1213 let cipher_client = client.vault().ciphers();
1214
1215 let encrypted_original1 = cipher_client.encrypt(cipher_view1.clone()).await.unwrap();
1216 repository
1217 .set(
1218 encrypted_original1.cipher.id.unwrap(),
1219 encrypted_original1.cipher.clone(),
1220 )
1221 .await
1222 .unwrap();
1223
1224 let encrypted_original2 = cipher_client.encrypt(cipher_view2.clone()).await.unwrap();
1225 repository
1226 .set(
1227 encrypted_original2.cipher.id.unwrap(),
1228 encrypted_original2.cipher.clone(),
1229 )
1230 .await
1231 .unwrap();
1232
1233 client
1234 .platform()
1235 .state()
1236 .register_client_managed(repository.clone());
1237
1238 if let Some(ref mut login) = cipher_view1.login {
1240 login.password = Some("new_password_1".to_string());
1241 }
1242 if let Some(ref mut login) = cipher_view2.login {
1243 login.password = Some("new_password_2".to_string());
1244 }
1245
1246 let result = cipher_client
1247 .share_ciphers_bulk(
1248 vec![cipher_view1, cipher_view2],
1249 org_id,
1250 vec![collection_id],
1251 )
1252 .await;
1253
1254 let shared_ciphers = result.unwrap();
1255 assert_eq!(shared_ciphers.len(), 2);
1256
1257 assert_eq!(
1258 shared_ciphers[0].password_history.clone().unwrap()[0].password,
1259 "original_password_1"
1260 );
1261 assert_eq!(
1262 shared_ciphers[0].login.clone().unwrap().password,
1263 Some("new_password_1".to_string())
1264 );
1265
1266 assert_eq!(
1267 shared_ciphers[1].password_history.clone().unwrap()[0].password,
1268 "original_password_2"
1269 );
1270 assert_eq!(
1271 shared_ciphers[1].login.clone().unwrap().password,
1272 Some("new_password_2".to_string())
1273 );
1274 }
1275}