1use bitwarden_api_api::{
2 apis::ApiClient,
3 models::{self, SendEncryptionType},
4};
5use bitwarden_core::{ApiError, key_management::KeySlotIds};
6use bitwarden_crypto::{
7 CryptoError, EncString, KeyDecryptable as _, KeyStore, SymmetricCryptoKey, derive_shareable_key,
8};
9use bitwarden_encoding::{B64, B64Url};
10use bitwarden_error::bitwarden_error;
11use bitwarden_vault::{CipherId, CipherView};
12use chrono::{DateTime, Utc};
13use serde::{Deserialize, Serialize};
14use thiserror::Error;
15#[cfg(feature = "wasm")]
16use wasm_bindgen::prelude::*;
17use zeroize::Zeroizing;
18
19use crate::{
20 SendParseError, SendType,
21 send::{SEND_ITERATIONS, SendItemMetadataView},
22 send_client::SendClient,
23};
24
25pub(crate) const SEND_KEY_LEN: usize = 16;
29
30#[derive(Debug, Serialize, Deserialize)]
36#[serde(rename_all = "camelCase")]
37#[bitwarden_ffi::wasm_record]
38pub struct SendAccessResponse {
39 pub id: Option<String>,
41 #[serde(rename = "type")]
43 pub type_: Option<SendType>,
44 pub name: Option<String>,
46 pub text: Option<SendAccessTextResponse>,
48 pub file: Option<SendAccessFileResponse>,
50 pub data: Option<SendAccessItemResponse>,
52 pub expiration_date: Option<DateTime<Utc>>,
54 pub creator_identifier: Option<String>,
56}
57
58#[derive(Debug, Serialize, Deserialize)]
60#[serde(rename_all = "camelCase")]
61#[bitwarden_ffi::wasm_record]
62pub struct SendAccessTextResponse {
63 pub text: Option<String>,
65 pub hidden: bool,
67}
68
69#[derive(Debug, Serialize, Deserialize)]
71#[serde(rename_all = "camelCase")]
72#[bitwarden_ffi::wasm_record]
73pub struct SendAccessFileResponse {
74 pub id: Option<String>,
76 pub file_name: Option<String>,
78 pub size: Option<String>,
80 pub size_name: Option<String>,
82}
83
84#[derive(Debug, Serialize, Deserialize)]
86#[serde(rename_all = "camelCase")]
87#[bitwarden_ffi::wasm_record]
88pub struct SendAccessItemResponse {
89 pub encryption_version: Option<SendEncryptionType>,
91 pub data: Option<String>,
93 pub metadata: SendAccessItemMetadataResponse,
95}
96
97#[derive(Debug, Serialize, Deserialize)]
98#[serde(rename_all = "camelCase")]
99#[bitwarden_ffi::wasm_record]
100pub struct SendAccessItemMetadataResponse {
101 pub item_id: CipherId,
103 pub folder_name: Option<String>,
105 pub collection_names: Option<Vec<String>>,
107 pub organization_name: Option<String>,
110 pub creation_date: Option<DateTime<Utc>>,
112 pub revision_date: Option<DateTime<Utc>>,
114}
115
116#[derive(Debug, Serialize, Deserialize)]
118#[serde(rename_all = "camelCase")]
119#[bitwarden_ffi::wasm_record]
120pub struct SendFileDownloadData {
121 pub id: Option<String>,
123 pub url: Option<String>,
125}
126
127#[derive(Debug, Serialize, Deserialize, PartialEq)]
142#[serde(rename_all = "camelCase")]
143#[bitwarden_ffi::wasm_record]
144pub struct SendAccessView {
145 pub id: Option<String>,
147 #[serde(rename = "type")]
149 pub type_: Option<SendType>,
150 pub name: Option<String>,
153 pub text: Option<SendAccessTextView>,
155 pub file: Option<SendAccessFileView>,
157 pub data: Option<SendAccessItemView>,
159 pub expiration_date: Option<DateTime<Utc>>,
161 pub creator_identifier: Option<String>,
163}
164
165#[derive(Debug, Serialize, Deserialize, PartialEq)]
167#[serde(rename_all = "camelCase")]
168#[bitwarden_ffi::wasm_record]
169pub struct SendAccessTextView {
170 pub text: Option<String>,
172 pub hidden: bool,
174}
175
176#[derive(Debug, Serialize, Deserialize, PartialEq)]
178#[serde(rename_all = "camelCase")]
179#[bitwarden_ffi::wasm_record]
180pub struct SendAccessFileView {
181 pub id: Option<String>,
183 pub file_name: Option<String>,
185 pub size: Option<String>,
187 pub size_name: Option<String>,
189}
190
191#[derive(Debug, Serialize, Deserialize, PartialEq)]
193#[serde(rename_all = "camelCase")]
194#[bitwarden_ffi::wasm_record]
195pub struct SendAccessItemView {
196 pub data: Option<CipherView>,
198 pub metadata: SendItemMetadataView,
200}
201
202#[bitwarden_error(flat)]
207#[derive(Debug, Error)]
208pub enum SendAccessKeyError {
209 #[error("The send key is not valid url-safe base64")]
211 InvalidEncoding,
212 #[error("The send key must be {SEND_KEY_LEN} bytes")]
214 InvalidLength,
215}
216
217#[bitwarden_error(flat)]
220#[derive(Debug, Error)]
221pub enum SendAccessDecryptError {
222 #[error(transparent)]
225 Crypto(#[from] CryptoError),
226 #[error(transparent)]
228 Key(#[from] SendAccessKeyError),
229}
230
231pub struct SendAccessKey {
241 secret: Zeroizing<[u8; SEND_KEY_LEN]>,
245 key: SymmetricCryptoKey,
248}
249
250impl SendAccessKey {
251 pub fn from_url_b64(key_b64: &str) -> Result<Self, SendAccessKeyError> {
260 let decoded = Zeroizing::new(
263 B64Url::try_from(key_b64)
264 .map_err(|_| SendAccessKeyError::InvalidEncoding)?
265 .into_bytes(),
266 );
267 if decoded.len() != SEND_KEY_LEN {
268 return Err(SendAccessKeyError::InvalidLength);
269 }
270 let mut secret = Zeroizing::new([0u8; SEND_KEY_LEN]);
271 secret.copy_from_slice(&decoded);
272
273 let key = SymmetricCryptoKey::Aes256CbcHmacKey(derive_shareable_key(
274 secret.clone(),
275 "send",
276 Some("send"),
277 ));
278
279 Ok(Self { secret, key })
280 }
281
282 pub fn hash_password_b64(&self, password: &str) -> String {
289 let hashed =
290 bitwarden_crypto::pbkdf2(password.as_bytes(), self.secret.as_slice(), SEND_ITERATIONS);
291 B64::from(hashed.as_slice()).to_string()
292 }
293
294 pub fn decrypt_response(
297 &self,
298 response: SendAccessResponse,
299 ) -> Result<SendAccessView, SendAccessDecryptError> {
300 let text = match response.text {
301 Some(t) => Some(SendAccessTextView {
302 text: self.decrypt_optional(t.text)?,
303 hidden: t.hidden,
304 }),
305 None => None,
306 };
307 let file = match response.file {
308 Some(f) => Some(SendAccessFileView {
309 id: f.id,
310 file_name: self.decrypt_optional(f.file_name)?,
311 size: f.size,
312 size_name: f.size_name,
313 }),
314 None => None,
315 };
316 let data = match response.data {
317 Some(d) => {
318 let key_store: KeyStore<KeySlotIds> = KeyStore::default();
319 let mut ctx = key_store.context_mut();
320 let key = ctx.add_local_symmetric_key(self.key.clone());
321 let Some(data) = d.data else {
322 return Err(SendAccessDecryptError::Crypto(CryptoError::MissingField(
323 "data",
324 )));
325 };
326 let mut cipher_view = CipherView::unseal_blob_for_item_sends(&data, &mut ctx, key)?;
327 cipher_view.id = Some(d.metadata.item_id);
329 if let Some(creation_date) = d.metadata.creation_date {
330 cipher_view.creation_date = creation_date;
331 }
332 if let Some(revision_date) = d.metadata.revision_date {
333 cipher_view.revision_date = revision_date;
334 }
335 Some(SendAccessItemView {
336 data: Some(cipher_view),
337 metadata: SendItemMetadataView {
338 item_id: d.metadata.item_id,
339 folder_name: self.decrypt_optional(d.metadata.folder_name)?,
340 collection_names: d
341 .metadata
342 .collection_names
343 .as_ref()
344 .map(|cols| {
345 cols.iter()
346 .map(|c| self.decrypt_required(c.to_string()))
347 .collect()
348 })
349 .transpose()?,
350 organization_name: d.metadata.organization_name,
351 creation_date: d.metadata.creation_date,
352 revision_date: d.metadata.revision_date,
353 },
354 })
355 }
356 None => None,
357 };
358
359 Ok(SendAccessView {
360 id: response.id,
361 type_: response.type_,
362 name: self.decrypt_optional(response.name)?,
363 text,
364 file,
365 data,
366 expiration_date: response.expiration_date,
367 creator_identifier: response.creator_identifier,
368 })
369 }
370
371 pub fn decrypt_file_buffer(&self, buffer: &[u8]) -> Result<Vec<u8>, SendAccessDecryptError> {
375 Ok(EncString::from_buffer(buffer)?.decrypt_with_key(&self.key)?)
376 }
377
378 fn decrypt_optional(
381 &self,
382 value: Option<String>,
383 ) -> Result<Option<String>, SendAccessDecryptError> {
384 match value {
385 Some(s) => Ok(Some(s.parse::<EncString>()?.decrypt_with_key(&self.key)?)),
386 None => Ok(None),
387 }
388 }
389
390 fn decrypt_required(&self, value: String) -> Result<String, SendAccessDecryptError> {
392 Ok(EncString::parse_strict(value.as_str())?.decrypt_with_key(&self.key)?)
393 }
394}
395
396#[bitwarden_error(flat)]
398#[derive(Debug, Error)]
399pub enum AccessSendError {
400 #[error("The send was not found")]
402 NotFound,
403 #[error(transparent)]
405 Api(ApiError),
406 #[error(transparent)]
410 Parse(#[from] SendParseError),
411}
412
413#[bitwarden_error(flat)]
415#[derive(Debug, Error)]
416pub enum GetFileDownloadDataError {
417 #[error("The send file was not found")]
420 NotFound,
421 #[error(transparent)]
423 Api(ApiError),
424}
425
426fn is_not_found(error: &ApiError) -> bool {
427 matches!(error, ApiError::Response(r) if r.status == reqwest::StatusCode::NOT_FOUND)
428}
429
430impl From<ApiError> for AccessSendError {
431 fn from(error: ApiError) -> Self {
432 if is_not_found(&error) {
433 Self::NotFound
434 } else {
435 Self::Api(error)
436 }
437 }
438}
439
440impl From<ApiError> for GetFileDownloadDataError {
441 fn from(error: ApiError) -> Self {
442 if is_not_found(&error) {
443 Self::NotFound
444 } else {
445 Self::Api(error)
446 }
447 }
448}
449
450pub(crate) async fn access_send(
453 api_client: &ApiClient,
454 access_token: &str,
455) -> Result<SendAccessResponse, AccessSendError> {
456 let resp = api_client
457 .sends_api()
458 .access_using_auth(access_token)
459 .await?;
460 Ok(resp.try_into()?)
461}
462
463pub(crate) async fn get_file_download_data(
464 api_client: &ApiClient,
465 file_id: &str,
466 access_token: &str,
467) -> Result<SendFileDownloadData, GetFileDownloadDataError> {
468 let resp = api_client
469 .sends_api()
470 .get_send_file_download_data_using_auth(file_id, access_token)
471 .await?;
472 Ok(resp.into())
473}
474
475impl TryFrom<models::SendAccessResponseModel> for SendAccessResponse {
478 type Error = SendParseError;
479
480 fn try_from(r: models::SendAccessResponseModel) -> Result<Self, Self::Error> {
481 Ok(SendAccessResponse {
482 id: r.id,
483 type_: r.r#type.map(SendType::try_from).transpose()?,
484 name: r.name,
485 text: r.text.map(|t| SendAccessTextResponse {
486 text: t.text,
487 hidden: t.hidden.unwrap_or(false),
488 }),
489 file: r.file.map(|f| SendAccessFileResponse {
490 id: f.id,
491 file_name: f.file_name,
492 size: f.size,
493 size_name: f.size_name,
494 }),
495 data: r
496 .data
497 .map(|dat| {
498 Ok::<SendAccessItemResponse, SendParseError>(SendAccessItemResponse {
499 encryption_version: dat.encryption_version,
500 data: dat.data,
501 metadata: SendAccessItemMetadataResponse {
502 item_id: CipherId::new(dat.metadata.item_id),
503 folder_name: dat.metadata.folder_name,
504 collection_names: dat.metadata.collection_names,
505 organization_name: dat.metadata.organization_name,
506 creation_date: dat
507 .metadata
508 .creation_date
509 .map(|cd| cd.parse())
510 .transpose()?,
511 revision_date: dat
512 .metadata
513 .revision_date
514 .map(|rd| rd.parse())
515 .transpose()?,
516 },
517 })
518 })
519 .transpose()?,
520 expiration_date: r.expiration_date.map(|s| s.parse()).transpose()?,
521 creator_identifier: r.creator_identifier,
522 })
523 }
524}
525
526impl From<models::SendFileDownloadDataResponseModel> for SendFileDownloadData {
527 fn from(r: models::SendFileDownloadDataResponseModel) -> Self {
528 SendFileDownloadData {
529 id: r.id,
530 url: r.url,
531 }
532 }
533}
534
535#[allow(deprecated)]
540#[bitwarden_ffi::wasm_export]
541impl SendClient {
542 #[deprecated(
546 note = "use `SendReceiveClient::access_send` instead; a `SendClient` is tied to the signed-in instance"
547 )]
548 pub async fn access_send(
549 &self,
550 access_token: String,
551 ) -> Result<SendAccessResponse, AccessSendError> {
552 let config = self.client.internal.get_api_configurations();
553 access_send(&config.api_client, &access_token).await
554 }
555
556 #[deprecated(
558 note = "use `SendReceiveClient::get_file_download_data` instead; a `SendClient` is tied to the signed-in instance"
559 )]
560 pub async fn get_file_download_data(
561 &self,
562 access_token: String,
563 file_id: String,
564 ) -> Result<SendFileDownloadData, GetFileDownloadDataError> {
565 let config = self.client.internal.get_api_configurations();
566 get_file_download_data(&config.api_client, &file_id, &access_token).await
567 }
568
569 #[deprecated(
576 note = "use `SendReceiveClient::decrypt_send_access` instead; a `SendClient` is tied to the signed-in instance"
577 )]
578 pub fn decrypt_send_access(
579 key_b64: String,
580 response: SendAccessResponse,
581 ) -> Result<SendAccessView, SendAccessDecryptError> {
582 let access_key = SendAccessKey::from_url_b64(key_b64.as_str())?;
583 access_key.decrypt_response(response)
584 }
585}
586
587#[cfg(test)]
588#[allow(deprecated)]
589mod tests {
590 use bitwarden_api_api::{
591 apis::ApiClient,
592 models::{
593 SendAccessResponseModel, SendFileDownloadDataResponseModel, SendFileModel,
594 SendTextModel, SendType,
595 },
596 };
597
598 use super::*;
599
600 const SEND_ID: &str = "25afb11c-9c95-4db5-8bac-c21cb204a3f1";
601 const FILE_ID: &str = "file-id-abc";
602 const ACCESS_TOKEN: &str = "send-access-token";
603
604 #[tokio::test]
607 async fn test_access_send_text() {
608 let api_client = ApiClient::new_mocked(|mock| {
609 mock.sends_api
610 .expect_access_using_auth()
611 .returning(|token| {
612 assert_eq!(token, ACCESS_TOKEN);
613 Ok(SendAccessResponseModel {
614 object: Some("send-access".to_string()),
615 id: Some(SEND_ID.to_string()),
616 r#type: Some(SendType::Text),
617 auth_type: None,
618 name: Some("encrypted-name".to_string()),
619 file: None,
620 text: Some(Box::new(SendTextModel {
621 text: Some("encrypted_send_text".to_string()),
622 hidden: Some(true),
623 })),
624 data: None,
625 expiration_date: Some("2025-01-10T00:00:00Z".to_string()),
626 creator_identifier: Some("[email protected]".to_string()),
627 })
628 })
629 .once();
630 });
631
632 let result = access_send(&api_client, ACCESS_TOKEN).await.unwrap();
633
634 assert_eq!(result.id, Some(SEND_ID.to_string()));
635 assert_eq!(result.type_, Some(crate::SendType::Text));
636 assert_eq!(result.name, Some("encrypted-name".to_string()));
637 assert!(result.file.is_none());
638 let text = result.text.expect("text variant should be populated");
639 assert_eq!(text.text, Some("encrypted_send_text".to_string()));
640 assert!(text.hidden);
641 assert_eq!(
642 result.expiration_date,
643 Some("2025-01-10T00:00:00Z".parse::<DateTime<Utc>>().unwrap())
644 );
645 assert_eq!(
646 result.creator_identifier,
647 Some("[email protected]".to_string())
648 );
649 }
650
651 #[tokio::test]
652 async fn test_access_send_file() {
653 let api_client = ApiClient::new_mocked(|mock| {
654 mock.sends_api
655 .expect_access_using_auth()
656 .returning(|token| {
657 assert_eq!(token, ACCESS_TOKEN);
658 Ok(SendAccessResponseModel {
659 object: Some("send-access".to_string()),
660 id: Some(SEND_ID.to_string()),
661 r#type: Some(SendType::File),
662 auth_type: None,
663 name: Some("encrypted-name".to_string()),
664 file: Some(Box::new(SendFileModel {
665 id: Some(FILE_ID.to_string()),
666 file_name: Some("encrypted-file-name".to_string()),
667 size: Some("4200".to_string()),
668 size_name: Some("4.2 KB".to_string()),
669 })),
670 text: None,
671 data: None,
672 expiration_date: None,
673 creator_identifier: None,
674 })
675 })
676 .once();
677 });
678
679 let result = access_send(&api_client, ACCESS_TOKEN).await.unwrap();
680
681 assert_eq!(result.id, Some(SEND_ID.to_string()));
682 assert_eq!(result.type_, Some(crate::SendType::File));
683 assert_eq!(result.name, Some("encrypted-name".to_string()));
684 assert!(result.text.is_none());
685 let file = result.file.expect("file variant should be populated");
686 assert_eq!(file.id, Some(FILE_ID.to_string()));
687 assert_eq!(file.file_name, Some("encrypted-file-name".to_string()));
688 assert_eq!(file.size, Some("4200".to_string()));
689 assert_eq!(file.size_name, Some("4.2 KB".to_string()));
690 assert_eq!(result.expiration_date, None);
691 assert_eq!(result.creator_identifier, None);
692 }
693
694 #[tokio::test]
695 async fn test_access_send_http_error() {
696 let api_client = ApiClient::new_mocked(|mock| {
697 mock.sends_api
698 .expect_access_using_auth()
699 .returning(|_token| {
700 Err(bitwarden_api_api::ApiError::Io(std::io::Error::other(
701 "Simulated error",
702 )))
703 })
704 .once();
705 });
706
707 let result = access_send(&api_client, ACCESS_TOKEN).await;
708
709 assert!(matches!(result.unwrap_err(), AccessSendError::Api(_)));
710 }
711
712 #[tokio::test]
713 async fn test_access_send_404_is_not_found() {
714 let api_client = ApiClient::new_mocked(|mock| {
715 mock.sends_api
716 .expect_access_using_auth()
717 .returning(|_token| Err(not_found_response()))
718 .once();
719 });
720
721 let result = access_send(&api_client, ACCESS_TOKEN).await;
722
723 assert!(matches!(result.unwrap_err(), AccessSendError::NotFound));
724 }
725
726 #[tokio::test]
727 async fn test_access_send_other_status_stays_api_error() {
728 let api_client = ApiClient::new_mocked(|mock| {
729 mock.sends_api
730 .expect_access_using_auth()
731 .returning(|_token| {
732 Err(bitwarden_api_api::ApiError::Response(
733 bitwarden_api_api::ResponseContent {
734 status: reqwest::StatusCode::INTERNAL_SERVER_ERROR,
735 message: "boom".to_string(),
736 },
737 ))
738 })
739 .once();
740 });
741
742 let result = access_send(&api_client, ACCESS_TOKEN).await;
743
744 assert!(matches!(result.unwrap_err(), AccessSendError::Api(_)));
745 }
746
747 fn not_found_response() -> bitwarden_api_api::ApiError {
748 bitwarden_api_api::ApiError::Response(bitwarden_api_api::ResponseContent {
749 status: reqwest::StatusCode::NOT_FOUND,
750 message: "Not Found".to_string(),
751 })
752 }
753
754 #[tokio::test]
757 async fn test_get_file_download_data() {
758 let api_client = ApiClient::new_mocked(|mock| {
759 mock.sends_api
760 .expect_get_send_file_download_data_using_auth()
761 .returning(|file_id, token| {
762 assert_eq!(file_id, FILE_ID);
763 assert_eq!(token, ACCESS_TOKEN);
764 Ok(SendFileDownloadDataResponseModel {
765 object: Some("send-fileDownload".to_string()),
766 id: Some(FILE_ID.to_string()),
767 url: Some("https://example.com/download".to_string()),
768 })
769 })
770 .once();
771 });
772
773 let result = get_file_download_data(&api_client, FILE_ID, ACCESS_TOKEN)
774 .await
775 .unwrap();
776
777 assert_eq!(result.id, Some(FILE_ID.to_string()));
778 assert_eq!(result.url, Some("https://example.com/download".to_string()));
779 }
780
781 #[tokio::test]
782 async fn test_get_file_download_data_http_error() {
783 let api_client = ApiClient::new_mocked(|mock| {
784 mock.sends_api
785 .expect_get_send_file_download_data_using_auth()
786 .returning(|_file_id, _token| {
787 Err(bitwarden_api_api::ApiError::Io(std::io::Error::other(
788 "Simulated error",
789 )))
790 })
791 .once();
792 });
793
794 let result = get_file_download_data(&api_client, FILE_ID, ACCESS_TOKEN).await;
795
796 assert!(matches!(
797 result.unwrap_err(),
798 GetFileDownloadDataError::Api(_)
799 ));
800 }
801
802 #[tokio::test]
803 async fn test_get_file_download_data_404_is_not_found() {
804 let api_client = ApiClient::new_mocked(|mock| {
805 mock.sends_api
806 .expect_get_send_file_download_data_using_auth()
807 .returning(|_file_id, _token| Err(not_found_response()))
808 .once();
809 });
810
811 let result = get_file_download_data(&api_client, FILE_ID, ACCESS_TOKEN).await;
812
813 assert!(matches!(
814 result.unwrap_err(),
815 GetFileDownloadDataError::NotFound
816 ));
817 }
818
819 mod send_access_key {
822 use bitwarden_core::key_management::create_test_crypto_with_user_key;
826 use bitwarden_crypto::{OctetStreamBytes, PrimitiveEncryptable as _, SymmetricCryptoKey};
827 use bitwarden_vault::CipherId;
828
829 use crate::{
830 Send, SendAccessDecryptError, SendAccessFileResponse, SendAccessKey,
831 SendAccessKeyError, SendAccessResponse, SendAccessTextResponse, SendAuthType,
832 SendClient, SendFileView, SendTextView, SendType, SendView,
833 access::{SendAccessItemMetadataResponse, SendAccessItemResponse},
834 send::tests::{TEST_ITEM_ID, TEST_VECTOR_ITEM_SEND_DATA},
835 };
836
837 const URL_KEY: &str = "Pgui0FK85cNhBGWHAlBHBw";
840 const USER_KEY: &str = "bYCsk857hl8QJJtxyRK65tjUrbxKC4aDifJpsml+NIv4W9cVgFvi3qVD+yJTUU2T4UwNKWYtt9pqWf7Q+2WCCg==";
841
842 fn user_key() -> SymmetricCryptoKey {
843 USER_KEY
844 .to_string()
845 .try_into()
846 .expect("valid test user key")
847 }
848
849 fn encrypt_send(view: SendView) -> Send {
853 create_test_crypto_with_user_key(user_key())
854 .encrypt(view)
855 .expect("send encrypts")
856 }
857
858 fn text_send_view(text: &str, name: &str) -> SendView {
859 SendView {
860 id: "3d80dd72-2d14-4f26-812c-b0f0018aa144".parse().ok(),
861 access_id: Some("ct2APRQtJk-BLLDwAYqhRA".to_owned()),
862 name: name.to_owned(),
863 notes: None,
864 key: Some(URL_KEY.to_owned()),
865 new_password: None,
866 has_password: false,
867 r#type: SendType::Text,
868 file: None,
869 text: Some(SendTextView {
870 text: Some(text.to_owned()),
871 hidden: false,
872 }),
873 data: None,
874 max_access_count: None,
875 access_count: 0,
876 disabled: false,
877 hide_email: false,
878 revision_date: "2024-01-07T23:56:48.207363Z".parse().unwrap(),
879 deletion_date: "2024-01-14T23:56:48Z".parse().unwrap(),
880 expiration_date: None,
881 emails: Vec::new(),
882 auth_type: crate::AuthType::None,
883 }
884 }
885
886 fn text_send_response(send: &Send) -> SendAccessResponse {
889 SendAccessResponse {
890 id: Some("access-id".to_owned()),
891 type_: Some(SendType::Text),
892 name: Some(send.name.to_string()),
893 text: Some(SendAccessTextResponse {
894 text: send
895 .text
896 .as_ref()
897 .and_then(|t| t.text.as_ref())
898 .map(|t| t.to_string()),
899 hidden: false,
900 }),
901 file: None,
902 data: None,
903 expiration_date: None,
904 creator_identifier: None,
905 }
906 }
907
908 #[test]
915 fn decrypts_ciphertext_produced_by_the_authenticated_path() {
916 let send = encrypt_send(text_send_view("This is a test", "Test"));
917 let response = text_send_response(&send);
918
919 let access_key = SendAccessKey::from_url_b64(URL_KEY).expect("key parses");
920 let view = access_key.decrypt_response(response).expect("decrypts");
921
922 assert_eq!(view.name.as_deref(), Some("Test"));
923 assert_eq!(
924 view.text.expect("text present").text.as_deref(),
925 Some("This is a test")
926 );
927 }
928
929 #[test]
930 fn decrypts_file_name_produced_by_the_authenticated_path() {
931 let mut view = text_send_view("unused", "File Send");
932 view.r#type = SendType::File;
933 view.text = None;
934 view.file = Some(SendFileView {
935 id: Some("file-id".to_owned()),
936 file_name: "secrets.txt".to_owned(),
937 size: Some("11".to_owned()),
938 size_name: Some("11 B".to_owned()),
939 });
940 let send = encrypt_send(view);
941 let file = send.file.expect("file present");
942
943 let response = SendAccessResponse {
944 id: Some("access-id".to_owned()),
945 type_: Some(SendType::File),
946 name: Some(send.name.to_string()),
947 text: None,
948 file: Some(SendAccessFileResponse {
949 id: file.id.clone(),
950 file_name: Some(file.file_name.to_string()),
951 size: file.size.clone(),
952 size_name: file.size_name.clone(),
953 }),
954 data: None,
955 expiration_date: None,
956 creator_identifier: None,
957 };
958
959 let access_key = SendAccessKey::from_url_b64(URL_KEY).expect("key parses");
960 let view = access_key.decrypt_response(response).expect("decrypts");
961
962 let decrypted_file = view.file.expect("file present");
963 assert_eq!(decrypted_file.file_name.as_deref(), Some("secrets.txt"));
964 assert_eq!(decrypted_file.size.as_deref(), Some("11"));
965 assert_eq!(decrypted_file.id.as_deref(), Some("file-id"));
966 assert_eq!(view.name.as_deref(), Some("File Send"));
967 }
968
969 #[test]
974 fn decrypt_file_buffer_round_trips_with_the_authenticated_path() {
975 let plaintext = b"file send contents".to_vec();
976
977 let crypto = create_test_crypto_with_user_key(user_key());
978 let mut ctx = crypto.context();
979 let raw_key = bitwarden_encoding::B64Url::try_from(URL_KEY)
980 .expect("url key decodes")
981 .into_bytes();
982 let send_key = Send::derive_shareable_key(&mut ctx, &raw_key).expect("key derives");
983 let encrypted = OctetStreamBytes::from(plaintext.clone())
984 .encrypt(&mut ctx, send_key)
985 .expect("buffer encrypts")
986 .to_buffer()
987 .expect("buffer serializes");
988
989 let access_key = SendAccessKey::from_url_b64(URL_KEY).expect("key parses");
990 let decrypted = access_key
991 .decrypt_file_buffer(&encrypted)
992 .expect("buffer decrypts");
993
994 assert_eq!(decrypted, plaintext);
995 }
996
997 #[test]
1002 fn hash_password_b64_matches_send_auth_type_auth_data() {
1003 let raw_key = bitwarden_encoding::B64Url::try_from(URL_KEY)
1004 .expect("url key decodes")
1005 .into_bytes();
1006
1007 let (created_hash, emails) = SendAuthType::Password {
1008 password: "hunter2".to_owned(),
1009 }
1010 .auth_data(&raw_key);
1011 assert_eq!(emails, None);
1012
1013 let access_key = SendAccessKey::from_url_b64(URL_KEY).expect("key parses");
1014 let receive_hash = access_key.hash_password_b64("hunter2");
1015
1016 assert_eq!(
1017 created_hash,
1018 Some(receive_hash),
1019 "receive's password hash must match the one `bw send create` stored"
1020 );
1021 }
1022
1023 #[test]
1024 fn hash_password_b64_is_salted_with_the_send_key() {
1025 let a = SendAccessKey::from_url_b64(URL_KEY).expect("key parses");
1028 let b = SendAccessKey::from_url_b64("AAAAAAAAAAAAAAAAAAAAAA").expect("key parses");
1029 assert_ne!(
1030 a.hash_password_b64("hunter2"),
1031 b.hash_password_b64("hunter2")
1032 );
1033 }
1034
1035 #[test]
1036 fn from_url_b64_accepts_padded_and_unpadded() {
1037 let unpadded = SendAccessKey::from_url_b64(URL_KEY).expect("unpadded parses");
1040 let padded =
1041 SendAccessKey::from_url_b64(&format!("{URL_KEY}==")).expect("padded parses");
1042 assert_eq!(
1043 unpadded.hash_password_b64("p"),
1044 padded.hash_password_b64("p"),
1045 "padded and unpadded forms must derive the same key"
1046 );
1047 }
1048
1049 #[test]
1050 fn from_url_b64_rejects_invalid_base64() {
1051 assert!(matches!(
1052 SendAccessKey::from_url_b64("not valid base64!"),
1053 Err(SendAccessKeyError::InvalidEncoding)
1054 ));
1055 }
1056
1057 #[test]
1058 fn from_url_b64_rejects_wrong_length() {
1059 for bad in ["AAAAAAAAAAA", "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"] {
1062 assert!(
1063 matches!(
1064 SendAccessKey::from_url_b64(bad),
1065 Err(SendAccessKeyError::InvalidLength)
1066 ),
1067 "expected InvalidLength for {bad:?}"
1068 );
1069 }
1070 assert!(matches!(
1071 SendAccessKey::from_url_b64(""),
1072 Err(SendAccessKeyError::InvalidLength)
1073 ));
1074 }
1075
1076 #[test]
1080 fn decrypt_response_tolerates_absent_fields() {
1081 let response = SendAccessResponse {
1082 id: None,
1083 type_: None,
1084 name: None,
1085 text: Some(SendAccessTextResponse {
1086 text: None,
1087 hidden: true,
1088 }),
1089 file: None,
1090 data: None,
1091 expiration_date: None,
1092 creator_identifier: None,
1093 };
1094
1095 let access_key = SendAccessKey::from_url_b64(URL_KEY).expect("key parses");
1096 let view = access_key.decrypt_response(response).expect("decrypts");
1097
1098 assert_eq!(view.name, None);
1099 assert_eq!(view.type_, None);
1100 let text = view.text.expect("text block present");
1101 assert_eq!(text.text, None);
1102 assert!(text.hidden);
1103 }
1104
1105 #[test]
1106 fn decrypt_response_restores_item_id_from_metadata() {
1107 let item_id: CipherId = TEST_ITEM_ID.parse().unwrap();
1108 let response = SendAccessResponse {
1109 id: None,
1110 type_: Some(SendType::Item),
1111 name: None,
1112 text: None,
1113 file: None,
1114 data: Some(SendAccessItemResponse {
1115 encryption_version: None,
1116 data: Some(TEST_VECTOR_ITEM_SEND_DATA.to_owned()),
1117 metadata: SendAccessItemMetadataResponse {
1118 item_id,
1119 creation_date: Default::default(),
1120 revision_date: Default::default(),
1121 folder_name: None,
1122 collection_names: None,
1123 organization_name: None,
1124 },
1125 }),
1126 expiration_date: None,
1127 creator_identifier: None,
1128 };
1129
1130 let access_key = SendAccessKey::from_url_b64(URL_KEY).expect("key parses");
1131 let view = access_key.decrypt_response(response).expect("decrypts");
1132
1133 let cipher = view.data.and_then(|d| d.data).expect("item present");
1134 assert_eq!(cipher.id, Some(item_id));
1135 }
1136
1137 #[test]
1138 fn decrypt_response_errors_on_a_key_that_does_not_match() {
1139 let send = encrypt_send(text_send_view("This is a test", "Test"));
1140 let response = SendAccessResponse {
1141 id: None,
1142 type_: Some(SendType::Text),
1143 name: Some(send.name.to_string()),
1144 text: None,
1145 file: None,
1146 data: None,
1147 expiration_date: None,
1148 creator_identifier: None,
1149 };
1150
1151 let wrong_key =
1153 SendAccessKey::from_url_b64("AAAAAAAAAAAAAAAAAAAAAA").expect("key parses");
1154 assert!(wrong_key.decrypt_response(response).is_err());
1155 }
1156
1157 #[test]
1158 fn decrypt_response_errors_on_a_malformed_enc_string() {
1159 let response = SendAccessResponse {
1160 id: None,
1161 type_: Some(SendType::Text),
1162 name: Some("this is not an EncString".to_owned()),
1163 text: None,
1164 file: None,
1165 data: None,
1166 expiration_date: None,
1167 creator_identifier: None,
1168 };
1169
1170 let access_key = SendAccessKey::from_url_b64(URL_KEY).expect("key parses");
1171 assert!(access_key.decrypt_response(response).is_err());
1172 }
1173
1174 #[test]
1178 fn send_access_view_serializes_in_camel_case() {
1179 let view = crate::SendAccessView {
1180 id: Some("access-id".to_owned()),
1181 type_: Some(SendType::File),
1182 name: Some("name".to_owned()),
1183 text: None,
1184 file: Some(crate::SendAccessFileView {
1185 id: Some("file-id".to_owned()),
1186 file_name: Some("secrets.txt".to_owned()),
1187 size: Some("11".to_owned()),
1188 size_name: Some("11 B".to_owned()),
1189 }),
1190 data: None,
1191 expiration_date: None,
1192 creator_identifier: None,
1193 };
1194
1195 let json = serde_json::to_value(&view).expect("serializes");
1196 assert_eq!(json["type"], serde_json::json!(1));
1197 assert_eq!(json["file"]["fileName"], serde_json::json!("secrets.txt"));
1198 assert_eq!(json["file"]["sizeName"], serde_json::json!("11 B"));
1199 assert_eq!(json["creatorIdentifier"], serde_json::Value::Null);
1200 }
1201
1202 #[test]
1203 fn decrypt_send_access_success() {
1204 let send = encrypt_send(text_send_view("This is a test", "Test"));
1205 let view =
1206 SendClient::decrypt_send_access(URL_KEY.to_owned(), text_send_response(&send))
1207 .expect("decrypts");
1208
1209 assert_eq!(view.name.as_deref(), Some("Test"));
1210 assert_eq!(
1211 view.text.expect("text present").text.as_deref(),
1212 Some("This is a test")
1213 );
1214 }
1215
1216 #[test]
1217 fn decrypt_send_access_malformed_b64() {
1218 let response = SendAccessResponse {
1219 id: Some("access-id".to_owned()),
1220 type_: Some(SendType::Text),
1221 name: Some("Test".to_owned()),
1222 text: None,
1223 file: None,
1224 data: None,
1225 expiration_date: None,
1226 creator_identifier: None,
1227 };
1228
1229 let result = SendClient::decrypt_send_access("not valid base64!".to_owned(), response);
1230
1231 assert!(matches!(
1232 result.unwrap_err(),
1233 SendAccessDecryptError::Key(SendAccessKeyError::InvalidEncoding)
1234 ));
1235 }
1236 }
1237}