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