Skip to main content

bitwarden_vault/cipher/cipher_client/
delete.rs

1use bitwarden_api_api::models::CipherBulkDeleteRequestModel;
2use bitwarden_core::{ApiError, OrganizationId};
3use bitwarden_error::bitwarden_error;
4use bitwarden_state::repository::{Repository, RepositoryError};
5use thiserror::Error;
6#[cfg(feature = "wasm")]
7use wasm_bindgen::prelude::wasm_bindgen;
8
9use crate::{Cipher, CipherId, CiphersClient};
10
11#[allow(missing_docs)]
12#[bitwarden_error(flat)]
13#[derive(Debug, Error)]
14pub enum DeleteCipherError {
15    #[error(transparent)]
16    Api(#[from] ApiError),
17    #[error(transparent)]
18    Repository(#[from] RepositoryError),
19}
20
21impl<T> From<bitwarden_api_api::apis::Error<T>> for DeleteCipherError {
22    fn from(value: bitwarden_api_api::apis::Error<T>) -> Self {
23        Self::Api(value.into())
24    }
25}
26
27async fn delete_cipher<R: Repository<Cipher> + ?Sized>(
28    cipher_id: CipherId,
29    api_client: &bitwarden_api_api::apis::ApiClient,
30    repository: &R,
31) -> Result<(), DeleteCipherError> {
32    let api = api_client.ciphers_api();
33    api.delete(cipher_id.into()).await?;
34    repository.remove(cipher_id).await?;
35    Ok(())
36}
37
38async fn delete_ciphers<R: Repository<Cipher> + ?Sized>(
39    cipher_ids: Vec<CipherId>,
40    organization_id: Option<OrganizationId>,
41    api_client: &bitwarden_api_api::apis::ApiClient,
42    repository: &R,
43) -> Result<(), DeleteCipherError> {
44    let api = api_client.ciphers_api();
45
46    api.delete_many(Some(CipherBulkDeleteRequestModel {
47        ids: cipher_ids.iter().map(|id| id.to_string()).collect(),
48        organization_id: organization_id.map(|id| id.to_string()),
49    }))
50    .await?;
51
52    for cipher_id in cipher_ids {
53        repository.remove(cipher_id).await?;
54    }
55    Ok(())
56}
57
58async fn soft_delete<R: Repository<Cipher> + ?Sized>(
59    cipher_id: CipherId,
60    api_client: &bitwarden_api_api::apis::ApiClient,
61    repository: &R,
62) -> Result<(), DeleteCipherError> {
63    let api = api_client.ciphers_api();
64    api.put_delete(cipher_id.into()).await?;
65    process_soft_delete(repository, cipher_id).await?;
66    Ok(())
67}
68
69async fn soft_delete_many<R: Repository<Cipher> + ?Sized>(
70    cipher_ids: Vec<CipherId>,
71    organization_id: Option<OrganizationId>,
72    api_client: &bitwarden_api_api::apis::ApiClient,
73    repository: &R,
74) -> Result<(), DeleteCipherError> {
75    let api = api_client.ciphers_api();
76
77    api.put_delete_many(Some(CipherBulkDeleteRequestModel {
78        ids: cipher_ids.iter().map(|id| id.to_string()).collect(),
79        organization_id: organization_id.map(|id| id.to_string()),
80    }))
81    .await?;
82    for cipher_id in cipher_ids {
83        process_soft_delete(repository, cipher_id).await?;
84    }
85    Ok(())
86}
87
88async fn process_soft_delete<R: Repository<Cipher> + ?Sized>(
89    repository: &R,
90    cipher_id: CipherId,
91) -> Result<(), RepositoryError> {
92    let cipher: Option<Cipher> = repository.get(cipher_id).await?;
93    if let Some(mut cipher) = cipher {
94        cipher.soft_delete();
95        repository.set(cipher_id, cipher).await?;
96    }
97    Ok(())
98}
99
100#[cfg_attr(feature = "wasm", wasm_bindgen)]
101impl CiphersClient {
102    /// Deletes the [Cipher] with the matching [CipherId] from the server.
103    pub async fn delete(&self, cipher_id: CipherId) -> Result<(), DeleteCipherError> {
104        let configs = self.client.internal.get_api_configurations();
105        delete_cipher(cipher_id, &configs.api_client, &*self.get_repository()?).await
106    }
107
108    /// Deletes all [Cipher] objects with a matching [CipherId] from the server.
109    pub async fn delete_many(
110        &self,
111        cipher_ids: Vec<CipherId>,
112        organization_id: Option<OrganizationId>,
113    ) -> Result<(), DeleteCipherError> {
114        let configs = self.client.internal.get_api_configurations();
115        delete_ciphers(
116            cipher_ids,
117            organization_id,
118            &configs.api_client,
119            &*self.get_repository()?,
120        )
121        .await
122    }
123
124    /// Soft-deletes the [Cipher] with the matching [CipherId] from the server.
125    pub async fn soft_delete(&self, cipher_id: CipherId) -> Result<(), DeleteCipherError> {
126        let configs = self.client.internal.get_api_configurations();
127        soft_delete(cipher_id, &configs.api_client, &*self.get_repository()?).await
128    }
129
130    /// Soft-deletes all [Cipher] objects for the given [CipherId]s from the server.
131    pub async fn soft_delete_many(
132        &self,
133        cipher_ids: Vec<CipherId>,
134        organization_id: Option<OrganizationId>,
135    ) -> Result<(), DeleteCipherError> {
136        soft_delete_many(
137            cipher_ids,
138            organization_id,
139            &self.client.internal.get_api_configurations().api_client,
140            &*self.get_repository()?,
141        )
142        .await
143    }
144}
145
146#[cfg(test)]
147mod tests {
148    use bitwarden_api_api::apis::ApiClient;
149    use bitwarden_state::repository::Repository;
150    use bitwarden_test::MemoryRepository;
151    use chrono::Utc;
152
153    use crate::{
154        Cipher, CipherId,
155        cipher_client::delete::{delete_cipher, delete_ciphers, soft_delete, soft_delete_many},
156    };
157
158    const TEST_CIPHER_ID: &str = "5faa9684-c793-4a2d-8a12-b33900187097";
159    const TEST_CIPHER_ID_2: &str = "6faa9684-c793-4a2d-8a12-b33900187098";
160
161    fn generate_test_cipher() -> Cipher {
162        Cipher {
163            id: TEST_CIPHER_ID.parse().ok(),
164            name: "2.pMS6/icTQABtulw52pq2lg==|XXbxKxDTh+mWiN1HjH2N1w==|Q6PkuT+KX/axrgN9ubD5Ajk2YNwxQkgs3WJM0S0wtG8=".parse().unwrap(),
165            r#type: crate::CipherType::Login,
166            notes: Default::default(),
167            organization_id: Default::default(),
168            folder_id: Default::default(),
169            favorite: Default::default(),
170            reprompt: Default::default(),
171            fields: Default::default(),
172            collection_ids: Default::default(),
173            key: Default::default(),
174            login: Default::default(),
175            identity: Default::default(),
176            card: Default::default(),
177            secure_note: Default::default(),
178            ssh_key: Default::default(),
179            bank_account: Default::default(),
180            organization_use_totp: Default::default(),
181            edit: Default::default(),
182            permissions: Default::default(),
183            view_password: Default::default(),
184            local_data: Default::default(),
185            attachments: Default::default(),
186            password_history: Default::default(),
187            creation_date: Default::default(),
188            deleted_date: Default::default(),
189            revision_date: Default::default(),
190            archived_date: Default::default(),
191            data: Default::default(),
192        }
193    }
194
195    #[tokio::test]
196    async fn test_delete() {
197        let api_client = ApiClient::new_mocked(move |mock| {
198            mock.ciphers_api
199                .expect_delete()
200                .returning(move |_model| Ok(()));
201        });
202
203        // let client = create_client_with_wiremock(mock_server).await;
204        let cipher_id: CipherId = TEST_CIPHER_ID.parse().unwrap();
205        let repository = MemoryRepository::<Cipher>::default();
206        repository
207            .set(cipher_id, generate_test_cipher())
208            .await
209            .unwrap();
210
211        delete_cipher(cipher_id, &api_client, &repository)
212            .await
213            .unwrap();
214
215        let cipher = repository.get(cipher_id).await.unwrap();
216        assert!(
217            cipher.is_none(),
218            "Cipher is deleted from the local repository"
219        );
220    }
221
222    #[tokio::test]
223    async fn test_delete_many() {
224        let api_client = ApiClient::new_mocked(move |mock| {
225            mock.ciphers_api
226                .expect_delete_many()
227                .returning(move |_model| Ok(()));
228        });
229        let repository = MemoryRepository::<Cipher>::default();
230
231        let cipher_1 = generate_test_cipher();
232        let mut cipher_2 = generate_test_cipher();
233        cipher_2.id = Some(TEST_CIPHER_ID_2.parse().unwrap());
234
235        let cipher_id: CipherId = TEST_CIPHER_ID.parse().unwrap();
236        let cipher_id_2: CipherId = TEST_CIPHER_ID_2.parse().unwrap();
237
238        repository.set(cipher_id, cipher_1).await.unwrap();
239        repository.set(cipher_id_2, cipher_2).await.unwrap();
240
241        delete_ciphers(vec![cipher_id, cipher_id_2], None, &api_client, &repository)
242            .await
243            .unwrap();
244
245        let cipher_1 = repository.get(cipher_id).await.unwrap();
246        let cipher_2 = repository.get(cipher_id_2).await.unwrap();
247        assert!(
248            cipher_1.is_none(),
249            "Cipher is deleted from the local repository"
250        );
251        assert!(
252            cipher_2.is_none(),
253            "Cipher is deleted from the local repository"
254        );
255    }
256
257    #[tokio::test]
258    async fn test_soft_delete() {
259        let api_client = ApiClient::new_mocked(move |mock| {
260            mock.ciphers_api
261                .expect_put_delete()
262                .returning(move |_model| Ok(()));
263        });
264        let repository = MemoryRepository::<Cipher>::default();
265
266        let cipher_id: CipherId = TEST_CIPHER_ID.parse().unwrap();
267        repository
268            .set(cipher_id, generate_test_cipher())
269            .await
270            .unwrap();
271
272        let start_time = Utc::now();
273        soft_delete(cipher_id, &api_client, &repository)
274            .await
275            .unwrap();
276        let end_time = Utc::now();
277
278        let cipher: Cipher = repository.get(cipher_id).await.unwrap().unwrap();
279        assert!(
280            cipher.deleted_date.unwrap() >= start_time && cipher.deleted_date.unwrap() <= end_time,
281            "Cipher was flagged as deleted in the repository."
282        );
283    }
284
285    #[tokio::test]
286    async fn test_soft_delete_many() {
287        let api_client = ApiClient::new_mocked(move |mock| {
288            mock.ciphers_api
289                .expect_put_delete_many()
290                .returning(move |_model| Ok(()));
291        });
292        let repository = MemoryRepository::<Cipher>::default();
293
294        let cipher_1 = generate_test_cipher();
295        let mut cipher_2 = generate_test_cipher();
296        cipher_2.id = Some(TEST_CIPHER_ID_2.parse().unwrap());
297
298        let cipher_id: CipherId = TEST_CIPHER_ID.parse().unwrap();
299        let cipher_id_2: CipherId = TEST_CIPHER_ID_2.parse().unwrap();
300        repository.set(cipher_id, cipher_1).await.unwrap();
301        repository.set(cipher_id_2, cipher_2).await.unwrap();
302
303        let start_time = Utc::now();
304
305        soft_delete_many(vec![cipher_id, cipher_id_2], None, &api_client, &repository)
306            .await
307            .unwrap();
308        let end_time = Utc::now();
309
310        let cipher_1 = repository.get(cipher_id).await.unwrap().unwrap();
311        let cipher_2 = repository.get(cipher_id_2).await.unwrap().unwrap();
312
313        assert!(
314            cipher_1.deleted_date.unwrap() >= start_time
315                && cipher_1.deleted_date.unwrap() <= end_time,
316            "Cipher was flagged as deleted in the repository."
317        );
318        assert!(
319            cipher_2.deleted_date.unwrap() >= start_time
320                && cipher_2.deleted_date.unwrap() <= end_time,
321            "Cipher was flagged as deleted in the repository."
322        );
323    }
324}