1use bitwarden_core::{ApiError, MissingFieldError};
2use bitwarden_error::bitwarden_error;
3use bitwarden_state::repository::{RepositoryError, RepositoryOption};
4use reqwest::StatusCode;
5use thiserror::Error;
6
7use crate::{AttachmentsClient, CipherId};
8
9#[allow(missing_docs)]
10#[bitwarden_error(flat)]
11#[derive(Debug, Error)]
12pub enum CipherGetAttachmentDownloadUrlError {
13 #[error(transparent)]
14 Api(#[from] ApiError),
15 #[error(transparent)]
16 Repository(#[from] RepositoryError),
17 #[error(transparent)]
18 MissingField(#[from] MissingFieldError),
19 #[error("Cipher or attachment not found")]
20 NotFound,
21 #[error("Invalid emergency access ID")]
22 InvalidEmergencyAccessId,
23}
24
25#[bitwarden_ffi::wasm_export]
26impl AttachmentsClient {
27 pub async fn get_attachment_download_url(
32 &self,
33 cipher_id: CipherId,
34 attachment_id: String,
35 emergency_access_id: Option<String>,
36 ) -> Result<String, CipherGetAttachmentDownloadUrlError> {
37 if let Some(emergency_access_id) = emergency_access_id {
38 return self
39 .get_emergency_access_attachment_download_url(
40 &emergency_access_id,
41 cipher_id,
42 &attachment_id,
43 )
44 .await;
45 }
46
47 match self
48 .api_configurations
49 .api_client
50 .ciphers_api()
51 .get_attachment_data(cipher_id.into(), &attachment_id)
52 .await
53 {
54 Ok(response) => response.url.ok_or_else(|| MissingFieldError("url").into()),
55 Err(bitwarden_api_api::ApiError::Response(content))
56 if content.status == StatusCode::NOT_FOUND =>
57 {
58 let repository = self.repository.require()?;
59 let cipher = repository
60 .get(cipher_id)
61 .await?
62 .ok_or(CipherGetAttachmentDownloadUrlError::NotFound)?;
63
64 cipher
65 .attachments
66 .and_then(|attachments| {
67 attachments
68 .into_iter()
69 .find(|a| a.id.as_deref() == Some(&attachment_id))
70 })
71 .and_then(|attachment| attachment.url)
72 .ok_or(CipherGetAttachmentDownloadUrlError::NotFound)
73 }
74 Err(e) => Err(e.into()),
75 }
76 }
77}
78
79impl AttachmentsClient {
80 async fn get_emergency_access_attachment_download_url(
82 &self,
83 emergency_access_id: &str,
84 cipher_id: CipherId,
85 attachment_id: &str,
86 ) -> Result<String, CipherGetAttachmentDownloadUrlError> {
87 let emergency_access_id = emergency_access_id
88 .parse::<uuid::Uuid>()
89 .map_err(|_| CipherGetAttachmentDownloadUrlError::InvalidEmergencyAccessId)?;
90
91 let response = self
92 .api_configurations
93 .api_client
94 .emergency_access_api()
95 .get_attachment_data(emergency_access_id, cipher_id.into(), attachment_id)
96 .await
97 .map_err(|e| match e {
98 bitwarden_api_api::ApiError::Response(content)
99 if content.status == StatusCode::NOT_FOUND =>
100 {
101 CipherGetAttachmentDownloadUrlError::NotFound
102 }
103 other => other.into(),
104 })?;
105
106 response.url.ok_or_else(|| MissingFieldError("url").into())
107 }
108}
109
110#[cfg(test)]
111mod tests {
112 use std::sync::Arc;
113
114 use bitwarden_api_api::{apis::ApiClient, models::AttachmentResponseModel};
115 use bitwarden_core::{client::ApiConfigurations, key_management::KeySlotIds};
116 use bitwarden_crypto::KeyStore;
117 use bitwarden_state::repository::Repository;
118 use bitwarden_test::MemoryRepository;
119
120 use super::*;
121 use crate::{Attachment, Cipher, CipherRepromptType, CipherType};
122
123 const TEST_CIPHER_ID: &str = "5faa9684-c793-4a2d-8a12-b33900187097";
124 const TEST_ATTACHMENT_ID: &str = "uf7bkexzag04d3cw04jsbqqkbpbwhxs0";
125 const TEST_CIPHER_NAME: &str = "2.pMS6/icTQABtulw52pq2lg==|XXbxKxDTh+mWiN1HjH2N1w==|Q6PkuT+KX/axrgN9ubD5Ajk2YNwxQkgs3WJM0S0wtG8=";
126 const TEST_FILE_NAME: &str = "2.mV50WiLq6duhwGbhM1TO0A==|dTufWNH8YTPP0EMlNLIpFA==|QHp+7OM8xHtEmCfc9QPXJ0Ro2BeakzvLgxJZ7NdLuDc=";
127 const TEST_API_URL: &str = "http://localhost:4000/attachments/test/api";
128 const TEST_FALLBACK_URL: &str = "http://localhost:4000/attachments/test/fallback";
129 const TEST_EMERGENCY_ACCESS_ID: &str = "1a2b3c4d-5e6f-7a8b-9c0d-1e2f3a4b5c6d";
130
131 fn client_with_api_and_repo(
132 api_client: ApiClient,
133 repository: MemoryRepository<Cipher>,
134 ) -> AttachmentsClient {
135 AttachmentsClient {
136 key_store: KeyStore::<KeySlotIds>::default(),
137 api_configurations: Arc::new(ApiConfigurations::from_api_client(api_client)),
138 repository: Some(Arc::new(repository)),
139 }
140 }
141
142 fn test_cipher() -> Cipher {
143 Cipher {
144 partial_data: None,
145 id: TEST_CIPHER_ID.parse().ok(),
146 name: Some(TEST_CIPHER_NAME.parse().unwrap()),
147 r#type: CipherType::Login,
148 attachments: Some(vec![Attachment {
149 id: Some(TEST_ATTACHMENT_ID.to_string()),
150 url: Some(TEST_FALLBACK_URL.to_string()),
151 file_name: Some(TEST_FILE_NAME.parse().unwrap()),
152 key: None,
153 size: Some("65".to_string()),
154 size_name: Some("65 Bytes".to_string()),
155 }]),
156 organization_id: None,
157 folder_id: None,
158 collection_ids: vec![],
159 key: None,
160 notes: None,
161 login: None,
162 identity: None,
163 card: None,
164 secure_note: None,
165 ssh_key: None,
166 bank_account: None,
167 drivers_license: None,
168 passport: None,
169 favorite: false,
170 reprompt: CipherRepromptType::None,
171 organization_use_totp: true,
172 edit: true,
173 permissions: None,
174 view_password: true,
175 local_data: None,
176 fields: None,
177 password_history: None,
178 creation_date: "2024-05-31T11:20:58.4566667Z".parse().unwrap(),
179 deleted_date: None,
180 revision_date: "2024-05-31T11:20:58.4566667Z".parse().unwrap(),
181 archived_date: None,
182 data: None,
183 }
184 }
185
186 fn not_found_response() -> bitwarden_api_api::ApiError {
187 bitwarden_api_api::ApiError::Response(bitwarden_api_api::ResponseContent {
188 status: StatusCode::NOT_FOUND,
189 message: String::new(),
190 })
191 }
192
193 #[tokio::test]
194 async fn returns_url_from_api_response() {
195 let api_client = ApiClient::new_mocked(|mock| {
196 mock.ciphers_api
197 .expect_get_attachment_data()
198 .returning(|id, attachment_id| {
199 assert_eq!(&id.to_string(), TEST_CIPHER_ID);
200 assert_eq!(attachment_id, TEST_ATTACHMENT_ID);
201 Ok(AttachmentResponseModel {
202 id: Some(TEST_ATTACHMENT_ID.to_string()),
203 url: Some(TEST_API_URL.to_string()),
204 ..Default::default()
205 })
206 });
207 });
208
209 let client = client_with_api_and_repo(api_client, MemoryRepository::<Cipher>::default());
210 let cipher_id: CipherId = TEST_CIPHER_ID.parse().unwrap();
211
212 let url = client
213 .get_attachment_download_url(cipher_id, TEST_ATTACHMENT_ID.to_string(), None)
214 .await
215 .unwrap();
216
217 assert_eq!(url, TEST_API_URL);
218 }
219
220 #[tokio::test]
221 async fn returns_missing_field_when_response_has_no_url() {
222 let api_client = ApiClient::new_mocked(|mock| {
223 mock.ciphers_api
224 .expect_get_attachment_data()
225 .returning(|_id, _attachment_id| {
226 Ok(AttachmentResponseModel {
227 id: Some(TEST_ATTACHMENT_ID.to_string()),
228 url: None,
229 ..Default::default()
230 })
231 });
232 });
233
234 let client = client_with_api_and_repo(api_client, MemoryRepository::<Cipher>::default());
235 let cipher_id: CipherId = TEST_CIPHER_ID.parse().unwrap();
236
237 let err = client
238 .get_attachment_download_url(cipher_id, TEST_ATTACHMENT_ID.to_string(), None)
239 .await
240 .unwrap_err();
241
242 assert!(matches!(
243 err,
244 CipherGetAttachmentDownloadUrlError::MissingField(_)
245 ));
246 }
247
248 #[tokio::test]
249 async fn falls_back_to_repository_url_on_404() {
250 let api_client = ApiClient::new_mocked(|mock| {
251 mock.ciphers_api
252 .expect_get_attachment_data()
253 .returning(|_id, _attachment_id| Err(not_found_response()));
254 });
255
256 let repository = MemoryRepository::<Cipher>::default();
257 let cipher_id: CipherId = TEST_CIPHER_ID.parse().unwrap();
258 repository.set(cipher_id, test_cipher()).await.unwrap();
259
260 let client = client_with_api_and_repo(api_client, repository);
261
262 let url = client
263 .get_attachment_download_url(cipher_id, TEST_ATTACHMENT_ID.to_string(), None)
264 .await
265 .unwrap();
266
267 assert_eq!(url, TEST_FALLBACK_URL);
268 }
269
270 #[tokio::test]
271 async fn returns_not_found_on_404_when_cipher_missing_from_repository() {
272 let api_client = ApiClient::new_mocked(|mock| {
273 mock.ciphers_api
274 .expect_get_attachment_data()
275 .returning(|_id, _attachment_id| Err(not_found_response()));
276 });
277
278 let client = client_with_api_and_repo(api_client, MemoryRepository::<Cipher>::default());
279 let cipher_id: CipherId = TEST_CIPHER_ID.parse().unwrap();
280
281 let err = client
282 .get_attachment_download_url(cipher_id, TEST_ATTACHMENT_ID.to_string(), None)
283 .await
284 .unwrap_err();
285
286 assert!(matches!(err, CipherGetAttachmentDownloadUrlError::NotFound));
287 }
288
289 #[tokio::test]
290 async fn returns_not_found_on_404_when_attachment_has_no_stored_url() {
291 let api_client = ApiClient::new_mocked(|mock| {
292 mock.ciphers_api
293 .expect_get_attachment_data()
294 .returning(|_id, _attachment_id| Err(not_found_response()));
295 });
296
297 let repository = MemoryRepository::<Cipher>::default();
298 let cipher_id: CipherId = TEST_CIPHER_ID.parse().unwrap();
299 let mut cipher = test_cipher();
300 if let Some(attachments) = cipher.attachments.as_mut() {
301 for attachment in attachments {
302 attachment.url = None;
303 }
304 }
305 repository.set(cipher_id, cipher).await.unwrap();
306
307 let client = client_with_api_and_repo(api_client, repository);
308
309 let err = client
310 .get_attachment_download_url(cipher_id, TEST_ATTACHMENT_ID.to_string(), None)
311 .await
312 .unwrap_err();
313
314 assert!(matches!(err, CipherGetAttachmentDownloadUrlError::NotFound));
315 }
316
317 #[tokio::test]
318 async fn propagates_non_404_api_errors() {
319 let api_client = ApiClient::new_mocked(|mock| {
320 mock.ciphers_api
321 .expect_get_attachment_data()
322 .returning(|_id, _attachment_id| {
323 Err(bitwarden_api_api::ApiError::Response(
324 bitwarden_api_api::ResponseContent {
325 status: StatusCode::INTERNAL_SERVER_ERROR,
326 message: "bitwarden".to_string(),
327 },
328 ))
329 });
330 });
331
332 let client = client_with_api_and_repo(api_client, MemoryRepository::<Cipher>::default());
333 let cipher_id: CipherId = TEST_CIPHER_ID.parse().unwrap();
334
335 let err = client
336 .get_attachment_download_url(cipher_id, TEST_ATTACHMENT_ID.to_string(), None)
337 .await
338 .unwrap_err();
339
340 assert!(matches!(err, CipherGetAttachmentDownloadUrlError::Api(_)));
341 }
342
343 #[tokio::test]
344 async fn emergency_access_returns_url_from_api_response() {
345 let api_client = ApiClient::new_mocked(|mock| {
346 mock.emergency_access_api
347 .expect_get_attachment_data()
348 .returning(|ea_id, cipher_id, attachment_id| {
349 assert_eq!(&ea_id.to_string(), TEST_EMERGENCY_ACCESS_ID);
350 assert_eq!(&cipher_id.to_string(), TEST_CIPHER_ID);
351 assert_eq!(attachment_id, TEST_ATTACHMENT_ID);
352 Ok(AttachmentResponseModel {
353 id: Some(TEST_ATTACHMENT_ID.to_string()),
354 url: Some(TEST_API_URL.to_string()),
355 ..Default::default()
356 })
357 });
358 });
359
360 let client = client_with_api_and_repo(api_client, MemoryRepository::<Cipher>::default());
361 let cipher_id: CipherId = TEST_CIPHER_ID.parse().unwrap();
362
363 let url = client
364 .get_attachment_download_url(
365 cipher_id,
366 TEST_ATTACHMENT_ID.to_string(),
367 Some(TEST_EMERGENCY_ACCESS_ID.to_string()),
368 )
369 .await
370 .unwrap();
371
372 assert_eq!(url, TEST_API_URL);
373 }
374
375 #[tokio::test]
376 async fn emergency_access_returns_missing_field_when_response_has_no_url() {
377 let api_client = ApiClient::new_mocked(|mock| {
378 mock.emergency_access_api
379 .expect_get_attachment_data()
380 .returning(|_ea_id, _cipher_id, _attachment_id| {
381 Ok(AttachmentResponseModel {
382 id: Some(TEST_ATTACHMENT_ID.to_string()),
383 url: None,
384 ..Default::default()
385 })
386 });
387 });
388
389 let client = client_with_api_and_repo(api_client, MemoryRepository::<Cipher>::default());
390 let cipher_id: CipherId = TEST_CIPHER_ID.parse().unwrap();
391
392 let err = client
393 .get_attachment_download_url(
394 cipher_id,
395 TEST_ATTACHMENT_ID.to_string(),
396 Some(TEST_EMERGENCY_ACCESS_ID.to_string()),
397 )
398 .await
399 .unwrap_err();
400
401 assert!(matches!(
402 err,
403 CipherGetAttachmentDownloadUrlError::MissingField(_)
404 ));
405 }
406
407 #[tokio::test]
408 async fn emergency_access_returns_not_found_on_404() {
409 let api_client = ApiClient::new_mocked(|mock| {
410 mock.emergency_access_api
411 .expect_get_attachment_data()
412 .returning(|_ea_id, _cipher_id, _attachment_id| Err(not_found_response()));
413 });
414
415 let client = client_with_api_and_repo(api_client, MemoryRepository::<Cipher>::default());
416 let cipher_id: CipherId = TEST_CIPHER_ID.parse().unwrap();
417
418 let err = client
419 .get_attachment_download_url(
420 cipher_id,
421 TEST_ATTACHMENT_ID.to_string(),
422 Some(TEST_EMERGENCY_ACCESS_ID.to_string()),
423 )
424 .await
425 .unwrap_err();
426
427 assert!(matches!(err, CipherGetAttachmentDownloadUrlError::NotFound));
428 }
429
430 #[tokio::test]
431 async fn emergency_access_propagates_non_404_api_errors() {
432 let api_client = ApiClient::new_mocked(|mock| {
433 mock.emergency_access_api
434 .expect_get_attachment_data()
435 .returning(|_ea_id, _cipher_id, _attachment_id| {
436 Err(bitwarden_api_api::ApiError::Response(
437 bitwarden_api_api::ResponseContent {
438 status: StatusCode::INTERNAL_SERVER_ERROR,
439 message: "bitwarden".to_string(),
440 },
441 ))
442 });
443 });
444
445 let client = client_with_api_and_repo(api_client, MemoryRepository::<Cipher>::default());
446 let cipher_id: CipherId = TEST_CIPHER_ID.parse().unwrap();
447
448 let err = client
449 .get_attachment_download_url(
450 cipher_id,
451 TEST_ATTACHMENT_ID.to_string(),
452 Some(TEST_EMERGENCY_ACCESS_ID.to_string()),
453 )
454 .await
455 .unwrap_err();
456
457 assert!(matches!(err, CipherGetAttachmentDownloadUrlError::Api(_)));
458 }
459
460 #[tokio::test]
461 async fn returns_invalid_emergency_access_id_when_parse_fails() {
462 let api_client = ApiClient::new_mocked(|_mock| {});
463 let client = client_with_api_and_repo(api_client, MemoryRepository::<Cipher>::default());
464 let cipher_id: CipherId = TEST_CIPHER_ID.parse().unwrap();
465
466 let err = client
467 .get_attachment_download_url(
468 cipher_id,
469 TEST_ATTACHMENT_ID.to_string(),
470 Some("not-a-uuid".to_string()),
471 )
472 .await
473 .unwrap_err();
474
475 assert!(matches!(
476 err,
477 CipherGetAttachmentDownloadUrlError::InvalidEmergencyAccessId
478 ));
479 }
480}