bitwarden_vault/cipher/attachment_client/
delete.rs1use bitwarden_core::{ApiError, MissingFieldError};
2use bitwarden_error::bitwarden_error;
3use bitwarden_state::repository::{RepositoryError, RepositoryOption};
4use thiserror::Error;
5
6use crate::{AttachmentsClient, Cipher, CipherId, VaultParseError, cipher::cipher::PartialCipher};
7
8#[allow(missing_docs)]
9#[bitwarden_error(flat)]
10#[derive(Debug, Error)]
11pub enum CipherDeleteAttachmentError {
12 #[error(transparent)]
13 Api(#[from] ApiError),
14 #[error(transparent)]
15 Repository(#[from] RepositoryError),
16 #[error(transparent)]
17 MissingField(#[from] MissingFieldError),
18 #[error(transparent)]
19 VaultParse(#[from] VaultParseError),
20}
21
22#[bitwarden_ffi::wasm_export]
23impl AttachmentsClient {
24 pub async fn delete_attachment(
27 &self,
28 cipher_id: CipherId,
29 attachment_id: String,
30 ) -> Result<Cipher, CipherDeleteAttachmentError> {
31 let repository = self.repository.require()?;
32
33 let response = self
34 .api_configurations
35 .api_client
36 .ciphers_api()
37 .delete_attachment(cipher_id.into(), &attachment_id)
38 .await?;
39
40 let existing_cipher = repository.get(cipher_id).await?;
41 let cipher_response = response
42 .cipher
43 .map(|c| *c)
44 .ok_or(MissingFieldError("cipher"))?;
45 let cipher = cipher_response.merge_with_cipher(existing_cipher)?;
46
47 repository.set(cipher_id, cipher.clone()).await?;
48
49 Ok(cipher)
50 }
51}
52
53#[cfg(test)]
54mod tests {
55 use std::sync::Arc;
56
57 use bitwarden_api_api::{
58 apis::ApiClient,
59 models::{CipherMiniResponseModel, DeleteAttachmentResponseModel},
60 };
61 use bitwarden_core::{client::ApiConfigurations, key_management::KeySlotIds};
62 use bitwarden_crypto::KeyStore;
63 use bitwarden_state::repository::Repository;
64 use bitwarden_test::MemoryRepository;
65
66 use super::*;
67 use crate::{Attachment, CipherRepromptType, CipherType};
68
69 const TEST_CIPHER_ID: &str = "5faa9684-c793-4a2d-8a12-b33900187097";
70 const TEST_ATTACHMENT_ID: &str = "uf7bkexzag04d3cw04jsbqqkbpbwhxs0";
71 const TEST_CIPHER_NAME: &str = "2.pMS6/icTQABtulw52pq2lg==|XXbxKxDTh+mWiN1HjH2N1w==|Q6PkuT+KX/axrgN9ubD5Ajk2YNwxQkgs3WJM0S0wtG8=";
72 const TEST_FILE_NAME: &str = "2.mV50WiLq6duhwGbhM1TO0A==|dTufWNH8YTPP0EMlNLIpFA==|QHp+7OM8xHtEmCfc9QPXJ0Ro2BeakzvLgxJZ7NdLuDc=";
73
74 fn client_with_api_and_repo(
75 api_client: ApiClient,
76 repository: MemoryRepository<Cipher>,
77 ) -> AttachmentsClient {
78 AttachmentsClient {
79 key_store: KeyStore::<KeySlotIds>::default(),
80 api_configurations: Arc::new(ApiConfigurations::from_api_client(api_client)),
81 repository: Some(Arc::new(repository)),
82 }
83 }
84
85 fn test_cipher() -> Cipher {
86 Cipher {
87 partial_data: None,
88 id: TEST_CIPHER_ID.parse().ok(),
89 name: Some(TEST_CIPHER_NAME.parse().unwrap()),
90 r#type: CipherType::Login,
91 attachments: Some(vec![Attachment {
92 id: Some(TEST_ATTACHMENT_ID.to_string()),
93 url: Some("http://localhost:4000/attachments/test".to_string()),
94 file_name: Some(TEST_FILE_NAME.parse().unwrap()),
95 key: None,
96 size: Some("65".to_string()),
97 size_name: Some("65 Bytes".to_string()),
98 }]),
99 organization_id: None,
100 folder_id: None,
101 collection_ids: vec![],
102 key: None,
103 notes: None,
104 login: None,
105 identity: None,
106 card: None,
107 secure_note: None,
108 ssh_key: None,
109 bank_account: None,
110 drivers_license: None,
111 passport: None,
112 favorite: false,
113 reprompt: CipherRepromptType::None,
114 organization_use_totp: true,
115 edit: true,
116 permissions: None,
117 view_password: true,
118 local_data: None,
119 fields: None,
120 password_history: None,
121 creation_date: "2024-05-31T11:20:58.4566667Z".parse().unwrap(),
122 deleted_date: None,
123 revision_date: "2024-05-31T11:20:58.4566667Z".parse().unwrap(),
124 archived_date: None,
125 data: None,
126 }
127 }
128
129 #[tokio::test]
130 async fn returns_updated_cipher_on_success() {
131 let cipher_id: CipherId = TEST_CIPHER_ID.parse().unwrap();
132 let api_client = ApiClient::new_mocked(|mock| {
133 mock.ciphers_api
134 .expect_delete_attachment()
135 .returning(|id, attachment_id| {
136 assert_eq!(&id.to_string(), TEST_CIPHER_ID);
137 assert_eq!(attachment_id, TEST_ATTACHMENT_ID);
138 Ok(DeleteAttachmentResponseModel {
139 object: None,
140 cipher: Some(Box::new(CipherMiniResponseModel {
141 id: Some(TEST_CIPHER_ID.try_into().unwrap()),
142 name: Some(TEST_CIPHER_NAME.to_string()),
143 r#type: Some(bitwarden_api_api::models::CipherType::Login),
144 creation_date: Some("2024-05-31T11:20:58.4566667Z".to_string()),
145 revision_date: Some("2024-05-31T11:20:58.4566667Z".to_string()),
146 attachments: None,
147 ..Default::default()
148 })),
149 })
150 });
151 });
152
153 let repository = MemoryRepository::<Cipher>::default();
154 repository.set(cipher_id, test_cipher()).await.unwrap();
155 let client = client_with_api_and_repo(api_client, repository);
156
157 let result = client
158 .delete_attachment(cipher_id, TEST_ATTACHMENT_ID.to_string())
159 .await
160 .unwrap();
161
162 assert!(result.attachments.is_none());
163
164 let repo_cipher = client
165 .repository
166 .as_ref()
167 .unwrap()
168 .get(cipher_id)
169 .await
170 .unwrap()
171 .unwrap();
172 assert!(repo_cipher.attachments.is_none());
173 }
174
175 #[tokio::test]
176 async fn errors_when_response_has_no_cipher() {
177 let cipher_id: CipherId = TEST_CIPHER_ID.parse().unwrap();
178 let api_client = ApiClient::new_mocked(|mock| {
179 mock.ciphers_api
180 .expect_delete_attachment()
181 .returning(|_id, _attachment_id| {
182 Ok(DeleteAttachmentResponseModel {
183 object: None,
184 cipher: None,
185 })
186 });
187 });
188
189 let repository = MemoryRepository::<Cipher>::default();
190 repository.set(cipher_id, test_cipher()).await.unwrap();
191 let client = client_with_api_and_repo(api_client, repository);
192
193 let result = client
194 .delete_attachment(cipher_id, TEST_ATTACHMENT_ID.to_string())
195 .await;
196
197 assert!(result.is_err());
198 }
199}