1use bitwarden_api_api::models::{
2 SendDataModel, SendFileModel, SendItemMetadataModel, SendResponseModel, SendTextModel,
3 SendWithIdRequestModel,
4};
5use bitwarden_core::{
6 key_management::{KeySlotIds, SymmetricKeySlotId},
7 require,
8};
9use bitwarden_crypto::{
10 CompositeEncryptable, CryptoError, Decryptable, EncString, IdentifyKey, KeyStoreContext,
11 OctetStreamBytes, PrimitiveEncryptable, generate_random_bytes,
12};
13use bitwarden_encoding::{B64, B64Url};
14use bitwarden_uuid::uuid_newtype;
15use bitwarden_vault::{CipherId, CipherView};
16use chrono::{DateTime, Utc};
17use serde::{Deserialize, Serialize};
18use serde_repr::{Deserialize_repr, Serialize_repr};
19use thiserror::Error;
20#[cfg(feature = "wasm")]
21use wasm_bindgen::prelude::*;
22use zeroize::Zeroizing;
23
24use crate::{SendParseError, access::SEND_KEY_LEN, error::SendItemDeserializationFailureError};
25pub const SEND_ITERATIONS: u32 = 100_000;
26pub const DEFAULT_SEND_ENCRYPTION: SendEncryptionType = SendEncryptionType::V1;
27
28uuid_newtype!(pub SendId);
29
30#[derive(Debug, Error)]
32#[error("Email authentication requires at least one email address")]
33pub struct EmptyEmailListError;
34
35#[derive(Serialize, Deserialize, Debug, Clone)]
37#[serde(rename_all = "camelCase", deny_unknown_fields)]
38#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
39#[bitwarden_ffi::wasm_record]
40pub struct SendFile {
41 pub id: Option<String>,
43 pub file_name: EncString,
45 pub size: Option<String>,
47 pub size_name: Option<String>,
49}
50
51#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
53#[serde(rename_all = "camelCase", deny_unknown_fields)]
54#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
55#[bitwarden_ffi::wasm_record]
56pub struct SendFileView {
57 pub id: Option<String>,
59 pub file_name: String,
61 pub size: Option<String>,
63 pub size_name: Option<String>,
65}
66
67#[derive(Serialize, Deserialize, Debug, Clone)]
69#[serde(rename_all = "camelCase", deny_unknown_fields)]
70#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
71#[bitwarden_ffi::wasm_record]
72pub struct SendText {
73 pub text: Option<EncString>,
74 pub hidden: bool,
75}
76
77#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
79#[serde(rename_all = "camelCase", deny_unknown_fields)]
80#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
81#[bitwarden_ffi::wasm_record]
82pub struct SendItemView {
83 pub data: CipherView,
85 pub metadata: SendItemMetadataView,
88}
89
90#[derive(Serialize, Deserialize, Debug, Clone)]
92#[serde(rename_all = "camelCase", deny_unknown_fields)]
93#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
94#[bitwarden_ffi::wasm_record]
95pub struct SendItem {
96 pub encryption_version: SendEncryptionType,
97 pub data: String,
99 pub metadata: SendItemMetadata,
102}
103
104#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
106#[serde(rename_all = "camelCase", deny_unknown_fields)]
107#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
108#[bitwarden_ffi::wasm_record]
109pub struct SendItemMetadataView {
110 pub item_id: CipherId,
112 pub folder_name: Option<String>,
114 pub collection_names: Option<Vec<String>>,
116 pub organization_name: Option<String>,
118 pub creation_date: Option<DateTime<Utc>>,
120 pub revision_date: Option<DateTime<Utc>>,
122}
123
124#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
126#[serde(rename_all = "camelCase", deny_unknown_fields)]
127#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
128#[bitwarden_ffi::wasm_record]
129pub struct SendItemMetadata {
130 pub item_id: CipherId,
132 pub folder_name: Option<EncString>,
134 pub collection_names: Option<Vec<EncString>>,
136 pub organization_name: Option<String>,
138 pub creation_date: Option<DateTime<Utc>>,
140 pub revision_date: Option<DateTime<Utc>>,
142}
143
144#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
146#[serde(rename_all = "camelCase", deny_unknown_fields)]
147#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
148#[bitwarden_ffi::wasm_record]
149pub struct SendTextView {
150 pub text: Option<String>,
152 pub hidden: bool,
154}
155
156#[derive(Clone, Copy, Serialize_repr, Deserialize_repr, Debug, PartialEq)]
158#[repr(u8)]
159#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
160#[bitwarden_ffi::wasm_object]
161pub enum SendType {
162 Text = 0,
164 File = 1,
166 Item = 2,
168}
169
170#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize_repr, Deserialize_repr)]
172#[repr(u8)]
173#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
174#[bitwarden_ffi::wasm_object]
175pub enum AuthType {
176 Email = 0,
178
179 Password = 1,
181
182 None = 2,
184}
185
186#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize_repr, Deserialize_repr)]
188#[repr(u8)]
189#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
190#[bitwarden_ffi::wasm_object]
191pub enum SendEncryptionType {
192 V1 = 1,
194}
195
196#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
199#[serde(tag = "type", rename_all = "camelCase")]
200#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
201#[bitwarden_ffi::wasm_record]
202pub enum SendAuthType {
203 None,
205 Password {
208 password: String,
210 },
211 HashedPassword {
217 #[serde(rename = "keyB64")]
219 key_b64: String,
220 },
221 Emails {
223 emails: Vec<String>,
225 },
226}
227
228impl SendAuthType {
229 pub fn from_plaintext_password(password: String) -> Self {
232 SendAuthType::Password { password }
233 }
234
235 pub fn from_hashed_password(key_b64: String) -> Self {
239 SendAuthType::HashedPassword { key_b64 }
240 }
241
242 pub fn auth_type(&self) -> AuthType {
244 match self {
245 SendAuthType::None => AuthType::None,
246 SendAuthType::Password { .. } | SendAuthType::HashedPassword { .. } => {
247 AuthType::Password
248 }
249 SendAuthType::Emails { .. } => AuthType::Email,
250 }
251 }
252
253 pub(crate) fn validate(&self) -> Result<(), EmptyEmailListError> {
256 if let SendAuthType::Emails { emails } = self
257 && emails.is_empty()
258 {
259 return Err(EmptyEmailListError);
260 }
261 Ok(())
262 }
263
264 pub(crate) fn auth_data(&self, k: &[u8]) -> (Option<String>, Option<String>) {
268 match self {
269 SendAuthType::Password { password } => {
270 let hashed = bitwarden_crypto::pbkdf2(password.as_bytes(), k, SEND_ITERATIONS);
271 (Some(B64::from(hashed.as_slice()).to_string()), None)
272 }
273 SendAuthType::HashedPassword { key_b64 } => (Some(key_b64.clone()), None),
274 SendAuthType::Emails { emails } => {
275 let emails_str = if emails.is_empty() {
276 None
277 } else {
278 Some(emails.join(","))
279 };
280 (None, emails_str)
281 }
282 SendAuthType::None => (None, None),
283 }
284 }
285}
286
287#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
289#[bitwarden_ffi::wasm_record]
290pub enum SendViewType {
291 File(SendFileView),
293 Text(SendTextView),
295 Item(Box<SendItemView>),
297}
298
299type SendApiModels = (
301 bitwarden_api_api::models::SendType,
302 Option<Box<bitwarden_api_api::models::SendFileModel>>,
303 Option<Box<bitwarden_api_api::models::SendTextModel>>,
304 Option<Box<bitwarden_api_api::models::SendDataModel>>,
305);
306
307impl CompositeEncryptable<KeySlotIds, SymmetricKeySlotId, SendApiModels> for SendViewType {
308 fn encrypt_composite(
309 &self,
310 ctx: &mut KeyStoreContext<KeySlotIds>,
311 key: SymmetricKeySlotId,
312 ) -> Result<SendApiModels, CryptoError> {
313 match self {
314 SendViewType::File(f) => Ok((
315 bitwarden_api_api::models::SendType::File,
316 Some(Box::new(bitwarden_api_api::models::SendFileModel {
317 id: f.id.clone(),
318 file_name: Some(f.file_name.encrypt(ctx, key)?.to_string()),
319 size: f.size.clone(),
320 size_name: f.size_name.clone(),
321 })),
322 None,
323 None,
324 )),
325 SendViewType::Text(t) => Ok((
326 bitwarden_api_api::models::SendType::Text,
327 None,
328 Some(Box::new(bitwarden_api_api::models::SendTextModel {
329 text: t
330 .text
331 .as_ref()
332 .map(|txt| txt.encrypt(ctx, key))
333 .transpose()?
334 .map(|e| e.to_string()),
335 hidden: Some(t.hidden),
336 })),
337 None,
338 )),
339 SendViewType::Item(i) => {
340 let encrypted = i.encrypt_composite(ctx, key)?;
341 Ok((
342 bitwarden_api_api::models::SendType::Item,
343 None,
344 None,
345 Some(Box::new(encrypted.into())),
346 ))
347 }
348 }
349 }
350}
351
352#[allow(missing_docs)]
353#[derive(Serialize, Deserialize, Debug, Clone)]
354#[serde(rename_all = "camelCase", deny_unknown_fields)]
355#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
356#[bitwarden_ffi::wasm_record]
357pub struct Send {
358 pub id: Option<SendId>,
359 pub access_id: Option<String>,
360
361 pub name: EncString,
362 pub notes: Option<EncString>,
363 pub key: EncString,
364 pub password: Option<String>,
365
366 pub r#type: SendType,
367 pub file: Option<SendFile>,
368 pub text: Option<SendText>,
369 pub data: Option<SendItem>,
370
371 pub max_access_count: Option<u32>,
372 pub access_count: u32,
373 pub disabled: bool,
374 pub hide_email: bool,
375
376 pub revision_date: DateTime<Utc>,
377 pub deletion_date: DateTime<Utc>,
378 pub expiration_date: Option<DateTime<Utc>>,
379
380 pub emails: Option<String>,
385 pub auth_type: AuthType,
386}
387
388bitwarden_state::register_repository_item!(SendId => Send, "Send");
389
390impl From<Send> for SendWithIdRequestModel {
391 fn from(send: Send) -> Self {
392 let file_length = send.file.as_ref().and_then(|file| {
393 file.size
394 .as_deref()
395 .and_then(|size| size.parse::<i64>().ok())
396 });
397
398 SendWithIdRequestModel {
399 r#type: Some(send.r#type.into()),
400 auth_type: Some(send.auth_type.into()),
401 file_length,
402 name: Some(send.name.to_string()),
403 notes: send.notes.map(|notes| notes.to_string()),
404 key: send.key.to_string(),
405 max_access_count: send.max_access_count.map(|count| count as i32),
406 expiration_date: send.expiration_date.map(|date| date.to_rfc3339()),
407 deletion_date: send.deletion_date.to_rfc3339(),
408 file: send.file.map(|file| Box::new(file.into())),
409 text: send.text.map(|text| Box::new(text.into())),
410 data: send.data.map(|data| Box::new(data.into())),
411 password: send.password,
412 emails: send.emails,
413 disabled: send.disabled,
414 hide_email: Some(send.hide_email),
415 id: send
416 .id
417 .expect("SendWithIdRequestModel conversion requires send id")
418 .into(),
419 }
420 }
421}
422
423#[allow(missing_docs)]
424#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
425#[serde(rename_all = "camelCase", deny_unknown_fields)]
426#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
427#[bitwarden_ffi::wasm_record]
428pub struct SendView {
429 pub id: Option<SendId>,
430 pub access_id: Option<String>,
431
432 pub name: String,
433 pub notes: Option<String>,
434 pub key: Option<String>,
436 pub new_password: Option<String>,
440 pub has_password: bool,
443
444 pub r#type: SendType,
445 pub file: Option<SendFileView>,
446 pub text: Option<SendTextView>,
447 pub data: Option<SendItemView>,
448
449 pub max_access_count: Option<u32>,
450 pub access_count: u32,
451 pub disabled: bool,
452 pub hide_email: bool,
453
454 pub revision_date: DateTime<Utc>,
455 pub deletion_date: DateTime<Utc>,
456 pub expiration_date: Option<DateTime<Utc>>,
457
458 pub emails: Vec<String>,
463 pub auth_type: AuthType,
464}
465
466#[allow(missing_docs)]
467#[derive(Serialize, Deserialize, Debug)]
468#[serde(rename_all = "camelCase", deny_unknown_fields)]
469#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
470#[bitwarden_ffi::wasm_record]
471pub struct SendListView {
472 pub id: Option<SendId>,
473 pub access_id: Option<String>,
474
475 pub name: String,
476
477 pub r#type: SendType,
478 pub disabled: bool,
479
480 pub revision_date: DateTime<Utc>,
481 pub deletion_date: DateTime<Utc>,
482 pub expiration_date: Option<DateTime<Utc>>,
483
484 pub auth_type: AuthType,
485}
486
487impl Send {
488 #[allow(missing_docs)]
489 pub fn get_key(
490 ctx: &mut KeyStoreContext<KeySlotIds>,
491 send_key: &EncString,
492 enc_key: SymmetricKeySlotId,
493 ) -> Result<SymmetricKeySlotId, CryptoError> {
494 let key: Vec<u8> = send_key.decrypt(ctx, enc_key)?;
495 Self::derive_shareable_key(ctx, &key)
496 }
497
498 pub(crate) fn derive_shareable_key(
499 ctx: &mut KeyStoreContext<KeySlotIds>,
500 key: &[u8],
501 ) -> Result<SymmetricKeySlotId, CryptoError> {
502 let key = Zeroizing::new(key.try_into().map_err(|_| CryptoError::InvalidKeyLen)?);
503 ctx.derive_shareable_key(key, "send", Some("send"))
504 }
505}
506
507impl IdentifyKey<SymmetricKeySlotId> for Send {
508 fn key_identifier(&self) -> SymmetricKeySlotId {
509 SymmetricKeySlotId::User
510 }
511}
512
513impl IdentifyKey<SymmetricKeySlotId> for SendView {
514 fn key_identifier(&self) -> SymmetricKeySlotId {
515 SymmetricKeySlotId::User
516 }
517}
518
519impl Decryptable<KeySlotIds, SymmetricKeySlotId, SendTextView> for SendText {
520 fn decrypt(
521 &self,
522 ctx: &mut KeyStoreContext<KeySlotIds>,
523 key: SymmetricKeySlotId,
524 ) -> Result<SendTextView, CryptoError> {
525 Ok(SendTextView {
526 text: self.text.decrypt(ctx, key)?,
527 hidden: self.hidden,
528 })
529 }
530}
531
532impl CompositeEncryptable<KeySlotIds, SymmetricKeySlotId, SendText> for SendTextView {
533 fn encrypt_composite(
534 &self,
535 ctx: &mut KeyStoreContext<KeySlotIds>,
536 key: SymmetricKeySlotId,
537 ) -> Result<SendText, CryptoError> {
538 Ok(SendText {
539 text: self.text.encrypt(ctx, key)?,
540 hidden: self.hidden,
541 })
542 }
543}
544
545impl Decryptable<KeySlotIds, SymmetricKeySlotId, SendFileView> for SendFile {
546 fn decrypt(
547 &self,
548 ctx: &mut KeyStoreContext<KeySlotIds>,
549 key: SymmetricKeySlotId,
550 ) -> Result<SendFileView, CryptoError> {
551 Ok(SendFileView {
552 id: self.id.clone(),
553 file_name: self.file_name.decrypt(ctx, key)?,
554 size: self.size.clone(),
555 size_name: self.size_name.clone(),
556 })
557 }
558}
559
560impl CompositeEncryptable<KeySlotIds, SymmetricKeySlotId, SendFile> for SendFileView {
561 fn encrypt_composite(
562 &self,
563 ctx: &mut KeyStoreContext<KeySlotIds>,
564 key: SymmetricKeySlotId,
565 ) -> Result<SendFile, CryptoError> {
566 Ok(SendFile {
567 id: self.id.clone(),
568 file_name: self.file_name.encrypt(ctx, key)?,
569 size: self.size.clone(),
570 size_name: self.size_name.clone(),
571 })
572 }
573}
574
575impl Decryptable<KeySlotIds, SymmetricKeySlotId, SendItemView> for SendItem {
576 fn decrypt(
577 &self,
578 ctx: &mut KeyStoreContext<KeySlotIds>,
579 key: SymmetricKeySlotId,
580 ) -> Result<SendItemView, CryptoError> {
581 let mut data = CipherView::unseal_blob_for_item_sends(&self.data, ctx, key)?;
582 data.id = Some(self.metadata.item_id);
584 if let Some(creation_date) = self.metadata.creation_date {
585 data.creation_date = creation_date;
586 }
587 if let Some(revision_date) = self.metadata.revision_date {
588 data.revision_date = revision_date;
589 }
590 Ok(SendItemView {
591 data,
592 metadata: self.metadata.clone().decrypt(ctx, key)?,
593 })
594 }
595}
596
597impl CompositeEncryptable<KeySlotIds, SymmetricKeySlotId, SendItem> for SendItemView {
598 fn encrypt_composite(
599 &self,
600 ctx: &mut KeyStoreContext<KeySlotIds>,
601 key: SymmetricKeySlotId,
602 ) -> Result<SendItem, CryptoError> {
603 Ok(SendItem {
604 encryption_version: DEFAULT_SEND_ENCRYPTION,
605 data: self.data.seal_blob_for_item_sends(ctx, key)?,
606 metadata: self.metadata.encrypt_composite(ctx, key)?,
607 })
608 }
609}
610
611impl Decryptable<KeySlotIds, SymmetricKeySlotId, SendItemMetadataView> for SendItemMetadata {
612 fn decrypt(
613 &self,
614 ctx: &mut KeyStoreContext<KeySlotIds>,
615 key: SymmetricKeySlotId,
616 ) -> Result<SendItemMetadataView, CryptoError> {
617 Ok(SendItemMetadataView {
618 item_id: self.item_id,
619 folder_name: self.folder_name.decrypt(ctx, key)?,
620 collection_names: self
621 .collection_names
622 .as_ref()
623 .map(|cols| cols.iter().map(|c| c.decrypt(ctx, key)).collect())
624 .transpose()?,
625 organization_name: self.organization_name.clone(),
626 creation_date: self.creation_date,
627 revision_date: self.revision_date,
628 })
629 }
630}
631
632impl CompositeEncryptable<KeySlotIds, SymmetricKeySlotId, SendItemMetadata>
633 for SendItemMetadataView
634{
635 fn encrypt_composite(
636 &self,
637 ctx: &mut KeyStoreContext<KeySlotIds>,
638 key: SymmetricKeySlotId,
639 ) -> Result<SendItemMetadata, CryptoError> {
640 Ok(SendItemMetadata {
641 item_id: self.item_id,
642 folder_name: self.folder_name.encrypt(ctx, key)?,
643 collection_names: self
644 .collection_names
645 .as_ref()
646 .map(|cols| cols.iter().map(|c| c.encrypt(ctx, key)).collect())
647 .transpose()?,
648 organization_name: self.organization_name.clone(),
649 creation_date: self.creation_date,
650 revision_date: self.revision_date,
651 })
652 }
653}
654
655impl Decryptable<KeySlotIds, SymmetricKeySlotId, SendView> for Send {
656 fn decrypt(
657 &self,
658 ctx: &mut KeyStoreContext<KeySlotIds>,
659 key: SymmetricKeySlotId,
660 ) -> Result<SendView, CryptoError> {
661 let k: Vec<u8> = self.key.decrypt(ctx, key)?;
665 let key = Send::derive_shareable_key(ctx, &k)?;
666
667 Ok(SendView {
668 id: self.id,
669 access_id: self.access_id.clone(),
670
671 name: self.name.decrypt(ctx, key).ok().unwrap_or_default(),
672 notes: self.notes.decrypt(ctx, key).ok().flatten(),
673 key: Some(B64Url::from(k).to_string()),
674 new_password: None,
675 has_password: self.password.is_some(),
676
677 r#type: self.r#type,
678 file: self.file.decrypt(ctx, key).ok().flatten(),
679 text: self.text.decrypt(ctx, key).ok().flatten(),
680 data: self.data.decrypt(ctx, key).ok().flatten(),
681
682 max_access_count: self.max_access_count,
683 access_count: self.access_count,
684 disabled: self.disabled,
685 hide_email: self.hide_email,
686
687 revision_date: self.revision_date,
688 deletion_date: self.deletion_date,
689 expiration_date: self.expiration_date,
690
691 emails: self
692 .emails
693 .as_deref()
694 .unwrap_or_default()
695 .split(',')
696 .map(|e| e.trim())
697 .filter(|e| !e.is_empty())
698 .map(String::from)
699 .collect(),
700 auth_type: self.auth_type,
701 })
702 }
703}
704
705impl Decryptable<KeySlotIds, SymmetricKeySlotId, SendListView> for Send {
706 fn decrypt(
707 &self,
708 ctx: &mut KeyStoreContext<KeySlotIds>,
709 key: SymmetricKeySlotId,
710 ) -> Result<SendListView, CryptoError> {
711 let key = Send::get_key(ctx, &self.key, key)?;
715
716 Ok(SendListView {
717 id: self.id,
718 access_id: self.access_id.clone(),
719
720 name: self.name.decrypt(ctx, key)?,
721 r#type: self.r#type,
722
723 disabled: self.disabled,
724
725 revision_date: self.revision_date,
726 deletion_date: self.deletion_date,
727 expiration_date: self.expiration_date,
728
729 auth_type: self.auth_type,
730 })
731 }
732}
733
734impl CompositeEncryptable<KeySlotIds, SymmetricKeySlotId, Send> for SendView {
735 fn encrypt_composite(
736 &self,
737 ctx: &mut KeyStoreContext<KeySlotIds>,
738 key: SymmetricKeySlotId,
739 ) -> Result<Send, CryptoError> {
740 let k = match (&self.key, &self.id) {
744 (Some(k), _) => B64Url::try_from(k.as_str())
746 .map_err(|_| CryptoError::InvalidKey)?
747 .as_bytes()
748 .to_vec(),
749 (None, None) => {
751 let key = generate_random_bytes::<[u8; SEND_KEY_LEN]>();
752 key.to_vec()
753 }
754 _ => return Err(CryptoError::InvalidKey),
756 };
757 let send_key = Send::derive_shareable_key(ctx, &k)?;
758
759 Ok(Send {
760 id: self.id,
761 access_id: self.access_id.clone(),
762
763 name: self.name.encrypt(ctx, send_key)?,
764 notes: self.notes.encrypt(ctx, send_key)?,
765 key: OctetStreamBytes::from(k.clone()).encrypt(ctx, key)?,
766 password: self.new_password.as_ref().map(|password| {
773 let password = bitwarden_crypto::pbkdf2(password.as_bytes(), &k, SEND_ITERATIONS);
774 B64::from(password.as_slice()).to_string()
775 }),
776
777 r#type: self.r#type,
778 file: self.file.encrypt_composite(ctx, send_key)?,
779 text: self.text.encrypt_composite(ctx, send_key)?,
780 data: self.data.encrypt_composite(ctx, send_key)?,
781
782 max_access_count: self.max_access_count,
783 access_count: self.access_count,
784 disabled: self.disabled,
785 hide_email: self.hide_email,
786
787 revision_date: self.revision_date,
788 deletion_date: self.deletion_date,
789 expiration_date: self.expiration_date,
790
791 emails: (!self.emails.is_empty()).then(|| self.emails.join(",")),
792 auth_type: self.auth_type,
793 })
794 }
795}
796
797impl TryFrom<SendResponseModel> for Send {
798 type Error = SendParseError;
799
800 fn try_from(send: SendResponseModel) -> Result<Self, Self::Error> {
801 let auth_type = match send.auth_type {
802 Some(t) => t.try_into()?,
803 None => {
804 if send.password.is_some() {
805 AuthType::Password
806 } else if send.emails.is_some() {
807 AuthType::Email
808 } else {
809 AuthType::None
810 }
811 }
812 };
813 Ok(Send {
814 id: send.id.map(SendId::new),
815 access_id: send.access_id,
816 name: require!(send.name).parse()?,
817 notes: EncString::try_from_optional(send.notes)?,
818 key: require!(send.key).parse()?,
819 password: send.password,
820 r#type: require!(send.r#type).try_into()?,
821 file: send.file.map(|f| (*f).try_into()).transpose()?,
822 text: send.text.map(|t| (*t).try_into()).transpose()?,
823 data: send.data.map(|d| (*d).try_into()).transpose()?,
824 max_access_count: send.max_access_count.map(|s| s as u32),
825 access_count: require!(send.access_count) as u32,
826 disabled: send.disabled.unwrap_or(false),
827 hide_email: send.hide_email.unwrap_or(false),
828 revision_date: require!(send.revision_date).parse()?,
829 deletion_date: require!(send.deletion_date).parse()?,
830 expiration_date: send.expiration_date.map(|s| s.parse()).transpose()?,
831 emails: send.emails,
832 auth_type,
833 })
834 }
835}
836
837impl TryFrom<bitwarden_api_api::models::SendType> for SendType {
838 type Error = bitwarden_core::MissingFieldError;
839
840 fn try_from(t: bitwarden_api_api::models::SendType) -> Result<Self, Self::Error> {
841 Ok(match t {
842 bitwarden_api_api::models::SendType::Text => SendType::Text,
843 bitwarden_api_api::models::SendType::File => SendType::File,
844 bitwarden_api_api::models::SendType::Item => SendType::Item,
845 bitwarden_api_api::models::SendType::__Unknown(_) => {
846 return Err(bitwarden_core::MissingFieldError("type"));
847 }
848 })
849 }
850}
851
852impl From<SendType> for bitwarden_api_api::models::SendType {
853 fn from(t: SendType) -> Self {
854 match t {
855 SendType::Text => bitwarden_api_api::models::SendType::Text,
856 SendType::File => bitwarden_api_api::models::SendType::File,
857 SendType::Item => bitwarden_api_api::models::SendType::Item,
858 }
859 }
860}
861
862impl TryFrom<bitwarden_api_api::models::AuthType> for AuthType {
863 type Error = bitwarden_core::MissingFieldError;
864
865 fn try_from(value: bitwarden_api_api::models::AuthType) -> Result<Self, Self::Error> {
866 Ok(match value {
867 bitwarden_api_api::models::AuthType::Email => AuthType::Email,
868 bitwarden_api_api::models::AuthType::Password => AuthType::Password,
869 bitwarden_api_api::models::AuthType::None => AuthType::None,
870 bitwarden_api_api::models::AuthType::__Unknown(_) => {
871 return Err(bitwarden_core::MissingFieldError("auth_type"));
872 }
873 })
874 }
875}
876
877impl From<AuthType> for bitwarden_api_api::models::AuthType {
878 fn from(value: AuthType) -> Self {
879 match value {
880 AuthType::Email => bitwarden_api_api::models::AuthType::Email,
881 AuthType::Password => bitwarden_api_api::models::AuthType::Password,
882 AuthType::None => bitwarden_api_api::models::AuthType::None,
883 }
884 }
885}
886
887impl From<SendFile> for SendFileModel {
888 fn from(file: SendFile) -> Self {
889 SendFileModel {
890 id: file.id,
891 file_name: Some(file.file_name.to_string()),
892 size: file.size,
893 size_name: file.size_name,
894 }
895 }
896}
897
898impl From<SendEncryptionType> for bitwarden_api_api::models::SendEncryptionType {
899 fn from(t: SendEncryptionType) -> Self {
900 match t {
901 SendEncryptionType::V1 => bitwarden_api_api::models::SendEncryptionType::V1,
902 }
903 }
904}
905
906impl TryFrom<bitwarden_api_api::models::SendEncryptionType> for SendEncryptionType {
907 type Error = bitwarden_core::MissingFieldError;
908
909 fn try_from(value: bitwarden_api_api::models::SendEncryptionType) -> Result<Self, Self::Error> {
910 Ok(match value {
911 bitwarden_api_api::models::SendEncryptionType::V1 => SendEncryptionType::V1,
912 bitwarden_api_api::models::SendEncryptionType::__Unknown(_) => {
913 return Err(bitwarden_core::MissingFieldError("encryption_version"));
914 }
915 })
916 }
917}
918
919impl From<SendText> for SendTextModel {
920 fn from(text: SendText) -> Self {
921 SendTextModel {
922 text: text.text.map(|text| text.to_string()),
923 hidden: Some(text.hidden),
924 }
925 }
926}
927
928impl TryFrom<SendFileModel> for SendFile {
929 type Error = SendParseError;
930
931 fn try_from(file: SendFileModel) -> Result<Self, Self::Error> {
932 Ok(SendFile {
933 id: file.id,
934 file_name: require!(file.file_name).parse()?,
935 size: file.size.map(|v| v.to_string()),
936 size_name: file.size_name,
937 })
938 }
939}
940
941impl TryFrom<SendTextModel> for SendText {
942 type Error = SendParseError;
943
944 fn try_from(text: SendTextModel) -> Result<Self, Self::Error> {
945 Ok(SendText {
946 text: EncString::try_from_optional(text.text)?,
947 hidden: text.hidden.unwrap_or(false),
948 })
949 }
950}
951
952impl TryFrom<SendDataModel> for SendItem {
953 type Error = SendParseError;
954
955 fn try_from(data: SendDataModel) -> Result<Self, Self::Error> {
956 let Some(sealed) = data.data else {
957 return Err(SendParseError::DeserializationFailure(
958 SendItemDeserializationFailureError,
959 ));
960 };
961
962 Ok(SendItem {
963 encryption_version: SendEncryptionType::try_from(
964 data.encryption_version
965 .unwrap_or(DEFAULT_SEND_ENCRYPTION.into()),
966 )?,
967 data: sealed,
968 metadata: SendItemMetadata {
969 item_id: CipherId::new(data.metadata.item_id),
970 creation_date: data
971 .metadata
972 .creation_date
973 .map(|cd| cd.parse())
974 .transpose()?,
975 revision_date: data
976 .metadata
977 .revision_date
978 .map(|rd| rd.parse())
979 .transpose()?,
980 folder_name: EncString::try_from_optional(data.metadata.folder_name)?,
981 collection_names: data
982 .metadata
983 .collection_names
984 .as_ref()
985 .map(|cols| cols.iter().map(|c| EncString::parse_strict(c)).collect())
986 .transpose()?,
987 organization_name: data.metadata.organization_name,
988 },
989 })
990 }
991}
992
993impl From<SendItem> for SendDataModel {
994 fn from(item: SendItem) -> Self {
995 SendDataModel {
996 encryption_version: Some(item.encryption_version.into()),
997 data: Some(item.data),
998 metadata: Box::new(SendItemMetadataModel {
999 item_id: item.metadata.item_id.into(),
1000 creation_date: item.metadata.creation_date.map(|cd| cd.to_rfc3339()),
1001 revision_date: item.metadata.revision_date.map(|rd| rd.to_rfc3339()),
1002 folder_name: item.metadata.folder_name.map(|f| f.to_string()),
1003 collection_names: item
1004 .metadata
1005 .collection_names
1006 .map(|cols| cols.iter().map(|c| c.to_string()).collect()),
1007 organization_name: item.metadata.organization_name.map(|o| o.to_string()),
1008 }),
1009 }
1010 }
1011}
1012
1013#[cfg(test)]
1014pub(crate) mod tests {
1015 use bitwarden_api_api::models::SendItemMetadataModel;
1016 use bitwarden_core::key_management::create_test_crypto_with_user_key;
1017 use bitwarden_crypto::SymmetricCryptoKey;
1018 use bitwarden_vault::{
1019 CipherRepromptType, CipherType, FieldType, FieldView, LoginView, PasswordHistoryView,
1020 };
1021
1022 use super::*;
1023
1024 const TEST_USER_KEY: &str =
1025 "bYCsk857hl8QJJtxyRK65tjUrbxKC4aDifJpsml+NIv4W9cVgFvi3qVD+yJTUU2T4UwNKWYtt9pqWf7Q+2WCCg==";
1026 const TEST_SEND_KEY: &str = "2.KLv/j0V4Ebs0dwyPdtt4vw==|jcrFuNYN1Qb3onBlwvtxUV/KpdnR1LPRL4EsCoXNAt4=|gHSywGy4Rj/RsCIZFwze4s2AACYKBtqDXTrQXjkgtIE=";
1027 const TEST_SEND_KEY_B64: &str = "Pgui0FK85cNhBGWHAlBHBw";
1028 pub(crate) const TEST_ITEM_ID: &str = "5d4fbf2b-7a36-4b3c-9f2e-1a6d8c0e9b71";
1029
1030 pub(crate) const TEST_VECTOR_ITEM_SEND_DATA: &str = "{\"format_version\":1,\"wrapped_cek\":\"2.e/m5UvBFEh4JEHYgnAVONQ==|Cl7wnKMdT9NxeisUg1Xx3OmOyZr7Z77luoLPCBxuo1EVAjf69q3yaFO25InB8swQgHdKgz/PVqtX6JmmbR4xu2PKZtNFNmRRUVnX5BWvvjE=|+PW2Knoda9s1qVKMAEcXDsw5ij/wUZ/GfR9xVDnpPSw=\",\"envelope\":\"g1hHpQEDA3gjYXBwbGljYXRpb24veC5iaXR3YXJkZW4uY2Jvci1wYWRkZWQEUCSl5i37B6J7uBZ8Ge91nw86AAE4gQI6AAE4gAGhBUxDZ7isjgG0Zt2UEERZATT9Jcf0kWC5y8qsWWn4iNEv9kbjf1jPeolS0FdxBu4y11Yez9MT1cPaJ8hxCjRztX5VgGzEKMnOcc491fwZXQByT0M9MLDDpJD3HDOOCzQ2gdk7VZktEmc8nhZoAGnZP0GmeoJh/my3WDukSsa2vOiOLE2KGIfF8OHa7nwXds9Z1aIhlavFSNAiqDWAdOk65OhqrvE0BPN7WdW7+NbuviPiEKa3wbCIhmjfQI1nW5simSqTMx4/ikLCqH2F3gLt4nk0SJ3KAbbQA3ENWMFef8s+m5uNWPIsALXeauC5X8XwvhOI2a1XNldR2r9LCEgg0vqzi+yCLVZpfKRQVFIfBmRwBtBObo1hFLBgbCkH8hXsX/eeU9qhL8oskb7s6HCGX0IGXoPzBLkUJH2IohWh3FMYVPd4Yw==\"}";
1033
1034 fn item_send_cipher_view() -> CipherView {
1037 CipherView {
1038 id: TEST_ITEM_ID.parse().ok(),
1039 organization_id: None,
1040 folder_id: None,
1041 collection_ids: Vec::new(),
1042 key: None,
1043 name: "Item Send".to_string(),
1044 notes: Some("Item Send notes".to_string()),
1045 r#type: CipherType::Login,
1046 login: Some(LoginView {
1047 username: Some("[email protected]".to_string()),
1048 password: Some("hunter2".to_string()),
1049 password_revision_date: None,
1050 uris: None,
1051 totp: None,
1052 autofill_on_page_load: None,
1053 http_authentication_enabled: Some(false),
1055 fido2_credentials: None,
1056 }),
1057 identity: None,
1058 card: None,
1059 secure_note: None,
1060 ssh_key: None,
1061 bank_account: None,
1062 drivers_license: None,
1063 passport: None,
1064 favorite: false,
1065 reprompt: CipherRepromptType::None,
1066 organization_use_totp: false,
1067 edit: false,
1068 permissions: None,
1069 view_password: true,
1070 local_data: None,
1071 attachments: None,
1072 attachment_decryption_failures: None,
1073 fields: Some(vec![FieldView {
1074 name: Some("field".to_string()),
1075 value: Some("value".to_string()),
1076 r#type: FieldType::Text,
1077 linked_id: None,
1078 }]),
1079 password_history: Some(vec![PasswordHistoryView {
1080 password: "old-password".to_string(),
1081 last_used_date: "2024-01-01T00:00:00Z".parse().unwrap(),
1082 }]),
1083 creation_date: Default::default(),
1084 deleted_date: None,
1085 revision_date: Default::default(),
1086 archived_date: None,
1087 partial: false,
1088 }
1089 }
1090
1091 fn item_send_view() -> SendView {
1092 SendView {
1093 id: "3d80dd72-2d14-4f26-812c-b0f0018aa144".parse().ok(),
1094 access_id: Some("ct2APRQtJk-BLLDwAYqhRA".to_owned()),
1095 name: "Test".to_string(),
1096 notes: None,
1097 key: Some(TEST_SEND_KEY_B64.to_owned()),
1098 new_password: None,
1099 has_password: false,
1100 r#type: SendType::Item,
1101 file: None,
1102 text: None,
1103 data: Some(SendItemView {
1104 data: item_send_cipher_view(),
1105 metadata: SendItemMetadataView {
1106 item_id: TEST_ITEM_ID
1107 .parse()
1108 .expect("TEST_ITEM_ID should be a valid CipherId"),
1109 creation_date: Some(DateTime::<Utc>::default()),
1110 revision_date: Some(DateTime::<Utc>::default()),
1111 folder_name: None,
1112 collection_names: None,
1113 organization_name: None,
1114 },
1115 }),
1116 max_access_count: None,
1117 access_count: 0,
1118 disabled: false,
1119 hide_email: false,
1120 revision_date: "2024-01-07T23:56:48.207363Z".parse().unwrap(),
1121 deletion_date: "2024-01-14T23:56:48Z".parse().unwrap(),
1122 expiration_date: None,
1123 emails: Vec::new(),
1124 auth_type: AuthType::None,
1125 }
1126 }
1127
1128 #[test]
1129 #[ignore = "Generates test vectors; run manually"]
1130 fn generate_item_send_test_vector() {
1131 let user_key: SymmetricCryptoKey = TEST_USER_KEY.to_string().try_into().unwrap();
1132 let crypto = create_test_crypto_with_user_key(user_key);
1133 let send: Send = crypto.encrypt(item_send_view()).unwrap();
1134 println!(
1135 "pub(crate) const TEST_VECTOR_ITEM_SEND_DATA: &str = {:?};",
1136 send.data.unwrap().data
1137 );
1138 }
1139
1140 #[test]
1141 fn test_item_send_test_vector() {
1142 let user_key: SymmetricCryptoKey = TEST_USER_KEY.to_string().try_into().unwrap();
1143 let crypto = create_test_crypto_with_user_key(user_key);
1144
1145 let item = SendItem::try_from(SendDataModel {
1147 encryption_version: Some(SendEncryptionType::V1.into()),
1148 data: Some(TEST_VECTOR_ITEM_SEND_DATA.to_string()),
1149 metadata: Box::new(SendItemMetadataModel {
1150 item_id: TEST_ITEM_ID.parse().unwrap(),
1151 creation_date: Some("1970-01-01T00:00:00Z".to_string()),
1152 revision_date: Some("1970-01-01T00:00:00Z".to_string()),
1153 folder_name: None,
1154 collection_names: None,
1155 organization_name: None,
1156 }),
1157 })
1158 .unwrap();
1159 let send = Send {
1160 id: "3d80dd72-2d14-4f26-812c-b0f0018aa144".parse().ok(),
1161 access_id: Some("ct2APRQtJk-BLLDwAYqhRA".to_owned()),
1162 r#type: SendType::Item,
1163 name: "2.STIyTrfDZN/JXNDN9zNEMw==|NDLum8BHZpPNYhJo9ggSkg==|UCsCLlBO3QzdPwvMAWs2VVwuE6xwOx/vxOooPObqnEw=".parse()
1164 .unwrap(),
1165 notes: None,
1166 file: None,
1167 text: None,
1168 data: Some(item),
1169 key: TEST_SEND_KEY.parse().unwrap(),
1170 max_access_count: None,
1171 access_count: 0,
1172 password: None,
1173 disabled: false,
1174 revision_date: "2024-01-07T23:56:48.207363Z".parse().unwrap(),
1175 expiration_date: None,
1176 deletion_date: "2024-01-14T23:56:48Z".parse().unwrap(),
1177 hide_email: false,
1178 emails: None,
1179 auth_type: AuthType::None,
1180 };
1181
1182 let view: SendView = crypto.decrypt(&send).unwrap();
1183
1184 assert_eq!(view, item_send_view());
1185 }
1186
1187 #[test]
1188 fn test_item_send_encrypt_round_trip() {
1189 let user_key: SymmetricCryptoKey = TEST_USER_KEY.to_string().try_into().unwrap();
1190 let crypto = create_test_crypto_with_user_key(user_key);
1191
1192 let send: Send = crypto.encrypt(item_send_view()).unwrap();
1193 let item = send.data.as_ref().unwrap();
1194 assert!(serde_json::from_str::<bitwarden_vault::Cipher>(&item.data).is_err());
1196
1197 let view: SendView = crypto.decrypt(&send).unwrap();
1198 assert_eq!(view, item_send_view());
1199 }
1200
1201 #[test]
1202 fn test_item_send_metadata_round_trip() {
1203 let user_key: SymmetricCryptoKey = TEST_USER_KEY.to_string().try_into().unwrap();
1204 let crypto = create_test_crypto_with_user_key(user_key);
1205
1206 let send: Send = crypto.encrypt(item_send_view()).unwrap();
1208 let item = send.data.as_ref().unwrap();
1209 assert_eq!(
1210 item.metadata,
1211 SendItemMetadata {
1212 item_id: TEST_ITEM_ID.parse().unwrap(),
1213 creation_date: Some(DateTime::<Utc>::default()),
1214 revision_date: Some(DateTime::<Utc>::default()),
1215 folder_name: None,
1216 collection_names: None,
1217 organization_name: None,
1218 }
1219 );
1220
1221 let decrypted: SendView = crypto.decrypt(&send).unwrap();
1222 assert_eq!(decrypted, item_send_view());
1223 }
1224
1225 #[test]
1226 fn test_get_send_key() {
1227 let user_key: SymmetricCryptoKey = "w2LO+nwV4oxwswVYCxlOfRUseXfvU03VzvKQHrqeklPgiMZrspUe6sOBToCnDn9Ay0tuCBn8ykVVRb7PWhub2Q==".to_string().try_into().unwrap();
1229 let crypto = create_test_crypto_with_user_key(user_key);
1230 let mut ctx = crypto.context();
1231
1232 let send_key = "2.+1KUfOX8A83Xkwk1bumo/w==|Nczvv+DTkeP466cP/wMDnGK6W9zEIg5iHLhcuQG6s+M=|SZGsfuIAIaGZ7/kzygaVUau3LeOvJUlolENBOU+LX7g="
1233 .parse()
1234 .unwrap();
1235
1236 let send_key = Send::get_key(&mut ctx, &send_key, SymmetricKeySlotId::User).unwrap();
1238 #[allow(deprecated)]
1239 let send_key = ctx.dangerous_get_symmetric_key(send_key).unwrap();
1240 let send_key_b64 = send_key.to_base64();
1241 assert_eq!(
1242 send_key_b64.to_string(),
1243 "IR9ImHGm6rRuIjiN7csj94bcZR5WYTJj5GtNfx33zm6tJCHUl+QZlpNPba8g2yn70KnOHsAODLcR0um6E3MAlg=="
1244 );
1245 }
1246
1247 #[test]
1248 pub fn test_decrypt() {
1249 let user_key: SymmetricCryptoKey = "bYCsk857hl8QJJtxyRK65tjUrbxKC4aDifJpsml+NIv4W9cVgFvi3qVD+yJTUU2T4UwNKWYtt9pqWf7Q+2WCCg==".to_string().try_into().unwrap();
1250 let crypto = create_test_crypto_with_user_key(user_key);
1251
1252 let send = Send {
1253 id: "3d80dd72-2d14-4f26-812c-b0f0018aa144".parse().ok(),
1254 access_id: Some("ct2APRQtJk-BLLDwAYqhRA".to_owned()),
1255 r#type: SendType::Text,
1256 name: "2.STIyTrfDZN/JXNDN9zNEMw==|NDLum8BHZpPNYhJo9ggSkg==|UCsCLlBO3QzdPwvMAWs2VVwuE6xwOx/vxOooPObqnEw=".parse()
1257 .unwrap(),
1258 notes: None,
1259 file: None,
1260 text: Some(SendText {
1261 text: "2.2VPyLzk1tMLug0X3x7RkaQ==|mrMt9vbZsCJhJIj4eebKyg==|aZ7JeyndytEMR1+uEBupEvaZuUE69D/ejhfdJL8oKq0=".parse().ok(),
1262 hidden: false,
1263 }),
1264 data: None,
1265 key: "2.KLv/j0V4Ebs0dwyPdtt4vw==|jcrFuNYN1Qb3onBlwvtxUV/KpdnR1LPRL4EsCoXNAt4=|gHSywGy4Rj/RsCIZFwze4s2AACYKBtqDXTrQXjkgtIE=".parse().unwrap(),
1266 max_access_count: None,
1267 access_count: 0,
1268 password: None,
1269 disabled: false,
1270 revision_date: "2024-01-07T23:56:48.207363Z".parse().unwrap(),
1271 expiration_date: None,
1272 deletion_date: "2024-01-14T23:56:48Z".parse().unwrap(),
1273 hide_email: false,
1274 emails: None,
1275 auth_type: AuthType::None,
1276 };
1277
1278 let view: SendView = crypto.decrypt(&send).unwrap();
1279
1280 let expected = SendView {
1281 id: "3d80dd72-2d14-4f26-812c-b0f0018aa144".parse().ok(),
1282 access_id: Some("ct2APRQtJk-BLLDwAYqhRA".to_owned()),
1283 name: "Test".to_string(),
1284 notes: None,
1285 key: Some("Pgui0FK85cNhBGWHAlBHBw".to_owned()),
1286 new_password: None,
1287 has_password: false,
1288 r#type: SendType::Text,
1289 file: None,
1290 text: Some(SendTextView {
1291 text: Some("This is a test".to_owned()),
1292 hidden: false,
1293 }),
1294 data: None,
1295 max_access_count: None,
1296 access_count: 0,
1297 disabled: false,
1298 hide_email: false,
1299 revision_date: "2024-01-07T23:56:48.207363Z".parse().unwrap(),
1300 deletion_date: "2024-01-14T23:56:48Z".parse().unwrap(),
1301 expiration_date: None,
1302 emails: Vec::new(),
1303 auth_type: AuthType::None,
1304 };
1305
1306 assert_eq!(view, expected);
1307 }
1308
1309 #[test]
1310 pub fn test_encrypt() {
1311 let user_key: SymmetricCryptoKey = "bYCsk857hl8QJJtxyRK65tjUrbxKC4aDifJpsml+NIv4W9cVgFvi3qVD+yJTUU2T4UwNKWYtt9pqWf7Q+2WCCg==".to_string().try_into().unwrap();
1312 let crypto = create_test_crypto_with_user_key(user_key);
1313
1314 let view = SendView {
1315 id: "3d80dd72-2d14-4f26-812c-b0f0018aa144".parse().ok(),
1316 access_id: Some("ct2APRQtJk-BLLDwAYqhRA".to_owned()),
1317 name: "Test".to_string(),
1318 notes: None,
1319 key: Some("Pgui0FK85cNhBGWHAlBHBw".to_owned()),
1320 new_password: None,
1321 has_password: false,
1322 r#type: SendType::Text,
1323 file: None,
1324 text: Some(SendTextView {
1325 text: Some("This is a test".to_owned()),
1326 hidden: false,
1327 }),
1328 data: None,
1329 max_access_count: None,
1330 access_count: 0,
1331 disabled: false,
1332 hide_email: false,
1333 revision_date: "2024-01-07T23:56:48.207363Z".parse().unwrap(),
1334 deletion_date: "2024-01-14T23:56:48Z".parse().unwrap(),
1335 expiration_date: None,
1336 emails: Vec::new(),
1337 auth_type: AuthType::None,
1338 };
1339
1340 let v: SendView = crypto
1342 .decrypt(&crypto.encrypt(view.clone()).unwrap())
1343 .unwrap();
1344 assert_eq!(v, view);
1345 }
1346
1347 #[test]
1348 pub fn test_create() {
1349 let user_key: SymmetricCryptoKey = "bYCsk857hl8QJJtxyRK65tjUrbxKC4aDifJpsml+NIv4W9cVgFvi3qVD+yJTUU2T4UwNKWYtt9pqWf7Q+2WCCg==".to_string().try_into().unwrap();
1350 let crypto = create_test_crypto_with_user_key(user_key);
1351
1352 let view = SendView {
1353 id: None,
1354 access_id: Some("ct2APRQtJk-BLLDwAYqhRA".to_owned()),
1355 name: "Test".to_string(),
1356 notes: None,
1357 key: None,
1358 new_password: None,
1359 has_password: false,
1360 r#type: SendType::Text,
1361 file: None,
1362 text: Some(SendTextView {
1363 text: Some("This is a test".to_owned()),
1364 hidden: false,
1365 }),
1366 data: None,
1367 max_access_count: None,
1368 access_count: 0,
1369 disabled: false,
1370 hide_email: false,
1371 revision_date: "2024-01-07T23:56:48.207363Z".parse().unwrap(),
1372 deletion_date: "2024-01-14T23:56:48Z".parse().unwrap(),
1373 expiration_date: None,
1374 emails: Vec::new(),
1375 auth_type: AuthType::None,
1376 };
1377
1378 let v: SendView = crypto
1380 .decrypt(&crypto.encrypt(view.clone()).unwrap())
1381 .unwrap();
1382
1383 let t = SendView { key: None, ..v };
1385 assert_eq!(t, view);
1386 }
1387
1388 #[test]
1389 pub fn test_create_password() {
1390 let user_key: SymmetricCryptoKey = "bYCsk857hl8QJJtxyRK65tjUrbxKC4aDifJpsml+NIv4W9cVgFvi3qVD+yJTUU2T4UwNKWYtt9pqWf7Q+2WCCg==".to_string().try_into().unwrap();
1391 let crypto = create_test_crypto_with_user_key(user_key);
1392
1393 let view = SendView {
1394 id: None,
1395 access_id: Some("ct2APRQtJk-BLLDwAYqhRA".to_owned()),
1396 name: "Test".to_owned(),
1397 notes: None,
1398 key: Some("Pgui0FK85cNhBGWHAlBHBw".to_owned()),
1399 new_password: Some("abc123".to_owned()),
1400 has_password: false,
1401 r#type: SendType::Text,
1402 file: None,
1403 text: Some(SendTextView {
1404 text: Some("This is a test".to_owned()),
1405 hidden: false,
1406 }),
1407 data: None,
1408 max_access_count: None,
1409 access_count: 0,
1410 disabled: false,
1411 hide_email: false,
1412 revision_date: "2024-01-07T23:56:48.207363Z".parse().unwrap(),
1413 deletion_date: "2024-01-14T23:56:48Z".parse().unwrap(),
1414 expiration_date: None,
1415 emails: Vec::new(),
1416 auth_type: AuthType::Password,
1417 };
1418
1419 let send: Send = crypto.encrypt(view).unwrap();
1420
1421 assert_eq!(
1422 send.password,
1423 Some("vTIDfdj3FTDbejmMf+mJWpYdMXsxfeSd1Sma3sjCtiQ=".to_owned())
1424 );
1425 assert_eq!(send.auth_type, AuthType::Password);
1426
1427 let v: SendView = crypto.decrypt(&send).unwrap();
1428 assert_eq!(v.new_password, None);
1429 assert!(v.has_password);
1430 assert_eq!(v.auth_type, AuthType::Password);
1431 }
1432
1433 #[test]
1434 pub fn test_create_email_otp() {
1435 let user_key: SymmetricCryptoKey = "bYCsk857hl8QJJtxyRK65tjUrbxKC4aDifJpsml+NIv4W9cVgFvi3qVD+yJTUU2T4UwNKWYtt9pqWf7Q+2WCCg==".to_string().try_into().unwrap();
1436 let crypto = create_test_crypto_with_user_key(user_key);
1437
1438 let view = SendView {
1439 id: None,
1440 access_id: Some("ct2APRQtJk-BLLDwAYqhRA".to_owned()),
1441 name: "Test".to_owned(),
1442 notes: None,
1443 key: Some("Pgui0FK85cNhBGWHAlBHBw".to_owned()),
1444 new_password: None,
1445 has_password: false,
1446 r#type: SendType::Text,
1447 file: None,
1448 text: Some(SendTextView {
1449 text: Some("This is a test".to_owned()),
1450 hidden: false,
1451 }),
1452 data: None,
1453 max_access_count: None,
1454 access_count: 0,
1455 disabled: false,
1456 hide_email: false,
1457 revision_date: "2024-01-07T23:56:48.207363Z".parse().unwrap(),
1458 deletion_date: "2024-01-14T23:56:48Z".parse().unwrap(),
1459 expiration_date: None,
1460 emails: vec![
1461 String::from("[email protected]"),
1462 String::from("[email protected]"),
1463 ],
1464 auth_type: AuthType::Email,
1465 };
1466
1467 let send: Send = crypto.encrypt(view.clone()).unwrap();
1468
1469 let v: SendView = crypto.decrypt(&send).unwrap();
1471
1472 assert_eq!(v, view);
1473 }
1474
1475 #[test]
1476 fn test_send_into_send_with_id_request_model() {
1477 let send_id = "3d80dd72-2d14-4f26-812c-b0f0018aa144".parse().unwrap();
1478 let revision_date = DateTime::parse_from_rfc3339("2024-01-07T23:56:48Z")
1479 .unwrap()
1480 .with_timezone(&Utc);
1481 let deletion_date = DateTime::parse_from_rfc3339("2024-01-14T23:56:48Z")
1482 .unwrap()
1483 .with_timezone(&Utc);
1484 let expiration_date = DateTime::parse_from_rfc3339("2024-01-20T23:56:48Z")
1485 .unwrap()
1486 .with_timezone(&Utc);
1487
1488 let name = "2.STIyTrfDZN/JXNDN9zNEMw==|NDLum8BHZpPNYhJo9ggSkg==|UCsCLlBO3QzdPwvMAWs2VVwuE6xwOx/vxOooPObqnEw=";
1489 let notes = "2.2VPyLzk1tMLug0X3x7RkaQ==|mrMt9vbZsCJhJIj4eebKyg==|aZ7JeyndytEMR1+uEBupEvaZuUE69D/ejhfdJL8oKq0=";
1490 let key = "2.KLv/j0V4Ebs0dwyPdtt4vw==|jcrFuNYN1Qb3onBlwvtxUV/KpdnR1LPRL4EsCoXNAt4=|gHSywGy4Rj/RsCIZFwze4s2AACYKBtqDXTrQXjkgtIE=";
1491 let file_name = "2.+1KUfOX8A83Xkwk1bumo/w==|Nczvv+DTkeP466cP/wMDnGK6W9zEIg5iHLhcuQG6s+M=|SZGsfuIAIaGZ7/kzygaVUau3LeOvJUlolENBOU+LX7g=";
1492 let text_value = "2.2VPyLzk1tMLug0X3x7RkaQ==|mrMt9vbZsCJhJIj4eebKyg==|aZ7JeyndytEMR1+uEBupEvaZuUE69D/ejhfdJL8oKq0=";
1493
1494 let send = Send {
1495 id: Some(SendId::new(send_id)),
1496 access_id: Some("ct2APRQtJk-BLLDwAYqhRA".to_string()),
1497 name: name.parse().unwrap(),
1498 notes: Some(notes.parse().unwrap()),
1499 key: key.parse().unwrap(),
1500 password: Some("hash".to_string()),
1501 r#type: SendType::File,
1502 file: Some(SendFile {
1503 id: Some("file-id".to_string()),
1504 file_name: file_name.parse().unwrap(),
1505 size: Some("1234".to_string()),
1506 size_name: Some("1.2 KB".to_string()),
1507 }),
1508 text: Some(SendText {
1509 text: Some(text_value.parse().unwrap()),
1510 hidden: true,
1511 }),
1512 data: None,
1513 max_access_count: Some(42),
1514 access_count: 0,
1515 disabled: true,
1516 hide_email: true,
1517 revision_date,
1518 deletion_date,
1519 expiration_date: Some(expiration_date),
1520 emails: Some("[email protected],[email protected]".to_string()),
1521 auth_type: AuthType::Email,
1522 };
1523
1524 let model: SendWithIdRequestModel = send.into();
1525
1526 assert_eq!(model.id, send_id);
1527 assert_eq!(
1528 model.r#type,
1529 Some(bitwarden_api_api::models::SendType::File)
1530 );
1531 assert_eq!(
1532 model.auth_type,
1533 Some(bitwarden_api_api::models::AuthType::Email)
1534 );
1535 assert_eq!(model.file_length, Some(1234));
1536 assert_eq!(model.name.as_deref(), Some(name));
1537 assert_eq!(model.notes.as_deref(), Some(notes));
1538 assert_eq!(model.key, key);
1539 assert_eq!(model.max_access_count, Some(42));
1540 assert_eq!(
1541 model
1542 .expiration_date
1543 .unwrap()
1544 .parse::<DateTime<Utc>>()
1545 .unwrap(),
1546 expiration_date
1547 );
1548 assert_eq!(
1549 model.deletion_date.parse::<DateTime<Utc>>().unwrap(),
1550 deletion_date
1551 );
1552 assert_eq!(model.password.as_deref(), Some("hash"));
1553 assert_eq!(
1554 model.emails.as_deref(),
1555 Some("[email protected],[email protected]")
1556 );
1557 assert!(model.disabled);
1558 assert_eq!(model.hide_email, Some(true));
1559
1560 let file = model.file.unwrap();
1561 assert_eq!(file.id.as_deref(), Some("file-id"));
1562 assert_eq!(file.file_name.as_deref(), Some(file_name));
1563 assert_eq!(file.size.as_deref(), Some("1234"));
1564 assert_eq!(file.size_name.as_deref(), Some("1.2 KB"));
1565
1566 let text = model.text.unwrap();
1567 assert_eq!(text.text.as_deref(), Some(text_value));
1568 assert_eq!(text.hidden, Some(true));
1569 }
1570
1571 #[test]
1572 fn test_item_send_into_send_with_id_request_model() {
1573 let send = Send {
1574 id: "3d80dd72-2d14-4f26-812c-b0f0018aa144".parse().ok(),
1575 access_id: None,
1576 r#type: SendType::Item,
1577 name: "2.STIyTrfDZN/JXNDN9zNEMw==|NDLum8BHZpPNYhJo9ggSkg==|UCsCLlBO3QzdPwvMAWs2VVwuE6xwOx/vxOooPObqnEw=".parse()
1578 .unwrap(),
1579 notes: None,
1580 file: None,
1581 text: None,
1582 data: Some(SendItem {
1583 encryption_version: SendEncryptionType::V1,
1584 data: TEST_VECTOR_ITEM_SEND_DATA.to_string(),
1585 metadata: SendItemMetadata {
1586 item_id: TEST_ITEM_ID.parse().unwrap(),
1587 creation_date: Some(DateTime::<Utc>::default()),
1588 revision_date: Some(DateTime::<Utc>::default()),
1589 folder_name: None,
1590 collection_names: None,
1591 organization_name: None,
1592 },
1593 }),
1594 key: TEST_SEND_KEY.parse().unwrap(),
1595 max_access_count: None,
1596 access_count: 0,
1597 password: None,
1598 disabled: false,
1599 revision_date: "2024-01-07T23:56:48Z".parse().unwrap(),
1600 expiration_date: None,
1601 deletion_date: "2024-01-14T23:56:48Z".parse().unwrap(),
1602 hide_email: false,
1603 emails: None,
1604 auth_type: AuthType::None,
1605 };
1606
1607 let model: SendWithIdRequestModel = send.into();
1608
1609 let data = model.data.expect("Item Send request must carry its data");
1611 assert_eq!(
1612 data.encryption_version,
1613 Some(bitwarden_api_api::models::SendEncryptionType::V1)
1614 );
1615 assert_eq!(data.data.as_deref(), Some(TEST_VECTOR_ITEM_SEND_DATA));
1616 assert_eq!(data.metadata.item_id.to_string(), TEST_ITEM_ID);
1617 }
1618
1619 #[test]
1620 fn auth_data_hashed_password_returns_key_b64_verbatim() {
1621 let key_b64 = "pretend-this-is-a-pbkdf2-output==".to_string();
1626 let auth = SendAuthType::HashedPassword {
1627 key_b64: key_b64.clone(),
1628 };
1629
1630 let (password, emails) = auth.auth_data(b"any-send-key-bytes-here");
1631
1632 assert_eq!(password, Some(key_b64));
1633 assert_eq!(emails, None);
1634 }
1635
1636 #[test]
1637 fn auth_data_hashed_and_plaintext_diverge_for_same_input() {
1638 let same_string = "abc123".to_string();
1643 let send_key = b"send-key-salt-bytes";
1644
1645 let (plaintext_out, _) = SendAuthType::Password {
1646 password: same_string.clone(),
1647 }
1648 .auth_data(send_key);
1649 let (hashed_out, _) = SendAuthType::HashedPassword {
1650 key_b64: same_string,
1651 }
1652 .auth_data(send_key);
1653
1654 assert_ne!(
1655 plaintext_out, hashed_out,
1656 "Plaintext path must run PBKDF2; HashedPassword path must not"
1657 );
1658 }
1659
1660 #[test]
1661 fn auth_type_for_hashed_password_maps_to_password() {
1662 assert_eq!(
1665 SendAuthType::Password {
1666 password: "p".to_string()
1667 }
1668 .auth_type(),
1669 AuthType::Password,
1670 );
1671 assert_eq!(
1672 SendAuthType::HashedPassword {
1673 key_b64: "k".to_string()
1674 }
1675 .auth_type(),
1676 AuthType::Password,
1677 );
1678 }
1679
1680 #[test]
1684 fn send_auth_type_round_trips_through_json() {
1685 let cases = [
1686 (SendAuthType::None, serde_json::json!({"type": "none"})),
1687 (
1688 SendAuthType::Password {
1689 password: "hunter2".to_string(),
1690 },
1691 serde_json::json!({"type": "password", "password": "hunter2"}),
1692 ),
1693 (
1694 SendAuthType::HashedPassword {
1695 key_b64: "deadbeef==".to_string(),
1696 },
1697 serde_json::json!({"type": "hashedPassword", "keyB64": "deadbeef=="}),
1698 ),
1699 (
1700 SendAuthType::Emails {
1701 emails: vec!["[email protected]".to_string()],
1702 },
1703 serde_json::json!({"type": "emails", "emails": ["[email protected]"]}),
1704 ),
1705 ];
1706 for (value, expected) in cases {
1707 let serialized = serde_json::to_value(&value).expect("serialize");
1708 assert_eq!(serialized, expected, "wire shape mismatch for {value:?}");
1709 let deserialized: SendAuthType =
1710 serde_json::from_value(serialized).expect("round-trip");
1711 assert_eq!(deserialized, value, "round-trip mismatch for {value:?}");
1712 }
1713 }
1714
1715 #[test]
1716 fn typed_constructors_produce_expected_variants() {
1717 assert_eq!(
1718 SendAuthType::from_plaintext_password("hunter2".to_string()),
1719 SendAuthType::Password {
1720 password: "hunter2".to_string()
1721 },
1722 );
1723 assert_eq!(
1724 SendAuthType::from_hashed_password("deadbeef==".to_string()),
1725 SendAuthType::HashedPassword {
1726 key_b64: "deadbeef==".to_string()
1727 },
1728 );
1729 }
1730}