Skip to main content

bitwarden_vault/cipher/cipher_client/admin/
restore.rs

1use bitwarden_api_api::{apis::ApiClient, models::CipherBulkRestoreRequestModel};
2use bitwarden_core::{ApiError, OrganizationId, key_management::KeyIds};
3use bitwarden_crypto::{CryptoError, KeyStore};
4use bitwarden_error::bitwarden_error;
5use thiserror::Error;
6#[cfg(feature = "wasm")]
7use wasm_bindgen::prelude::wasm_bindgen;
8
9use crate::{
10    Cipher, CipherId, CipherView, DecryptCipherListResult, VaultParseError,
11    cipher::cipher::PartialCipher, cipher_client::admin::CipherAdminClient,
12};
13
14#[allow(missing_docs)]
15#[bitwarden_error(flat)]
16#[derive(Debug, Error)]
17pub enum RestoreCipherAdminError {
18    #[error(transparent)]
19    Api(#[from] ApiError),
20    #[error(transparent)]
21    VaultParse(#[from] VaultParseError),
22    #[error(transparent)]
23    Crypto(#[from] CryptoError),
24}
25
26impl<T> From<bitwarden_api_api::apis::Error<T>> for RestoreCipherAdminError {
27    fn from(val: bitwarden_api_api::apis::Error<T>) -> Self {
28        Self::Api(val.into())
29    }
30}
31
32/// Restores a soft-deleted cipher on the server, using the admin endpoint.
33pub async fn restore_as_admin(
34    cipher_id: CipherId,
35    api_client: &ApiClient,
36    key_store: &KeyStore<KeyIds>,
37) -> Result<CipherView, RestoreCipherAdminError> {
38    let api = api_client.ciphers_api();
39
40    let cipher: Cipher = api
41        .put_restore_admin(cipher_id.into())
42        .await?
43        .merge_with_cipher(None)?;
44
45    Ok(key_store.decrypt(&cipher)?)
46}
47
48/// Restores multiple soft-deleted ciphers on the server.
49pub async fn restore_many_as_admin(
50    cipher_ids: Vec<CipherId>,
51    org_id: OrganizationId,
52    api_client: &ApiClient,
53    key_store: &KeyStore<KeyIds>,
54) -> Result<DecryptCipherListResult, RestoreCipherAdminError> {
55    let api = api_client.ciphers_api();
56
57    let ciphers: Vec<Cipher> = api
58        .put_restore_many_admin(Some(CipherBulkRestoreRequestModel {
59            ids: cipher_ids.into_iter().map(|id| id.to_string()).collect(),
60            organization_id: Some(org_id.into()),
61        }))
62        .await?
63        .data
64        .into_iter()
65        .flatten()
66        .map(|c| c.merge_with_cipher(None))
67        .collect::<Result<Vec<_>, _>>()?;
68
69    let (successes, failures) = key_store.decrypt_list_with_failures(&ciphers);
70    Ok(DecryptCipherListResult {
71        successes,
72        failures: failures.into_iter().cloned().collect(),
73    })
74}
75
76#[cfg_attr(feature = "wasm", wasm_bindgen)]
77impl CipherAdminClient {
78    /// Restores a soft-deleted cipher on the server, using the admin endpoint.
79    pub async fn restore(
80        &self,
81        cipher_id: CipherId,
82    ) -> Result<CipherView, RestoreCipherAdminError> {
83        let api_client = &self.client.internal.get_api_configurations().api_client;
84        let key_store = self.client.internal.get_key_store();
85
86        restore_as_admin(cipher_id, api_client, key_store).await
87    }
88    /// Restores multiple soft-deleted ciphers on the server.
89    pub async fn restore_many(
90        &self,
91        cipher_ids: Vec<CipherId>,
92        org_id: OrganizationId,
93    ) -> Result<DecryptCipherListResult, RestoreCipherAdminError> {
94        let api_client = &self.client.internal.get_api_configurations().api_client;
95        let key_store = self.client.internal.get_key_store();
96
97        restore_many_as_admin(cipher_ids, org_id, api_client, key_store).await
98    }
99}
100
101#[cfg(test)]
102mod tests {
103    use bitwarden_api_api::{
104        apis::ApiClient,
105        models::{CipherMiniResponseModel, CipherMiniResponseModelListResponseModel},
106    };
107    use bitwarden_core::key_management::{KeyIds, SymmetricKeyId};
108    use bitwarden_crypto::{KeyStore, PrimitiveEncryptable, SymmetricCryptoKey};
109    use chrono::Utc;
110
111    use super::*;
112    use crate::{Cipher, CipherId, Login};
113
114    const TEST_CIPHER_ID: &str = "5faa9684-c793-4a2d-8a12-b33900187097";
115    const TEST_CIPHER_ID_2: &str = "6faa9684-c793-4a2d-8a12-b33900187098";
116    const TEST_ORG_ID: &str = "1bc9ac1e-f5aa-45f2-94bf-b181009709b8";
117
118    fn setup_key_store() -> KeyStore<KeyIds> {
119        let store: KeyStore<KeyIds> = KeyStore::default();
120        #[allow(deprecated)]
121        let _ = store.context_mut().set_symmetric_key(
122            SymmetricKeyId::User,
123            SymmetricCryptoKey::make_aes256_cbc_hmac_key(),
124        );
125        store
126    }
127
128    fn generate_test_cipher(store: &KeyStore<KeyIds>) -> Cipher {
129        let mut ctx = store.context();
130        Cipher {
131            id: TEST_CIPHER_ID.parse().ok(),
132            name: "Test cipher"
133                .encrypt(&mut ctx, SymmetricKeyId::User)
134                .unwrap(),
135            r#type: crate::CipherType::Login,
136            notes: Default::default(),
137            organization_id: Default::default(),
138            folder_id: Default::default(),
139            favorite: Default::default(),
140            reprompt: Default::default(),
141            fields: Default::default(),
142            collection_ids: Default::default(),
143            key: Default::default(),
144            login: Some(Login {
145                username: None,
146                password: None,
147                password_revision_date: None,
148                uris: None,
149                totp: None,
150                autofill_on_page_load: None,
151                fido2_credentials: None,
152            }),
153            identity: Default::default(),
154            card: Default::default(),
155            secure_note: Default::default(),
156            ssh_key: Default::default(),
157            organization_use_totp: Default::default(),
158            edit: Default::default(),
159            permissions: Default::default(),
160            view_password: Default::default(),
161            local_data: Default::default(),
162            attachments: Default::default(),
163            password_history: Default::default(),
164            creation_date: Default::default(),
165            deleted_date: Default::default(),
166            revision_date: Default::default(),
167            archived_date: Default::default(),
168            data: Default::default(),
169        }
170    }
171
172    #[tokio::test]
173    async fn test_restore_as_admin() {
174        let store = setup_key_store();
175        let mut cipher = generate_test_cipher(&store);
176        cipher.deleted_date = Some(Utc::now());
177
178        let api_client = {
179            let cipher = cipher.clone();
180            ApiClient::new_mocked(move |mock| {
181                mock.ciphers_api
182                    .expect_put_restore_admin()
183                    .returning(move |_model| {
184                        Ok(CipherMiniResponseModel {
185                            id: Some(TEST_CIPHER_ID.try_into().unwrap()),
186                            name: Some(cipher.name.to_string()),
187                            r#type: Some(cipher.r#type.into()),
188                            creation_date: Some(cipher.creation_date.to_string()),
189                            revision_date: Some(Utc::now().to_rfc3339()),
190                            login: cipher.login.clone().map(|l| Box::new(l.into())),
191                            ..Default::default()
192                        })
193                    });
194            })
195        };
196
197        let start_time = Utc::now();
198        let updated_cipher = restore_as_admin(TEST_CIPHER_ID.parse().unwrap(), &api_client, &store)
199            .await
200            .unwrap();
201        let end_time = Utc::now();
202
203        assert!(updated_cipher.deleted_date.is_none());
204        assert!(
205            updated_cipher.revision_date >= start_time && updated_cipher.revision_date <= end_time
206        );
207    }
208
209    #[tokio::test]
210    async fn test_restore_many_as_admin() {
211        let store = setup_key_store();
212        let cipher_id_2: CipherId = TEST_CIPHER_ID_2.parse().unwrap();
213        let mut cipher_1 = generate_test_cipher(&store);
214        cipher_1.deleted_date = Some(Utc::now());
215        let mut cipher_2 = generate_test_cipher(&store);
216        cipher_2.deleted_date = Some(Utc::now());
217        cipher_2.id = Some(cipher_id_2);
218
219        let api_client = ApiClient::new_mocked(move |mock| {
220            mock.ciphers_api
221                .expect_put_restore_many_admin()
222                .returning(move |_model| {
223                    Ok(CipherMiniResponseModelListResponseModel {
224                        object: None,
225                        data: Some(vec![
226                            CipherMiniResponseModel {
227                                id: cipher_1.id.map(|id| id.into()),
228                                name: Some(cipher_1.name.to_string()),
229                                r#type: Some(cipher_1.r#type.into()),
230                                login: cipher_1.login.clone().map(|l| Box::new(l.into())),
231                                creation_date: cipher_1.creation_date.to_string().into(),
232                                deleted_date: None,
233                                revision_date: Some(Utc::now().to_rfc3339()),
234                                ..Default::default()
235                            },
236                            CipherMiniResponseModel {
237                                id: cipher_2.id.map(|id| id.into()),
238                                name: Some(cipher_2.name.to_string()),
239                                r#type: Some(cipher_2.r#type.into()),
240                                login: cipher_2.login.clone().map(|l| Box::new(l.into())),
241                                creation_date: cipher_2.creation_date.to_string().into(),
242                                deleted_date: None,
243                                revision_date: Some(Utc::now().to_rfc3339()),
244                                ..Default::default()
245                            },
246                        ]),
247                        continuation_token: None,
248                    })
249                });
250        });
251
252        let start_time = Utc::now();
253        let ciphers = restore_many_as_admin(
254            vec![
255                TEST_CIPHER_ID.parse().unwrap(),
256                TEST_CIPHER_ID_2.parse().unwrap(),
257            ],
258            TEST_ORG_ID.parse().unwrap(),
259            &api_client,
260            &store,
261        )
262        .await
263        .unwrap();
264        let end_time = Utc::now();
265
266        assert_eq!(ciphers.successes.len(), 2,);
267        assert_eq!(ciphers.failures.len(), 0,);
268        assert_eq!(
269            ciphers.successes[0].id,
270            Some(TEST_CIPHER_ID.parse().unwrap()),
271        );
272        assert_eq!(
273            ciphers.successes[1].id,
274            Some(TEST_CIPHER_ID_2.parse().unwrap()),
275        );
276        assert_eq!(ciphers.successes[0].deleted_date, None,);
277        assert_eq!(ciphers.successes[1].deleted_date, None,);
278
279        assert!(
280            ciphers.successes[0].revision_date >= start_time
281                && ciphers.successes[0].revision_date <= end_time
282        );
283        assert!(
284            ciphers.successes[1].revision_date >= start_time
285                && ciphers.successes[1].revision_date <= end_time
286        );
287    }
288}