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            organization_use_totp: Default::default(),
180            edit: Default::default(),
181            permissions: Default::default(),
182            view_password: Default::default(),
183            local_data: Default::default(),
184            attachments: Default::default(),
185            password_history: Default::default(),
186            creation_date: Default::default(),
187            deleted_date: Default::default(),
188            revision_date: Default::default(),
189            archived_date: Default::default(),
190            data: Default::default(),
191        }
192    }
193
194    #[tokio::test]
195    async fn test_delete() {
196        let api_client = ApiClient::new_mocked(move |mock| {
197            mock.ciphers_api
198                .expect_delete()
199                .returning(move |_model| Ok(()));
200        });
201
202        // let client = create_client_with_wiremock(mock_server).await;
203        let cipher_id: CipherId = TEST_CIPHER_ID.parse().unwrap();
204        let repository = MemoryRepository::<Cipher>::default();
205        repository
206            .set(cipher_id, generate_test_cipher())
207            .await
208            .unwrap();
209
210        delete_cipher(cipher_id, &api_client, &repository)
211            .await
212            .unwrap();
213
214        let cipher = repository.get(cipher_id).await.unwrap();
215        assert!(
216            cipher.is_none(),
217            "Cipher is deleted from the local repository"
218        );
219    }
220
221    #[tokio::test]
222    async fn test_delete_many() {
223        let api_client = ApiClient::new_mocked(move |mock| {
224            mock.ciphers_api
225                .expect_delete_many()
226                .returning(move |_model| Ok(()));
227        });
228        let repository = MemoryRepository::<Cipher>::default();
229
230        let cipher_1 = generate_test_cipher();
231        let mut cipher_2 = generate_test_cipher();
232        cipher_2.id = Some(TEST_CIPHER_ID_2.parse().unwrap());
233
234        let cipher_id: CipherId = TEST_CIPHER_ID.parse().unwrap();
235        let cipher_id_2: CipherId = TEST_CIPHER_ID_2.parse().unwrap();
236
237        repository.set(cipher_id, cipher_1).await.unwrap();
238        repository.set(cipher_id_2, cipher_2).await.unwrap();
239
240        delete_ciphers(vec![cipher_id, cipher_id_2], None, &api_client, &repository)
241            .await
242            .unwrap();
243
244        let cipher_1 = repository.get(cipher_id).await.unwrap();
245        let cipher_2 = repository.get(cipher_id_2).await.unwrap();
246        assert!(
247            cipher_1.is_none(),
248            "Cipher is deleted from the local repository"
249        );
250        assert!(
251            cipher_2.is_none(),
252            "Cipher is deleted from the local repository"
253        );
254    }
255
256    #[tokio::test]
257    async fn test_soft_delete() {
258        let api_client = ApiClient::new_mocked(move |mock| {
259            mock.ciphers_api
260                .expect_put_delete()
261                .returning(move |_model| Ok(()));
262        });
263        let repository = MemoryRepository::<Cipher>::default();
264
265        let cipher_id: CipherId = TEST_CIPHER_ID.parse().unwrap();
266        repository
267            .set(cipher_id, generate_test_cipher())
268            .await
269            .unwrap();
270
271        let start_time = Utc::now();
272        soft_delete(cipher_id, &api_client, &repository)
273            .await
274            .unwrap();
275        let end_time = Utc::now();
276
277        let cipher: Cipher = repository.get(cipher_id).await.unwrap().unwrap();
278        assert!(
279            cipher.deleted_date.unwrap() >= start_time && cipher.deleted_date.unwrap() <= end_time,
280            "Cipher was flagged as deleted in the repository."
281        );
282    }
283
284    #[tokio::test]
285    async fn test_soft_delete_many() {
286        let api_client = ApiClient::new_mocked(move |mock| {
287            mock.ciphers_api
288                .expect_put_delete_many()
289                .returning(move |_model| Ok(()));
290        });
291        let repository = MemoryRepository::<Cipher>::default();
292
293        let cipher_1 = generate_test_cipher();
294        let mut cipher_2 = generate_test_cipher();
295        cipher_2.id = Some(TEST_CIPHER_ID_2.parse().unwrap());
296
297        let cipher_id: CipherId = TEST_CIPHER_ID.parse().unwrap();
298        let cipher_id_2: CipherId = TEST_CIPHER_ID_2.parse().unwrap();
299        repository.set(cipher_id, cipher_1).await.unwrap();
300        repository.set(cipher_id_2, cipher_2).await.unwrap();
301
302        let start_time = Utc::now();
303
304        soft_delete_many(vec![cipher_id, cipher_id_2], None, &api_client, &repository)
305            .await
306            .unwrap();
307        let end_time = Utc::now();
308
309        let cipher_1 = repository.get(cipher_id).await.unwrap().unwrap();
310        let cipher_2 = repository.get(cipher_id_2).await.unwrap().unwrap();
311
312        assert!(
313            cipher_1.deleted_date.unwrap() >= start_time
314                && cipher_1.deleted_date.unwrap() <= end_time,
315            "Cipher was flagged as deleted in the repository."
316        );
317        assert!(
318            cipher_2.deleted_date.unwrap() >= start_time
319                && cipher_2.deleted_date.unwrap() <= end_time,
320            "Cipher was flagged as deleted in the repository."
321        );
322    }
323}