Skip to main content

bitwarden_vault/cipher/cipher_client/admin/
get.rs

1use bitwarden_api_api::models::CipherMiniDetailsResponseModelListResponseModel;
2use bitwarden_core::{ApiError, OrganizationId, key_management::KeySlotIds};
3use bitwarden_crypto::KeyStore;
4use bitwarden_error::bitwarden_error;
5use thiserror::Error;
6
7use crate::{
8    Cipher, VaultParseError,
9    cipher::cipher::{
10        DecryptCipherResult, ListOrganizationCiphersResult, PartialCipher, StrictDecrypt,
11    },
12    cipher_client::admin::CipherAdminClient,
13};
14
15#[allow(missing_docs)]
16#[bitwarden_error(flat)]
17#[derive(Debug, Error)]
18pub enum GetAssignedOrgCiphersAdminError {
19    #[error(transparent)]
20    Api(#[from] ApiError),
21    #[error(transparent)]
22    VaultParse(#[from] VaultParseError),
23}
24
25#[allow(missing_docs)]
26#[bitwarden_error(flat)]
27#[derive(Debug, Error)]
28pub enum GetOrganizationCiphersAdminError {
29    #[error(transparent)]
30    VaultParse(#[from] VaultParseError),
31    #[error(transparent)]
32    Api(#[from] ApiError),
33}
34
35/// Get all ciphers for an organization.
36pub async fn list_org_ciphers(
37    org_id: OrganizationId,
38    include_member_items: bool,
39    api_client: &bitwarden_api_api::apis::ApiClient,
40    key_store: &KeyStore<KeySlotIds>,
41    use_strict_decryption: bool,
42) -> Result<ListOrganizationCiphersResult, GetOrganizationCiphersAdminError> {
43    let api = api_client.ciphers_api();
44    let response: CipherMiniDetailsResponseModelListResponseModel = api
45        .get_organization_ciphers(Some(org_id.into()), Some(include_member_items))
46        .await?;
47    let ciphers = response
48        .data
49        .into_iter()
50        .flatten()
51        .map(|model| model.merge_with_cipher(None))
52        .collect::<Result<Vec<_>, _>>()?;
53
54    let list_views = if use_strict_decryption {
55        let wrapped: Vec<StrictDecrypt<Cipher>> =
56            ciphers.iter().cloned().map(StrictDecrypt).collect();
57        let (list_views, _failures) = key_store.decrypt_list_with_failures(&wrapped);
58        list_views
59    } else {
60        let (list_views, _failures) = key_store.decrypt_list_with_failures(&ciphers);
61        list_views
62    };
63    Ok(ListOrganizationCiphersResult {
64        ciphers,
65        list_views,
66    })
67}
68
69/// Get all Login ciphers for an organization, decrypted to full [crate::CipherView].
70pub async fn list_org_login_ciphers(
71    org_id: OrganizationId,
72    api_client: &bitwarden_api_api::apis::ApiClient,
73    key_store: &KeyStore<KeySlotIds>,
74    use_strict_decryption: bool,
75) -> Result<DecryptCipherResult, GetOrganizationCiphersAdminError> {
76    let response: CipherMiniDetailsResponseModelListResponseModel = api_client
77        .ciphers_api()
78        .get_organization_login_ciphers(Some(org_id.into()))
79        .await?;
80    let ciphers = response
81        .data
82        .into_iter()
83        .flatten()
84        .map(|model| model.merge_with_cipher(None))
85        .collect::<Result<Vec<_>, _>>()?;
86
87    Ok(if use_strict_decryption {
88        let wrapped: Vec<StrictDecrypt<Cipher>> = ciphers.into_iter().map(StrictDecrypt).collect();
89        let (successes, failures) = key_store.decrypt_list_with_failures(&wrapped);
90        DecryptCipherResult {
91            successes,
92            failures: failures.into_iter().map(|f| f.0.clone()).collect(),
93        }
94    } else {
95        let (successes, failures) = key_store.decrypt_list_with_failures(&ciphers);
96        DecryptCipherResult {
97            successes,
98            failures: failures.into_iter().cloned().collect(),
99        }
100    })
101}
102
103#[bitwarden_ffi::wasm_export]
104impl CipherAdminClient {
105    /// Fetches and decrypts all ciphers assigned to the current user for an organization.
106    pub async fn list_assigned_org_ciphers(
107        &self,
108        org_id: OrganizationId,
109    ) -> Result<ListOrganizationCiphersResult, GetAssignedOrgCiphersAdminError> {
110        use bitwarden_api_api::models::CipherDetailsResponseModelListResponseModel;
111
112        let response: CipherDetailsResponseModelListResponseModel = self
113            .api_configurations
114            .api_client
115            .ciphers_api()
116            .get_assigned_organization_ciphers(Some(org_id.into()))
117            .await?;
118
119        let ciphers = response
120            .data
121            .into_iter()
122            .flatten()
123            .map(|model| model.merge_with_cipher(None))
124            .collect::<Result<Vec<_>, _>>()?;
125
126        let list_views = if self.is_strict_decrypt().await {
127            let wrapped: Vec<StrictDecrypt<Cipher>> =
128                ciphers.iter().cloned().map(StrictDecrypt).collect();
129            let (list_views, _failures) = self.key_store.decrypt_list_with_failures(&wrapped);
130            list_views
131        } else {
132            let (list_views, _failures) = self.key_store.decrypt_list_with_failures(&ciphers);
133            list_views
134        };
135        Ok(ListOrganizationCiphersResult {
136            ciphers,
137            list_views,
138        })
139    }
140
141    /// Get all ciphers for an organization.
142    pub async fn list_org_ciphers(
143        &self,
144        org_id: OrganizationId,
145        include_member_items: bool,
146    ) -> Result<ListOrganizationCiphersResult, GetOrganizationCiphersAdminError> {
147        list_org_ciphers(
148            org_id,
149            include_member_items,
150            &self.api_configurations.api_client,
151            &self.key_store,
152            self.is_strict_decrypt().await,
153        )
154        .await
155    }
156
157    /// Fetches all Login ciphers for an organization and decrypts them to full [crate::CipherView].
158    pub async fn list_org_login_ciphers(
159        &self,
160        org_id: OrganizationId,
161    ) -> Result<DecryptCipherResult, GetOrganizationCiphersAdminError> {
162        list_org_login_ciphers(
163            org_id,
164            &self.api_configurations.api_client,
165            &self.key_store,
166            self.is_strict_decrypt().await,
167        )
168        .await
169    }
170}
171
172#[cfg(test)]
173mod tests {
174    use std::sync::Arc;
175
176    use bitwarden_api_api::{
177        apis::ApiClient,
178        models::{
179            CipherDetailsResponseModel, CipherDetailsResponseModelListResponseModel,
180            CipherMiniDetailsResponseModel, CipherMiniDetailsResponseModelListResponseModel,
181        },
182    };
183    use bitwarden_core::{
184        client::ApiConfigurations, key_management::create_test_crypto_with_user_key,
185    };
186    use bitwarden_crypto::{SymmetricCryptoKey, SymmetricKeyAlgorithm};
187    use chrono::Utc;
188
189    use super::*;
190    use crate::{Cipher, CipherType, Login};
191
192    const TEST_ORG_ID: &str = "1bc9ac1e-f5aa-45f2-94bf-b181009709b8";
193    const TEST_CIPHER_ID_1: &str = "5faa9684-c793-4a2d-8a12-b33900187097";
194    const TEST_CIPHER_ID_2: &str = "6faa9684-c793-4a2d-8a12-b33900187098";
195
196    fn create_test_client(api_client: ApiClient) -> CipherAdminClient {
197        #[allow(deprecated)]
198        CipherAdminClient {
199            key_store: create_test_crypto_with_user_key(SymmetricCryptoKey::make(
200                SymmetricKeyAlgorithm::Aes256CbcHmac,
201            )),
202            api_configurations: Arc::new(ApiConfigurations::from_api_client(api_client)),
203            client: bitwarden_core::Client::new_test(None),
204        }
205    }
206
207    fn mock_mini_cipher(cipher_id: &str) -> CipherMiniDetailsResponseModel {
208        let cipher = generate_test_cipher();
209        CipherMiniDetailsResponseModel {
210            id: cipher_id.parse().ok(),
211            name: cipher.name.as_ref().map(ToString::to_string),
212            r#type: Some(cipher.r#type.into()),
213            login: cipher.login.clone().map(|l| Box::new(l.into())),
214            creation_date: Some(Utc::now().to_rfc3339()),
215            revision_date: Some(Utc::now().to_rfc3339()),
216            ..Default::default()
217        }
218    }
219
220    fn mock_details_cipher(cipher_id: &str) -> CipherDetailsResponseModel {
221        CipherDetailsResponseModel {
222            id: Some(cipher_id.parse().unwrap()),
223            name: Some("2.pMS6/icTQABtulw52pq2lg==|XXbxKxDTh+mWiN1HjH2N1w==|Q6PkuT+KX/axrgN9ubD5Ajk2YNwxQkgs3WJM0S0wtG8=".to_string()),
224            r#type: Some(bitwarden_api_api::models::CipherType::Login),
225            login: Some(Box::new(bitwarden_api_api::models::CipherLoginModel::default())),
226            creation_date: Some(Utc::now().to_rfc3339()),
227            revision_date: Some(Utc::now().to_rfc3339()),
228            ..Default::default()
229        }
230    }
231
232    fn generate_test_cipher() -> Cipher {
233        Cipher {
234            partial_data: None,
235            id: TEST_CIPHER_ID_1.parse().ok(),
236            name: Some("2.pMS6/icTQABtulw52pq2lg==|XXbxKxDTh+mWiN1HjH2N1w==|Q6PkuT+KX/axrgN9ubD5Ajk2YNwxQkgs3WJM0S0wtG8=".parse().unwrap()),
237            r#type: CipherType::Login,
238            notes: Default::default(),
239            organization_id: Default::default(),
240            folder_id: Default::default(),
241            favorite: Default::default(),
242            reprompt: Default::default(),
243            fields: Default::default(),
244            collection_ids: Default::default(),
245            key: Default::default(),
246            login: Some(Login {
247                username: None,
248                password: None,
249                password_revision_date: None,
250                uris: None,
251                totp: None,
252                autofill_on_page_load: None,
253                http_authentication_enabled: None,
254                fido2_credentials: None,
255            }),
256            identity: Default::default(),
257            card: Default::default(),
258            secure_note: Default::default(),
259            ssh_key: Default::default(),
260            bank_account: Default::default(),
261            drivers_license: Default::default(),
262            passport: Default::default(),
263            organization_use_totp: Default::default(),
264            edit: Default::default(),
265            permissions: Default::default(),
266            view_password: Default::default(),
267            local_data: Default::default(),
268            attachments: Default::default(),
269            password_history: Default::default(),
270            creation_date: Default::default(),
271            deleted_date: Default::default(),
272            revision_date: Default::default(),
273            archived_date: Default::default(),
274            data: Default::default(),
275        }
276    }
277
278    #[tokio::test]
279    async fn test_list_org_ciphers_all_success() {
280        let api_client = ApiClient::new_mocked(move |mock| {
281            mock.ciphers_api
282                .expect_get_organization_ciphers()
283                .returning(move |_org_id, _include_member_items| {
284                    Ok(CipherMiniDetailsResponseModelListResponseModel {
285                        object: None,
286                        data: Some(vec![
287                            mock_mini_cipher(TEST_CIPHER_ID_1),
288                            mock_mini_cipher(TEST_CIPHER_ID_2),
289                        ]),
290                        continuation_token: None,
291                    })
292                });
293        });
294
295        let client = create_test_client(api_client);
296        let result = client
297            .list_org_ciphers(TEST_ORG_ID.parse().unwrap(), true)
298            .await
299            .unwrap();
300
301        assert_eq!(result.ciphers.len(), 2);
302        assert_eq!(result.list_views.len(), 2);
303        assert_eq!(result.ciphers[0].id, TEST_CIPHER_ID_1.parse().ok());
304        assert_eq!(result.ciphers[1].id, TEST_CIPHER_ID_2.parse().ok());
305    }
306
307    #[tokio::test]
308    async fn test_list_org_ciphers_with_failures() {
309        let api_client = ApiClient::new_mocked(move |mock| {
310            mock.ciphers_api
311                .expect_get_organization_ciphers()
312                .returning(move |_org_id, _include_member_items| {
313                    let mut bad = mock_mini_cipher(TEST_CIPHER_ID_2);
314                    bad.key = Some("2.Gg8yCM4IIgykCZyq0O4+cA==|GJLBtfvSJTDJh/F7X4cJPkzI6ccnzJm5DYl3yxOW2iUn7DgkkmzoOe61sUhC5dgVdV0kFqsZPcQ0yehlN1DDsFIFtrb4x7LwzJNIkMgxNyg=|1rGkGJ8zcM5o5D0aIIwAyLsjMLrPsP3EWm3CctBO3Fw=".to_string());
315                    Ok(CipherMiniDetailsResponseModelListResponseModel {
316                        object: None,
317                        data: Some(vec![mock_mini_cipher(TEST_CIPHER_ID_1), bad]),
318                        continuation_token: None,
319                    })
320                });
321        });
322
323        let client = create_test_client(api_client);
324        let result = client
325            .list_org_ciphers(TEST_ORG_ID.parse().unwrap(), true)
326            .await
327            .unwrap();
328
329        assert_eq!(result.ciphers.len(), 2);
330        assert_eq!(result.list_views.len(), 1);
331    }
332
333    #[tokio::test]
334    async fn test_list_org_ciphers_empty() {
335        let api_client = ApiClient::new_mocked(move |mock| {
336            mock.ciphers_api
337                .expect_get_organization_ciphers()
338                .returning(move |_org_id, _include_member_items| {
339                    Ok(CipherMiniDetailsResponseModelListResponseModel {
340                        object: None,
341                        data: Some(vec![]),
342                        continuation_token: None,
343                    })
344                });
345        });
346
347        let client = create_test_client(api_client);
348        let result = client
349            .list_org_ciphers(TEST_ORG_ID.parse().unwrap(), false)
350            .await
351            .unwrap();
352
353        assert!(result.ciphers.is_empty());
354        assert!(result.list_views.is_empty());
355    }
356
357    #[tokio::test]
358    async fn test_list_org_login_ciphers_all_success() {
359        let api_client = ApiClient::new_mocked(move |mock| {
360            mock.ciphers_api
361                .expect_get_organization_login_ciphers()
362                .withf(|org_id| *org_id == TEST_ORG_ID.parse().ok())
363                .returning(move |_org_id| {
364                    Ok(CipherMiniDetailsResponseModelListResponseModel {
365                        object: None,
366                        data: Some(vec![
367                            mock_mini_cipher(TEST_CIPHER_ID_1),
368                            mock_mini_cipher(TEST_CIPHER_ID_2),
369                        ]),
370                        continuation_token: None,
371                    })
372                });
373        });
374
375        let client = create_test_client(api_client);
376        let result = client
377            .list_org_login_ciphers(TEST_ORG_ID.parse().unwrap())
378            .await
379            .unwrap();
380
381        assert_eq!(result.successes.len(), 2);
382        assert!(result.failures.is_empty());
383        assert_eq!(result.successes[0].id, TEST_CIPHER_ID_1.parse().ok());
384        assert_eq!(result.successes[1].id, TEST_CIPHER_ID_2.parse().ok());
385        assert!(result.successes[0].login.is_some());
386    }
387
388    #[tokio::test]
389    async fn test_list_org_login_ciphers_with_failures() {
390        let api_client = ApiClient::new_mocked(move |mock| {
391            mock.ciphers_api
392                .expect_get_organization_login_ciphers()
393                .returning(move |_org_id| {
394                    let mut bad = mock_mini_cipher(TEST_CIPHER_ID_2);
395                    bad.key = Some("2.Gg8yCM4IIgykCZyq0O4+cA==|GJLBtfvSJTDJh/F7X4cJPkzI6ccnzJm5DYl3yxOW2iUn7DgkkmzoOe61sUhC5dgVdV0kFqsZPcQ0yehlN1DDsFIFtrb4x7LwzJNIkMgxNyg=|1rGkGJ8zcM5o5D0aIIwAyLsjMLrPsP3EWm3CctBO3Fw=".to_string());
396                    Ok(CipherMiniDetailsResponseModelListResponseModel {
397                        object: None,
398                        data: Some(vec![mock_mini_cipher(TEST_CIPHER_ID_1), bad]),
399                        continuation_token: None,
400                    })
401                });
402        });
403
404        let client = create_test_client(api_client);
405        let result = client
406            .list_org_login_ciphers(TEST_ORG_ID.parse().unwrap())
407            .await
408            .unwrap();
409
410        assert_eq!(result.successes.len(), 1);
411        assert_eq!(result.successes[0].id, TEST_CIPHER_ID_1.parse().ok());
412        assert_eq!(result.failures.len(), 1);
413        assert_eq!(result.failures[0].id, TEST_CIPHER_ID_2.parse().ok());
414    }
415
416    #[tokio::test]
417    async fn test_list_org_login_ciphers_empty() {
418        let api_client = ApiClient::new_mocked(move |mock| {
419            mock.ciphers_api
420                .expect_get_organization_login_ciphers()
421                .returning(move |_org_id| {
422                    Ok(CipherMiniDetailsResponseModelListResponseModel {
423                        object: None,
424                        data: None,
425                        continuation_token: None,
426                    })
427                });
428        });
429
430        let client = create_test_client(api_client);
431        let result = client
432            .list_org_login_ciphers(TEST_ORG_ID.parse().unwrap())
433            .await
434            .unwrap();
435
436        assert!(result.successes.is_empty());
437        assert!(result.failures.is_empty());
438    }
439
440    #[tokio::test]
441    async fn test_list_assigned_org_ciphers_success() {
442        let api_client = ApiClient::new_mocked(|mock| {
443            mock.ciphers_api
444                .expect_get_assigned_organization_ciphers()
445                .returning(|_| {
446                    Ok(CipherDetailsResponseModelListResponseModel {
447                        object: None,
448                        data: Some(vec![
449                            mock_details_cipher(TEST_CIPHER_ID_1),
450                            mock_details_cipher(TEST_CIPHER_ID_2),
451                        ]),
452                        continuation_token: None,
453                    })
454                });
455        });
456
457        let client = create_test_client(api_client);
458        let result = client
459            .list_assigned_org_ciphers(TEST_ORG_ID.parse().unwrap())
460            .await
461            .unwrap();
462
463        assert_eq!(result.ciphers.len(), 2);
464        assert_eq!(result.list_views.len(), 2);
465    }
466
467    #[tokio::test]
468    async fn test_list_assigned_org_ciphers_with_failures() {
469        let api_client = ApiClient::new_mocked(|mock| {
470            mock.ciphers_api
471                .expect_get_assigned_organization_ciphers()
472                .returning(|_| {
473                    let mut bad = mock_details_cipher(TEST_CIPHER_ID_2);
474                    bad.key = Some("2.Gg8yCM4IIgykCZyq0O4+cA==|GJLBtfvSJTDJh/F7X4cJPkzI6ccnzJm5DYl3yxOW2iUn7DgkkmzoOe61sUhC5dgVdV0kFqsZPcQ0yehlN1DDsFIFtrb4x7LwzJNIkMgxNyg=|1rGkGJ8zcM5o5D0aIIwAyLsjMLrPsP3EWm3CctBO3Fw=".to_string());
475                    Ok(CipherDetailsResponseModelListResponseModel {
476                        object: None,
477                        data: Some(vec![mock_details_cipher(TEST_CIPHER_ID_1), bad]),
478                        continuation_token: None,
479                    })
480                });
481        });
482
483        let client = create_test_client(api_client);
484        let result = client
485            .list_assigned_org_ciphers(TEST_ORG_ID.parse().unwrap())
486            .await
487            .unwrap();
488
489        assert_eq!(result.ciphers.len(), 2);
490        assert_eq!(result.list_views.len(), 1);
491        assert_eq!(result.list_views[0].id, TEST_CIPHER_ID_1.parse().ok());
492    }
493
494    #[tokio::test]
495    async fn test_list_assigned_org_ciphers_empty() {
496        let api_client = ApiClient::new_mocked(|mock| {
497            mock.ciphers_api
498                .expect_get_assigned_organization_ciphers()
499                .returning(|_| {
500                    Ok(CipherDetailsResponseModelListResponseModel {
501                        object: None,
502                        data: Some(vec![]),
503                        continuation_token: None,
504                    })
505                });
506        });
507
508        let client = create_test_client(api_client);
509        let result = client
510            .list_assigned_org_ciphers(TEST_ORG_ID.parse().unwrap())
511            .await
512            .unwrap();
513
514        assert!(result.ciphers.is_empty());
515        assert!(result.list_views.is_empty());
516    }
517}