1use bitwarden_api_api::models::{
2 CipherDetailsResponseModel, CipherMiniDetailsResponseModel, CipherMiniResponseModel,
3 CipherRequestModel, CipherResponseModel, CipherWithIdRequestModel,
4};
5use bitwarden_collections::collection::CollectionId;
6use bitwarden_core::{
7 ApiError, MissingFieldError, OrganizationId, UserId,
8 key_management::{KeySlotIds, MINIMUM_ENFORCE_ICON_URI_HASH_VERSION, SymmetricKeySlotId},
9 require,
10};
11use bitwarden_crypto::{
12 CompositeEncryptable, CryptoError, Decryptable, EncString, IdentifyKey, KeyStoreContext,
13 PrimitiveEncryptable, SymmetricCryptoKey, SymmetricKeyAlgorithm,
14};
15use bitwarden_error::bitwarden_error;
16use bitwarden_state::repository::RepositoryError;
17use bitwarden_uuid::uuid_newtype;
18use chrono::{DateTime, SecondsFormat, Utc};
19use serde::{Deserialize, Serialize};
20use serde_repr::{Deserialize_repr, Serialize_repr};
21use thiserror::Error;
22
23use super::{
24 attachment, bank_account,
25 bank_account::BankAccountListView,
26 blob::{decrypt_blob_cipher, encrypt_blob_cipher_with_wrapping_key, try_parse_blob},
27 card,
28 card::CardListView,
29 cipher_permissions::CipherPermissions,
30 drivers_license, field, identity,
31 local_data::{LocalData, LocalDataView},
32 login::{LoginListView, LoginUri, LoginUriView},
33 passport, secure_note, ssh_key,
34};
35use crate::{
36 DecryptError, EncryptError, Fido2CredentialFullView, Fido2CredentialView, FieldView, FolderId,
37 Login, LoginView, VaultParseError,
38 password_history::{self, MAX_PASSWORD_HISTORY_ENTRIES},
39};
40
41uuid_newtype!(pub CipherId);
42
43#[allow(missing_docs)]
44#[bitwarden_error(flat)]
45#[derive(Debug, Error)]
46pub enum CipherError {
47 #[error(transparent)]
48 MissingField(#[from] MissingFieldError),
49 #[error(transparent)]
50 Crypto(#[from] CryptoError),
51 #[error(transparent)]
52 Decrypt(#[from] DecryptError),
53 #[error(transparent)]
54 Encrypt(#[from] EncryptError),
55 #[error(
56 "This cipher contains attachments without keys. Those attachments will need to be reuploaded to complete the operation"
57 )]
58 AttachmentsWithoutKeys,
59 #[error("This cipher cannot be moved to the specified organization")]
60 OrganizationAlreadySet,
61 #[error(transparent)]
62 Repository(#[from] RepositoryError),
63 #[error(transparent)]
64 Chrono(#[from] chrono::ParseError),
65 #[error(transparent)]
66 SerdeJson(#[from] serde_json::Error),
67 #[error(transparent)]
68 Api(#[from] ApiError),
69}
70
71pub(super) trait CipherKind {
73 fn decrypt_subtitle(
75 &self,
76 ctx: &mut KeyStoreContext<KeySlotIds>,
77 key: SymmetricKeySlotId,
78 ) -> Result<String, CryptoError>;
79
80 fn get_copyable_fields(&self, cipher: Option<&Cipher>) -> Vec<CopyableCipherFields>;
82}
83
84#[allow(missing_docs)]
85#[derive(Clone, Copy, Serialize_repr, Deserialize_repr, Debug, PartialEq)]
86#[repr(u8)]
87#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
88#[bitwarden_ffi::wasm_object]
89pub enum CipherType {
90 Login = 1,
91 SecureNote = 2,
92 Card = 3,
93 Identity = 4,
94 SshKey = 5,
95 BankAccount = 6,
96 DriversLicense = 7,
97 Passport = 8,
98}
99
100#[allow(missing_docs)]
101#[derive(Clone, Copy, Default, Serialize_repr, Deserialize_repr, Debug, PartialEq)]
102#[repr(u8)]
103#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
104#[bitwarden_ffi::wasm_object]
105pub enum CipherRepromptType {
106 #[default]
107 None = 0,
108 Password = 1,
109}
110
111#[serde_with::skip_serializing_none]
112#[allow(missing_docs)]
113#[derive(Serialize, Deserialize, Debug, Clone)]
114#[serde(rename_all = "camelCase", deny_unknown_fields)]
115#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
116#[bitwarden_ffi::wasm_record]
117pub struct EncryptionContext {
118 pub encrypted_for: UserId,
121 #[serde(default)]
125 #[cfg_attr(feature = "uniffi", uniffi(default = None))]
126 #[cfg_attr(feature = "wasm", tsify(optional))]
127 pub encrypted_by_key_id: Option<String>,
128 pub cipher: Cipher,
129}
130
131impl TryFrom<EncryptionContext> for CipherWithIdRequestModel {
132 type Error = CipherError;
133 fn try_from(
134 EncryptionContext {
135 cipher,
136 encrypted_for,
137 encrypted_by_key_id,
138 }: EncryptionContext,
139 ) -> Result<Self, Self::Error> {
140 Ok(Self {
141 id: require!(cipher.id).into(),
142 encrypted_for: Some(encrypted_for.into()),
143 encrypted_by_key_id,
144 r#type: Some(cipher.r#type.into()),
145 organization_id: cipher.organization_id.map(|o| o.to_string()),
146 is_organization_cipher: None,
147 folder_id: cipher.folder_id.as_ref().map(ToString::to_string),
148 favorite: cipher.favorite.into(),
149 reprompt: Some(cipher.reprompt.into()),
150 key: cipher.key.map(|k| k.to_string()),
151 name: cipher.name.as_ref().map(ToString::to_string),
152 notes: cipher.notes.map(|n| n.to_string()),
153 fields: Some(
154 cipher
155 .fields
156 .into_iter()
157 .flatten()
158 .map(Into::into)
159 .collect(),
160 ),
161 password_history: Some(
162 cipher
163 .password_history
164 .into_iter()
165 .flatten()
166 .map(Into::into)
167 .collect(),
168 ),
169 attachments: None,
170 attachments2: Some(
171 cipher
172 .attachments
173 .into_iter()
174 .flatten()
175 .filter_map(|a| {
176 a.id.map(|id| {
177 (
178 id,
179 bitwarden_api_api::models::CipherAttachmentModel {
180 file_name: a.file_name.map(|n| n.to_string()),
181 key: a.key.map(|k| k.to_string()),
182 },
183 )
184 })
185 })
186 .collect(),
187 ),
188 login: cipher.login.map(|l| Box::new(l.into())),
189 card: cipher.card.map(|c| Box::new(c.into())),
190 identity: cipher.identity.map(|i| Box::new(i.into())),
191 secure_note: cipher.secure_note.map(|s| Box::new(s.into())),
192 ssh_key: cipher.ssh_key.map(|s| Box::new(s.into())),
193 bank_account: cipher.bank_account.map(|b| Box::new(b.into())),
194 drivers_license: cipher.drivers_license.map(|d| Box::new(d.into())),
195 passport: cipher.passport.map(|p| Box::new(p.into())),
196 data: cipher.data,
197 last_known_revision_date: Some(
198 cipher
199 .revision_date
200 .to_rfc3339_opts(SecondsFormat::Millis, true),
201 ),
202 archived_date: cipher
203 .archived_date
204 .map(|d| d.to_rfc3339_opts(SecondsFormat::Millis, true)),
205 })
206 }
207}
208
209impl From<EncryptionContext> for CipherRequestModel {
210 fn from(
211 EncryptionContext {
212 cipher,
213 encrypted_for,
214 encrypted_by_key_id,
215 }: EncryptionContext,
216 ) -> Self {
217 Self {
218 encrypted_for: Some(encrypted_for.into()),
219 encrypted_by_key_id,
220 r#type: Some(cipher.r#type.into()),
221 organization_id: cipher.organization_id.map(|o| o.to_string()),
222 is_organization_cipher: None,
223 folder_id: cipher.folder_id.as_ref().map(ToString::to_string),
224 favorite: cipher.favorite.into(),
225 reprompt: Some(cipher.reprompt.into()),
226 key: cipher.key.map(|k| k.to_string()),
227 name: cipher.name.as_ref().map(ToString::to_string),
228 notes: cipher.notes.map(|n| n.to_string()),
229 fields: Some(
230 cipher
231 .fields
232 .into_iter()
233 .flatten()
234 .map(Into::into)
235 .collect(),
236 ),
237 password_history: Some(
238 cipher
239 .password_history
240 .into_iter()
241 .flatten()
242 .map(Into::into)
243 .collect(),
244 ),
245 attachments: None,
246 attachments2: Some(
247 cipher
248 .attachments
249 .into_iter()
250 .flatten()
251 .filter_map(|a| {
252 a.id.map(|id| {
253 (
254 id,
255 bitwarden_api_api::models::CipherAttachmentModel {
256 file_name: a.file_name.map(|n| n.to_string()),
257 key: a.key.map(|k| k.to_string()),
258 },
259 )
260 })
261 })
262 .collect(),
263 ),
264 login: cipher.login.map(|l| Box::new(l.into())),
265 card: cipher.card.map(|c| Box::new(c.into())),
266 identity: cipher.identity.map(|i| Box::new(i.into())),
267 secure_note: cipher.secure_note.map(|s| Box::new(s.into())),
268 ssh_key: cipher.ssh_key.map(|s| Box::new(s.into())),
269 bank_account: cipher.bank_account.map(|b| Box::new(b.into())),
270 drivers_license: cipher.drivers_license.map(|d| Box::new(d.into())),
271 passport: cipher.passport.map(|p| Box::new(p.into())),
272 data: cipher.data,
273 last_known_revision_date: Some(
274 cipher
275 .revision_date
276 .to_rfc3339_opts(SecondsFormat::Millis, true),
277 ),
278 archived_date: cipher
279 .archived_date
280 .map(|d| d.to_rfc3339_opts(SecondsFormat::Millis, true)),
281 }
282 }
283}
284
285#[serde_with::skip_serializing_none]
298#[allow(missing_docs)]
299#[derive(Serialize, Deserialize, Debug, Clone)]
300#[serde(rename_all = "camelCase", deny_unknown_fields)]
301#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
302#[bitwarden_ffi::wasm_record]
303pub struct Cipher {
304 pub id: Option<CipherId>,
305 pub organization_id: Option<OrganizationId>,
306 pub folder_id: Option<FolderId>,
307 pub collection_ids: Vec<CollectionId>,
308 pub key: Option<EncString>,
312
313 pub name: Option<EncString>,
317 pub notes: Option<EncString>,
319
320 pub r#type: CipherType,
321 pub login: Option<Login>,
323 pub identity: Option<identity::Identity>,
325 pub card: Option<card::Card>,
327 pub secure_note: Option<secure_note::SecureNote>,
329 pub ssh_key: Option<ssh_key::SshKey>,
331 pub bank_account: Option<bank_account::BankAccount>,
333 pub drivers_license: Option<drivers_license::DriversLicense>,
335 pub passport: Option<passport::Passport>,
337
338 pub favorite: bool,
339 pub reprompt: CipherRepromptType,
340 pub organization_use_totp: bool,
341 pub edit: bool,
342 pub permissions: Option<CipherPermissions>,
343 pub view_password: bool,
344 pub local_data: Option<LocalData>,
345
346 pub attachments: Option<Vec<attachment::Attachment>>,
347 pub fields: Option<Vec<field::Field>>,
349 pub password_history: Option<Vec<password_history::PasswordHistory>>,
351
352 pub creation_date: DateTime<Utc>,
353 pub deleted_date: Option<DateTime<Utc>>,
354 pub revision_date: DateTime<Utc>,
355 pub archived_date: Option<DateTime<Utc>>,
356 pub data: Option<String>,
359
360 #[serde(default, skip_serializing_if = "Option::is_none")]
365 pub partial_data: Option<String>,
366}
367
368pub enum CipherKeyRewrapError {
371 NoCipherKey,
372 DecryptionFailure,
373 EncryptionFailure,
374}
375
376impl Cipher {
377 pub fn rewrap_cipher_key(
382 &mut self,
383 old_key: SymmetricKeySlotId,
384 new_key: SymmetricKeySlotId,
385 ctx: &mut KeyStoreContext<KeySlotIds>,
386 ) -> Result<(), CipherKeyRewrapError> {
387 let new_cipher_key = self
388 .key
389 .as_ref()
390 .ok_or(CipherKeyRewrapError::NoCipherKey)
391 .and_then(|wrapped_cipher_key| {
392 ctx.unwrap_symmetric_key(old_key, wrapped_cipher_key)
393 .map_err(|_| CipherKeyRewrapError::DecryptionFailure)
394 })
395 .and_then(|cipher_key| {
396 ctx.wrap_symmetric_key(new_key, cipher_key)
397 .map_err(|_| CipherKeyRewrapError::EncryptionFailure)
398 })?;
399 self.key = Some(new_cipher_key);
400 Ok(())
401 }
402
403 pub fn is_blob_encrypted(&self) -> bool {
405 try_parse_blob(self).is_some()
406 }
407}
408
409bitwarden_state::register_repository_item!(CipherId => Cipher, "Cipher");
410
411impl TryFrom<Cipher> for CipherRequestModel {
412 type Error = CryptoError;
413
414 fn try_from(c: Cipher) -> Result<Self, Self::Error> {
421 let attachments2 = c
422 .attachments
423 .map(|list| {
424 list.into_iter()
425 .map(|a| {
426 let id = a.id.clone().ok_or(CryptoError::MissingField("id"))?;
427 Ok::<_, CryptoError>((id, a.into()))
428 })
429 .collect::<Result<_, _>>()
430 })
431 .transpose()?;
432
433 Ok(CipherRequestModel {
434 encrypted_for: None,
435 encrypted_by_key_id: None,
436 r#type: Some(c.r#type.into()),
437 organization_id: c.organization_id.map(|id| id.to_string()),
438 is_organization_cipher: None,
439 folder_id: c.folder_id.map(|id| id.to_string()),
440 favorite: Some(c.favorite),
441 reprompt: Some(c.reprompt.into()),
442 key: c.key.map(|k| k.to_string()),
443 name: c.name.as_ref().map(ToString::to_string),
444 notes: c.notes.map(|n| n.to_string()),
445 login: c.login.map(|v| Box::new(v.into())),
446 card: c.card.map(|v| Box::new(v.into())),
447 identity: c.identity.map(|v| Box::new(v.into())),
448 secure_note: c.secure_note.map(|v| Box::new(v.into())),
449 ssh_key: c.ssh_key.map(|v| Box::new(v.into())),
450 bank_account: c.bank_account.map(|v| Box::new(v.into())),
451 drivers_license: c.drivers_license.map(|v| Box::new(v.into())),
452 passport: c.passport.map(|v| Box::new(v.into())),
453 fields: c.fields.map(|f| f.into_iter().map(Into::into).collect()),
454 password_history: c
455 .password_history
456 .map(|h| h.into_iter().map(Into::into).collect()),
457 attachments: None,
458 attachments2,
459 last_known_revision_date: Some(
460 c.revision_date.to_rfc3339_opts(SecondsFormat::Secs, true),
461 ),
462 archived_date: c.archived_date.map(|d| d.to_rfc3339()),
463 data: c.data,
464 })
465 }
466}
467
468#[serde_with::skip_serializing_none]
469#[allow(missing_docs)]
470#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
471#[serde(rename_all = "camelCase", deny_unknown_fields)]
472#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
473#[bitwarden_ffi::wasm_record]
474pub struct CipherView {
475 pub id: Option<CipherId>,
476 pub organization_id: Option<OrganizationId>,
477 pub folder_id: Option<FolderId>,
478 pub collection_ids: Vec<CollectionId>,
479
480 #[cfg_attr(feature = "wasm", tsify(type = "SymmetricKey | undefined"))]
481 pub key: Option<SymmetricCryptoKey>,
482
483 pub name: String,
484 pub notes: Option<String>,
485
486 pub r#type: CipherType,
487 pub login: Option<LoginView>,
488 pub identity: Option<identity::IdentityView>,
489 pub card: Option<card::CardView>,
490 pub secure_note: Option<secure_note::SecureNoteView>,
491 pub ssh_key: Option<ssh_key::SshKeyView>,
492 pub bank_account: Option<bank_account::BankAccountView>,
493 pub drivers_license: Option<drivers_license::DriversLicenseView>,
494 pub passport: Option<passport::PassportView>,
495
496 pub favorite: bool,
497 pub reprompt: CipherRepromptType,
498 pub organization_use_totp: bool,
499 pub edit: bool,
500 pub permissions: Option<CipherPermissions>,
501 pub view_password: bool,
502 pub local_data: Option<LocalDataView>,
503
504 pub attachments: Option<Vec<attachment::AttachmentView>>,
505 #[serde(skip_serializing_if = "Option::is_none")]
507 pub attachment_decryption_failures: Option<Vec<attachment::AttachmentView>>,
508 pub fields: Option<Vec<field::FieldView>>,
509 pub password_history: Option<Vec<password_history::PasswordHistoryView>>,
510 pub creation_date: DateTime<Utc>,
511 pub deleted_date: Option<DateTime<Utc>>,
512 pub revision_date: DateTime<Utc>,
513 pub archived_date: Option<DateTime<Utc>>,
514
515 #[serde(default)]
522 pub partial: bool,
523}
524
525#[allow(missing_docs)]
526#[derive(Serialize, Deserialize, Debug, PartialEq)]
527#[serde(rename_all = "camelCase", deny_unknown_fields)]
528#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
529#[bitwarden_ffi::wasm_record]
530pub enum CipherListViewType {
531 Login(LoginListView),
532 SecureNote,
533 Card(CardListView),
534 Identity,
535 SshKey,
536 BankAccount(BankAccountListView),
537 Passport,
538 DriversLicense,
539}
540
541#[derive(Serialize, Deserialize, Debug, PartialEq)]
543#[bitwarden_ffi::wasm_record]
544#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
545pub enum CopyableCipherFields {
546 LoginUsername,
547 LoginPassword,
548 LoginTotp,
549 CardNumber,
550 CardSecurityCode,
551 IdentityUsername,
552 IdentityEmail,
553 IdentityPhone,
554 IdentityAddress,
555 SshKey,
556 SecureNotes,
557 BankAccountNameOnAccount,
558 BankAccountAccountNumber,
559 BankAccountRoutingNumber,
560 BankAccountBranchNumber,
561 BankAccountPin,
562 BankAccountIban,
563 BankAccountSwift,
564 PassportGivenName,
565 PassportSurname,
566 PassportPassportNumber,
567 PassportNationalIdentificationNumber,
568 DriversLicenseFirstName,
569 DriversLicenseMiddleName,
570 DriversLicenseLastName,
571 DriversLicenseLicenseNumber,
572}
573
574#[serde_with::skip_serializing_none]
575#[allow(missing_docs)]
576#[derive(Serialize, Deserialize, Debug, PartialEq)]
577#[serde(rename_all = "camelCase", deny_unknown_fields)]
578#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
579#[bitwarden_ffi::wasm_record]
580pub struct CipherListView {
581 pub id: Option<CipherId>,
582 pub organization_id: Option<OrganizationId>,
583 pub folder_id: Option<FolderId>,
584 pub collection_ids: Vec<CollectionId>,
585
586 pub name: String,
587 pub subtitle: String,
588
589 pub r#type: CipherListViewType,
590
591 pub favorite: bool,
592 pub reprompt: CipherRepromptType,
593 pub organization_use_totp: bool,
594 pub edit: bool,
595 pub permissions: Option<CipherPermissions>,
596
597 pub view_password: bool,
598
599 pub attachments: u32,
601 pub has_old_attachments: bool,
603
604 pub creation_date: DateTime<Utc>,
605 pub deleted_date: Option<DateTime<Utc>>,
606 pub revision_date: DateTime<Utc>,
607 pub archived_date: Option<DateTime<Utc>>,
608
609 pub copyable_fields: Vec<CopyableCipherFields>,
611
612 pub local_data: Option<LocalDataView>,
613
614 #[serde(default)]
617 pub partial: bool,
618
619 #[cfg(feature = "wasm")]
621 pub notes: Option<String>,
622 #[cfg(feature = "wasm")]
625 pub fields: Option<Vec<field::FieldListView>>,
626 #[cfg(feature = "wasm")]
628 pub attachment_names: Option<Vec<String>>,
629}
630
631#[derive(Serialize, Deserialize, Debug)]
637#[serde(rename_all = "camelCase", deny_unknown_fields)]
638#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
639#[bitwarden_ffi::wasm_record]
640pub struct DecryptCipherListResult {
641 pub successes: Vec<CipherListView>,
643 pub failures: Vec<Cipher>,
645}
646
647#[derive(Serialize, Deserialize, Debug)]
653#[serde(rename_all = "camelCase", deny_unknown_fields)]
654#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
655#[bitwarden_ffi::wasm_record]
656pub struct DecryptCipherResult {
657 pub successes: Vec<CipherView>,
659 pub failures: Vec<Cipher>,
661}
662
663#[derive(Serialize, Deserialize, Debug)]
667#[serde(rename_all = "camelCase", deny_unknown_fields)]
668#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
669#[bitwarden_ffi::wasm_record]
670pub struct ListOrganizationCiphersResult {
671 pub ciphers: Vec<Cipher>,
673 pub list_views: Vec<CipherListView>,
675}
676
677impl CipherListView {
678 pub(crate) fn get_totp_key(self) -> Result<Option<String>, CryptoError> {
679 Ok(match self.r#type {
680 CipherListViewType::Login(LoginListView { totp, .. }) => totp,
681 _ => None,
682 })
683 }
684}
685
686impl CipherView {
687 fn encrypt_legacy_field_encryption(
688 &mut self,
689 ctx: &mut KeyStoreContext<KeySlotIds>,
690 key: SymmetricKeySlotId,
691 ) -> Result<Cipher, CryptoError> {
692 if self.partial {
696 return Err(CryptoError::EncryptRestrictedView);
697 }
698
699 let ciphers_key = self.load_cipher_key_slot(ctx)?;
700
701 self.generate_checksums();
702
703 Ok(Cipher {
704 partial_data: None,
705 id: self.id,
706 organization_id: self.organization_id,
707 folder_id: self.folder_id,
708 collection_ids: self.collection_ids.clone(),
709 key: Some(ctx.wrap_symmetric_key(key, ciphers_key)?),
710 name: Some(self.name.encrypt(ctx, ciphers_key)?),
711 notes: self.notes.encrypt(ctx, ciphers_key)?,
712 r#type: self.r#type,
713 login: self.login.encrypt_composite(ctx, ciphers_key)?,
714 identity: self.identity.encrypt_composite(ctx, ciphers_key)?,
715 card: self.card.encrypt_composite(ctx, ciphers_key)?,
716 secure_note: self.secure_note.encrypt_composite(ctx, ciphers_key)?,
717 ssh_key: self.ssh_key.encrypt_composite(ctx, ciphers_key)?,
718 bank_account: self.bank_account.encrypt_composite(ctx, ciphers_key)?,
719 drivers_license: self.drivers_license.encrypt_composite(ctx, ciphers_key)?,
720 passport: self.passport.encrypt_composite(ctx, ciphers_key)?,
721 favorite: self.favorite,
722 reprompt: self.reprompt,
723 organization_use_totp: self.organization_use_totp,
724 edit: self.edit,
725 view_password: self.view_password,
726 local_data: self.local_data.encrypt_composite(ctx, ciphers_key)?,
727 attachments: self.attachments.encrypt_composite(ctx, ciphers_key)?,
728 fields: self.fields.encrypt_composite(ctx, ciphers_key)?,
729 password_history: self.password_history.encrypt_composite(ctx, ciphers_key)?,
730 creation_date: self.creation_date,
731 deleted_date: self.deleted_date,
732 revision_date: self.revision_date,
733 permissions: self.permissions,
734 archived_date: self.archived_date,
735 data: None, })
737 }
738}
739
740pub(crate) fn lenient_decrypt_cipher_view(
746 cipher: &Cipher,
747 ctx: &mut KeyStoreContext<KeySlotIds>,
748 key: SymmetricKeySlotId,
749) -> Result<CipherView, CryptoError> {
750 let ciphers_key = Cipher::decrypt_cipher_key(ctx, key, &cipher.key)?;
751
752 let (attachments, attachment_decryption_failures) =
754 attachment::decrypt_attachments_with_failures(
755 cipher.attachments.as_deref().unwrap_or_default(),
756 ctx,
757 ciphers_key,
758 );
759
760 let mut view = CipherView {
761 partial: false,
762 id: cipher.id,
763 organization_id: cipher.organization_id,
764 folder_id: cipher.folder_id,
765 collection_ids: cipher.collection_ids.clone(),
766 key: if cipher.key.is_some() {
767 #[allow(deprecated)]
768 Some(ctx.dangerous_get_symmetric_key(ciphers_key)?.clone())
769 } else {
770 None
771 },
772 name: cipher
773 .name
774 .as_ref()
775 .and_then(|n| n.decrypt(ctx, ciphers_key).ok())
776 .unwrap_or_default(),
777 notes: cipher.notes.decrypt(ctx, ciphers_key).ok().flatten(),
778 r#type: cipher.r#type,
779 login: cipher.login.decrypt(ctx, ciphers_key).ok().flatten(),
780 identity: cipher.identity.decrypt(ctx, ciphers_key).ok().flatten(),
781 card: cipher.card.decrypt(ctx, ciphers_key).ok().flatten(),
782 secure_note: cipher.secure_note.decrypt(ctx, ciphers_key).ok().flatten(),
783 ssh_key: cipher.ssh_key.decrypt(ctx, ciphers_key).ok().flatten(),
784 bank_account: cipher.bank_account.decrypt(ctx, ciphers_key).ok().flatten(),
785 drivers_license: cipher
786 .drivers_license
787 .decrypt(ctx, ciphers_key)
788 .ok()
789 .flatten(),
790 passport: cipher.passport.decrypt(ctx, ciphers_key).ok().flatten(),
791 favorite: cipher.favorite,
792 reprompt: cipher.reprompt,
793 organization_use_totp: cipher.organization_use_totp,
794 edit: cipher.edit,
795 permissions: cipher.permissions,
796 view_password: cipher.view_password,
797 local_data: cipher.local_data.decrypt(ctx, ciphers_key).ok().flatten(),
798 attachments: Some(attachments),
799 attachment_decryption_failures: Some(attachment_decryption_failures),
800 fields: cipher.fields.decrypt(ctx, ciphers_key).ok().flatten(),
801 password_history: cipher
802 .password_history
803 .decrypt(ctx, ciphers_key)
804 .ok()
805 .flatten(),
806 creation_date: cipher.creation_date,
807 deleted_date: cipher.deleted_date,
808 revision_date: cipher.revision_date,
809 archived_date: cipher.archived_date,
810 };
811
812 if view.key.is_some()
815 || ctx.get_security_state_version() >= MINIMUM_ENFORCE_ICON_URI_HASH_VERSION
816 {
817 view.remove_invalid_checksums();
818 }
819
820 Ok(view)
821}
822
823impl Cipher {
824 #[bitwarden_logging::instrument(err)]
835 pub(crate) fn decrypt_cipher_key(
836 ctx: &mut KeyStoreContext<KeySlotIds>,
837 key: SymmetricKeySlotId,
838 ciphers_key: &Option<EncString>,
839 ) -> Result<SymmetricKeySlotId, CryptoError> {
840 match ciphers_key {
841 Some(ciphers_key) => ctx.unwrap_symmetric_key(key, ciphers_key),
842 None => Ok(key),
843 }
844 }
845
846 #[bitwarden_logging::instrument(err)]
854 pub(crate) fn make_attachment_material(
855 &self,
856 ctx: &mut KeyStoreContext<KeySlotIds>,
857 file_name: &str,
858 ) -> Result<attachment::AttachmentMaterial, CryptoError> {
859 let cipher_key = Self::decrypt_cipher_key(ctx, self.key_identifier(), &self.key)?;
860 let key = SymmetricCryptoKey::make(SymmetricKeyAlgorithm::Aes256CbcHmac);
861 let slot = ctx.add_local_symmetric_key(key.clone());
862 let wrapped_key = ctx.wrap_symmetric_key(cipher_key, slot)?;
863 let encrypted_file_name = file_name.encrypt(ctx, cipher_key)?;
864 Ok(attachment::AttachmentMaterial {
865 key,
866 wrapped_key,
867 encrypted_file_name,
868 })
869 }
870
871 fn get_kind(&self) -> Option<&dyn CipherKind> {
873 match self.r#type {
874 CipherType::Login => self.login.as_ref().map(|v| v as _),
875 CipherType::Card => self.card.as_ref().map(|v| v as _),
876 CipherType::Identity => self.identity.as_ref().map(|v| v as _),
877 CipherType::SshKey => self.ssh_key.as_ref().map(|v| v as _),
878 CipherType::SecureNote => self.secure_note.as_ref().map(|v| v as _),
879 CipherType::BankAccount => self.bank_account.as_ref().map(|v| v as _),
880 CipherType::DriversLicense => self.drivers_license.as_ref().map(|v| v as _),
881 CipherType::Passport => self.passport.as_ref().map(|v| v as _),
882 }
883 }
884
885 fn decrypt_subtitle(
887 &self,
888 ctx: &mut KeyStoreContext<KeySlotIds>,
889 key: SymmetricKeySlotId,
890 ) -> Result<String, CryptoError> {
891 self.get_kind()
892 .map(|sub| sub.decrypt_subtitle(ctx, key))
893 .unwrap_or_else(|| Ok(String::new()))
894 }
895
896 fn get_copyable_fields(&self) -> Vec<CopyableCipherFields> {
899 self.get_kind()
900 .map(|kind| kind.get_copyable_fields(Some(self)))
901 .unwrap_or_default()
902 }
903
904 #[allow(unused)] pub(crate) fn populate_cipher_types(&mut self) -> Result<(), VaultParseError> {
910 let data = self
911 .data
912 .as_ref()
913 .ok_or(VaultParseError::MissingField(MissingFieldError("data")))?;
914
915 match &self.r#type {
916 crate::CipherType::Login => self.login = serde_json::from_str(data)?,
917 crate::CipherType::SecureNote => self.secure_note = serde_json::from_str(data)?,
918 crate::CipherType::Card => self.card = serde_json::from_str(data)?,
919 crate::CipherType::Identity => self.identity = serde_json::from_str(data)?,
920 crate::CipherType::SshKey => self.ssh_key = serde_json::from_str(data)?,
921 crate::CipherType::BankAccount => self.bank_account = serde_json::from_str(data)?,
922 crate::CipherType::DriversLicense => self.drivers_license = serde_json::from_str(data)?,
923 crate::CipherType::Passport => self.passport = serde_json::from_str(data)?,
924 }
925 Ok(())
926 }
927
928 pub(crate) fn soft_delete(&mut self) {
930 self.deleted_date = Some(Utc::now());
931 }
932}
933impl CipherView {
934 pub fn load_cipher_key_slot(
937 &mut self,
938 ctx: &mut KeyStoreContext<KeySlotIds>,
939 ) -> Result<SymmetricKeySlotId, CryptoError> {
940 if let Some(key) = &self.key {
941 return Ok(ctx.add_local_symmetric_key(key.clone()));
942 }
943
944 let new_key = ctx.generate_symmetric_key();
945 #[allow(deprecated)]
946 let new_key_raw = ctx.dangerous_get_symmetric_key(new_key)?.clone();
947 self.key = Some(new_key_raw);
948 Ok(new_key)
949 }
950
951 #[allow(missing_docs)]
952 pub fn generate_checksums(&mut self) {
953 if let Some(l) = self.login.as_mut() {
954 l.generate_checksums();
955 }
956 }
957
958 #[allow(missing_docs)]
959 pub fn remove_invalid_checksums(&mut self) {
960 if let Some(uris) = self.login.as_mut().and_then(|l| l.uris.as_mut()) {
961 uris.retain(|u| u.is_checksum_valid());
962 }
963 }
964
965 #[allow(missing_docs)]
966 pub fn get_fido2_credentials(&self) -> Vec<Fido2CredentialView> {
967 self.login
968 .as_ref()
969 .and_then(|l| l.fido2_credentials.as_ref())
970 .cloned()
971 .unwrap_or_default()
972 }
973
974 pub fn move_to_organization(
979 &mut self,
980 organization_id: OrganizationId,
981 ) -> Result<(), CipherError> {
982 self.validate_attachment_keys()?;
983 self.organization_id = Some(organization_id);
984
985 Ok(())
986 }
987
988 pub fn validate_attachment_keys(&mut self) -> Result<(), CipherError> {
993 if self.attachments.iter().flatten().any(|a| a.key.is_none()) {
994 return Err(CipherError::AttachmentsWithoutKeys);
995 }
996 Ok(())
997 }
998
999 #[allow(missing_docs)]
1000 pub fn set_new_fido2_credentials(
1001 &mut self,
1002 creds: Vec<Fido2CredentialFullView>,
1003 ) -> Result<(), CipherError> {
1004 require!(self.login.as_mut()).fido2_credentials =
1005 Some(creds.into_iter().map(Fido2CredentialView::from).collect());
1006 Ok(())
1007 }
1008
1009 pub(crate) fn update_password_history(&mut self, original_cipher: &CipherView) {
1010 let changes = self
1011 .login
1012 .as_mut()
1013 .map_or(vec![], |login| {
1014 login.detect_password_change(&original_cipher.login)
1015 })
1016 .into_iter()
1017 .chain(self.fields.as_deref().map_or(vec![], |fields| {
1018 FieldView::detect_hidden_field_changes(
1019 fields,
1020 original_cipher.fields.as_deref().unwrap_or(&[]),
1021 )
1022 }))
1023 .rev()
1024 .chain(original_cipher.password_history.iter().flatten().cloned())
1025 .take(MAX_PASSWORD_HISTORY_ENTRIES)
1026 .collect();
1027 self.password_history = Some(changes)
1028 }
1029
1030 pub(crate) fn to_list_view(&self) -> Result<CipherListView, CryptoError> {
1036 let all_attachments = || {
1037 self.attachments
1038 .iter()
1039 .flatten()
1040 .chain(self.attachment_decryption_failures.iter().flatten())
1041 };
1042 let attachments_count = all_attachments().count() as u32;
1043 let has_old_attachments = all_attachments().any(|att| att.key.is_none());
1044
1045 let list_type = match self.r#type {
1046 CipherType::Login => {
1047 let login = self
1048 .login
1049 .as_ref()
1050 .ok_or(CryptoError::MissingField("login"))?;
1051 CipherListViewType::Login(login.to_list_view())
1052 }
1053 CipherType::SecureNote => CipherListViewType::SecureNote,
1054 CipherType::Card => {
1055 let card = self
1056 .card
1057 .as_ref()
1058 .ok_or(CryptoError::MissingField("card"))?;
1059 CipherListViewType::Card(CardListView {
1060 brand: card.brand.clone(),
1061 })
1062 }
1063 CipherType::Identity => CipherListViewType::Identity,
1064 CipherType::SshKey => CipherListViewType::SshKey,
1065 CipherType::BankAccount => {
1066 let bank_account = self
1067 .bank_account
1068 .as_ref()
1069 .ok_or(CryptoError::MissingField("bank_account"))?;
1070 CipherListViewType::BankAccount(BankAccountListView {
1071 account_number: bank_account.account_number.clone(),
1072 account_type: bank_account.account_type.clone(),
1073 })
1074 }
1075 CipherType::DriversLicense => CipherListViewType::DriversLicense,
1076 CipherType::Passport => CipherListViewType::Passport,
1077 };
1078
1079 Ok(CipherListView {
1080 partial: false,
1081 id: self.id,
1082 organization_id: self.organization_id,
1083 folder_id: self.folder_id,
1084 collection_ids: self.collection_ids.clone(),
1085 name: self.name.clone(),
1086 subtitle: self.subtitle(),
1087 r#type: list_type,
1088 favorite: self.favorite,
1089 reprompt: self.reprompt,
1090 organization_use_totp: self.organization_use_totp,
1091 edit: self.edit,
1092 permissions: self.permissions,
1093 view_password: self.view_password,
1094 attachments: attachments_count,
1095 has_old_attachments,
1096 creation_date: self.creation_date,
1097 deleted_date: self.deleted_date,
1098 revision_date: self.revision_date,
1099 archived_date: self.archived_date,
1100 copyable_fields: self.get_copyable_fields(),
1101 local_data: self.local_data.clone(),
1102 #[cfg(feature = "wasm")]
1103 notes: self.notes.clone(),
1104 #[cfg(feature = "wasm")]
1105 fields: self.fields.as_ref().map(|fields| {
1106 fields
1107 .iter()
1108 .cloned()
1109 .map(field::FieldListView::from)
1110 .collect()
1111 }),
1112 #[cfg(feature = "wasm")]
1113 attachment_names: self.attachments.as_ref().map(|attachments| {
1114 attachments
1115 .iter()
1116 .filter_map(|a| a.file_name.clone())
1117 .collect()
1118 }),
1119 })
1120 }
1121
1122 fn subtitle(&self) -> String {
1127 match self.r#type {
1128 CipherType::Login => self
1129 .login
1130 .as_ref()
1131 .and_then(|l| l.username.clone())
1132 .unwrap_or_default(),
1133 CipherType::Card => self
1134 .card
1135 .as_ref()
1136 .map(|c| card::build_subtitle_card(c.brand.clone(), c.number.clone()))
1137 .unwrap_or_default(),
1138 CipherType::Identity => self
1139 .identity
1140 .as_ref()
1141 .map(|i| {
1142 identity::build_subtitle_identity(i.first_name.clone(), i.last_name.clone())
1143 })
1144 .unwrap_or_default(),
1145 CipherType::SshKey => self
1146 .ssh_key
1147 .as_ref()
1148 .map(|s| s.fingerprint.clone())
1149 .unwrap_or_default(),
1150 CipherType::SecureNote => String::new(),
1151 CipherType::BankAccount => self
1152 .bank_account
1153 .as_ref()
1154 .map(|b| b.bank_name.clone().unwrap_or_default())
1155 .unwrap_or_default(),
1156 CipherType::DriversLicense => self
1157 .drivers_license
1158 .as_ref()
1159 .map(|d| {
1160 drivers_license::build_subtitle_drivers_license(
1161 d.first_name.clone(),
1162 d.last_name.clone(),
1163 d.issuing_state.clone(),
1164 )
1165 })
1166 .unwrap_or_default(),
1167 CipherType::Passport => self
1168 .passport
1169 .as_ref()
1170 .map(|p| {
1171 passport::build_subtitle_passport(
1172 p.given_name.clone(),
1173 p.surname.clone(),
1174 p.issuing_country.clone(),
1175 )
1176 })
1177 .unwrap_or_default(),
1178 }
1179 }
1180
1181 fn get_copyable_fields(&self) -> Vec<CopyableCipherFields> {
1186 match self.r#type {
1187 CipherType::Login => self
1188 .login
1189 .as_ref()
1190 .map(|l| {
1191 [
1192 l.username
1193 .as_ref()
1194 .map(|_| CopyableCipherFields::LoginUsername),
1195 l.password
1196 .as_ref()
1197 .map(|_| CopyableCipherFields::LoginPassword),
1198 l.totp.as_ref().map(|_| CopyableCipherFields::LoginTotp),
1199 ]
1200 .into_iter()
1201 .flatten()
1202 .collect()
1203 })
1204 .unwrap_or_default(),
1205 CipherType::Card => self
1206 .card
1207 .as_ref()
1208 .map(|c| {
1209 [
1210 c.number.as_ref().map(|_| CopyableCipherFields::CardNumber),
1211 c.code
1212 .as_ref()
1213 .map(|_| CopyableCipherFields::CardSecurityCode),
1214 ]
1215 .into_iter()
1216 .flatten()
1217 .collect()
1218 })
1219 .unwrap_or_default(),
1220 CipherType::Identity => self
1221 .identity
1222 .as_ref()
1223 .map(|i| {
1224 [
1225 i.username
1226 .as_ref()
1227 .map(|_| CopyableCipherFields::IdentityUsername),
1228 i.email
1229 .as_ref()
1230 .map(|_| CopyableCipherFields::IdentityEmail),
1231 i.phone
1232 .as_ref()
1233 .map(|_| CopyableCipherFields::IdentityPhone),
1234 i.address1
1235 .as_ref()
1236 .or(i.address2.as_ref())
1237 .or(i.address3.as_ref())
1238 .or(i.city.as_ref())
1239 .or(i.state.as_ref())
1240 .or(i.postal_code.as_ref())
1241 .map(|_| CopyableCipherFields::IdentityAddress),
1242 ]
1243 .into_iter()
1244 .flatten()
1245 .collect()
1246 })
1247 .unwrap_or_default(),
1248 CipherType::SshKey => vec![CopyableCipherFields::SshKey],
1249 CipherType::SecureNote => self
1250 .notes
1251 .as_ref()
1252 .map(|_| vec![CopyableCipherFields::SecureNotes])
1253 .unwrap_or_default(),
1254 CipherType::BankAccount => self
1255 .bank_account
1256 .as_ref()
1257 .map(|b| {
1258 [
1259 b.name_on_account
1260 .as_ref()
1261 .map(|_| CopyableCipherFields::BankAccountNameOnAccount),
1262 b.account_number
1263 .as_ref()
1264 .map(|_| CopyableCipherFields::BankAccountAccountNumber),
1265 b.routing_number
1266 .as_ref()
1267 .map(|_| CopyableCipherFields::BankAccountRoutingNumber),
1268 b.branch_number
1269 .as_ref()
1270 .map(|_| CopyableCipherFields::BankAccountBranchNumber),
1271 b.pin.as_ref().map(|_| CopyableCipherFields::BankAccountPin),
1272 b.iban
1273 .as_ref()
1274 .map(|_| CopyableCipherFields::BankAccountIban),
1275 b.swift_code
1276 .as_ref()
1277 .map(|_| CopyableCipherFields::BankAccountSwift),
1278 ]
1279 .into_iter()
1280 .flatten()
1281 .collect()
1282 })
1283 .unwrap_or_default(),
1284 CipherType::DriversLicense => self
1285 .drivers_license
1286 .as_ref()
1287 .map(|d| {
1288 [
1289 d.first_name
1290 .as_ref()
1291 .map(|_| CopyableCipherFields::DriversLicenseFirstName),
1292 d.middle_name
1293 .as_ref()
1294 .map(|_| CopyableCipherFields::DriversLicenseMiddleName),
1295 d.last_name
1296 .as_ref()
1297 .map(|_| CopyableCipherFields::DriversLicenseLastName),
1298 d.license_number
1299 .as_ref()
1300 .map(|_| CopyableCipherFields::DriversLicenseLicenseNumber),
1301 ]
1302 .into_iter()
1303 .flatten()
1304 .collect()
1305 })
1306 .unwrap_or_default(),
1307 CipherType::Passport => self
1308 .passport
1309 .as_ref()
1310 .map(|p| {
1311 [
1312 p.given_name
1313 .as_ref()
1314 .map(|_| CopyableCipherFields::PassportGivenName),
1315 p.surname
1316 .as_ref()
1317 .map(|_| CopyableCipherFields::PassportSurname),
1318 p.passport_number
1319 .as_ref()
1320 .map(|_| CopyableCipherFields::PassportPassportNumber),
1321 p.national_identification_number
1322 .as_ref()
1323 .map(|_| CopyableCipherFields::PassportNationalIdentificationNumber),
1324 ]
1325 .into_iter()
1326 .flatten()
1327 .collect()
1328 })
1329 .unwrap_or_default(),
1330 }
1331 }
1332}
1333
1334pub(crate) fn lenient_decrypt_cipher_list_view(
1337 cipher: &Cipher,
1338 ctx: &mut KeyStoreContext<KeySlotIds>,
1339 key: SymmetricKeySlotId,
1340) -> Result<CipherListView, CryptoError> {
1341 let ciphers_key = Cipher::decrypt_cipher_key(ctx, key, &cipher.key)?;
1342
1343 Ok(CipherListView {
1344 partial: false,
1345 id: cipher.id,
1346 organization_id: cipher.organization_id,
1347 folder_id: cipher.folder_id,
1348 collection_ids: cipher.collection_ids.clone(),
1349 name: cipher
1350 .name
1351 .as_ref()
1352 .and_then(|n| n.decrypt(ctx, ciphers_key).ok())
1353 .unwrap_or_default(),
1354 subtitle: cipher
1355 .decrypt_subtitle(ctx, ciphers_key)
1356 .ok()
1357 .unwrap_or_default(),
1358 r#type: match cipher.r#type {
1359 CipherType::Login => {
1360 let login = cipher
1361 .login
1362 .as_ref()
1363 .ok_or(CryptoError::MissingField("login"))?;
1364 CipherListViewType::Login(login.decrypt(ctx, ciphers_key)?)
1365 }
1366 CipherType::SecureNote => CipherListViewType::SecureNote,
1367 CipherType::Card => {
1368 let card = cipher
1369 .card
1370 .as_ref()
1371 .ok_or(CryptoError::MissingField("card"))?;
1372 CipherListViewType::Card(card.decrypt(ctx, ciphers_key)?)
1373 }
1374 CipherType::Identity => CipherListViewType::Identity,
1375 CipherType::SshKey => CipherListViewType::SshKey,
1376 CipherType::BankAccount => {
1377 let bank_account = cipher
1378 .bank_account
1379 .as_ref()
1380 .ok_or(CryptoError::MissingField("bank_account"))?;
1381 CipherListViewType::BankAccount(bank_account.decrypt(ctx, ciphers_key)?)
1382 }
1383 CipherType::Passport => CipherListViewType::Passport,
1384 CipherType::DriversLicense => CipherListViewType::DriversLicense,
1385 },
1386 favorite: cipher.favorite,
1387 reprompt: cipher.reprompt,
1388 organization_use_totp: cipher.organization_use_totp,
1389 edit: cipher.edit,
1390 permissions: cipher.permissions,
1391 view_password: cipher.view_password,
1392 attachments: cipher
1393 .attachments
1394 .as_ref()
1395 .map(|a| a.len() as u32)
1396 .unwrap_or(0),
1397 has_old_attachments: cipher
1398 .attachments
1399 .as_ref()
1400 .map(|a| a.iter().any(|att| att.key.is_none()))
1401 .unwrap_or(false),
1402 creation_date: cipher.creation_date,
1403 deleted_date: cipher.deleted_date,
1404 revision_date: cipher.revision_date,
1405 copyable_fields: cipher.get_copyable_fields(),
1406 local_data: cipher.local_data.decrypt(ctx, ciphers_key)?,
1407 archived_date: cipher.archived_date,
1408 #[cfg(feature = "wasm")]
1409 notes: cipher.notes.decrypt(ctx, ciphers_key).ok().flatten(),
1410 #[cfg(feature = "wasm")]
1411 fields: cipher.fields.as_ref().map(|fields| {
1412 fields
1413 .iter()
1414 .filter_map(|f| {
1415 f.decrypt(ctx, ciphers_key)
1416 .ok()
1417 .map(field::FieldListView::from)
1418 })
1419 .collect()
1420 }),
1421 #[cfg(feature = "wasm")]
1422 attachment_names: cipher.attachments.as_ref().map(|attachments| {
1423 attachments
1424 .iter()
1425 .filter_map(|a| a.file_name.decrypt(ctx, ciphers_key).ok().flatten())
1426 .collect()
1427 }),
1428 })
1429}
1430
1431impl IdentifyKey<SymmetricKeySlotId> for Cipher {
1432 fn key_identifier(&self) -> SymmetricKeySlotId {
1433 match self.organization_id {
1434 Some(organization_id) => SymmetricKeySlotId::Organization(organization_id),
1435 None => SymmetricKeySlotId::User,
1436 }
1437 }
1438}
1439
1440#[derive(Deserialize, Default)]
1449#[serde(rename_all = "camelCase")]
1450struct RestrictedCipherData {
1451 name: Option<EncString>,
1452 uris: Option<Vec<LoginUri>>,
1453}
1454
1455fn decrypt_restricted_name(
1459 restricted: &RestrictedCipherData,
1460 ctx: &mut KeyStoreContext<KeySlotIds>,
1461 ciphers_key: SymmetricKeySlotId,
1462 strict: bool,
1463) -> Result<String, CryptoError> {
1464 let Some(name) = restricted.name.as_ref() else {
1465 return Ok(String::new());
1466 };
1467 if strict {
1468 name.decrypt(ctx, ciphers_key)
1469 } else {
1470 Ok(name.decrypt(ctx, ciphers_key).ok().unwrap_or_default())
1471 }
1472}
1473
1474fn decrypt_restricted_uris(
1477 restricted: &RestrictedCipherData,
1478 ctx: &mut KeyStoreContext<KeySlotIds>,
1479 ciphers_key: SymmetricKeySlotId,
1480 strict: bool,
1481) -> Result<Option<Vec<LoginUriView>>, CryptoError> {
1482 if strict {
1483 restricted.uris.decrypt(ctx, ciphers_key)
1484 } else {
1485 Ok(restricted.uris.decrypt(ctx, ciphers_key).ok().flatten())
1486 }
1487}
1488
1489fn decrypt_restricted_cipher_view(
1498 cipher: &Cipher,
1499 raw: &str,
1500 ctx: &mut KeyStoreContext<KeySlotIds>,
1501 key: SymmetricKeySlotId,
1502 strict: bool,
1503) -> Result<CipherView, CryptoError> {
1504 let ciphers_key = Cipher::decrypt_cipher_key(ctx, key, &cipher.key)?;
1505 let restricted: RestrictedCipherData = serde_json::from_str(raw).unwrap_or_default();
1506
1507 let name = decrypt_restricted_name(&restricted, ctx, ciphers_key, strict)?;
1508
1509 let login = if matches!(cipher.r#type, CipherType::Login) {
1512 Some(LoginView {
1513 username: None,
1514 password: None,
1515 password_revision_date: None,
1516 uris: decrypt_restricted_uris(&restricted, ctx, ciphers_key, strict)?,
1517 totp: None,
1518 autofill_on_page_load: None,
1519 http_authentication_enabled: None,
1520 fido2_credentials: None,
1521 })
1522 } else {
1523 None
1524 };
1525
1526 let mut view = CipherView {
1527 id: cipher.id,
1528 organization_id: cipher.organization_id,
1529 folder_id: cipher.folder_id,
1530 collection_ids: cipher.collection_ids.clone(),
1531 key: None,
1534 name,
1535 notes: None,
1536 r#type: cipher.r#type,
1537 login,
1538 identity: None,
1539 card: None,
1540 secure_note: None,
1541 ssh_key: None,
1542 bank_account: None,
1543 drivers_license: None,
1544 passport: None,
1545 favorite: cipher.favorite,
1546 reprompt: cipher.reprompt,
1547 organization_use_totp: cipher.organization_use_totp,
1548 edit: cipher.edit,
1549 permissions: cipher.permissions,
1550 view_password: cipher.view_password,
1551 local_data: cipher.local_data.decrypt(ctx, ciphers_key).ok().flatten(),
1552 attachments: None,
1553 attachment_decryption_failures: None,
1554 fields: None,
1555 password_history: None,
1556 creation_date: cipher.creation_date,
1557 deleted_date: cipher.deleted_date,
1558 revision_date: cipher.revision_date,
1559 archived_date: cipher.archived_date,
1560 partial: true,
1561 };
1562
1563 if cipher.key.is_some()
1566 || ctx.get_security_state_version() >= MINIMUM_ENFORCE_ICON_URI_HASH_VERSION
1567 {
1568 view.remove_invalid_checksums();
1569 }
1570
1571 Ok(view)
1572}
1573
1574fn decrypt_restricted_cipher_list_view(
1579 cipher: &Cipher,
1580 raw: &str,
1581 ctx: &mut KeyStoreContext<KeySlotIds>,
1582 key: SymmetricKeySlotId,
1583 strict: bool,
1584) -> Result<CipherListView, CryptoError> {
1585 let ciphers_key = Cipher::decrypt_cipher_key(ctx, key, &cipher.key)?;
1586 let restricted: RestrictedCipherData = serde_json::from_str(raw).unwrap_or_default();
1587
1588 let name = decrypt_restricted_name(&restricted, ctx, ciphers_key, strict)?;
1589
1590 let r#type = match cipher.r#type {
1591 CipherType::Login => CipherListViewType::Login(LoginListView {
1592 fido2_credentials: None,
1593 has_fido2: false,
1594 username: None,
1595 totp: None,
1596 uris: decrypt_restricted_uris(&restricted, ctx, ciphers_key, strict)?,
1597 }),
1598 CipherType::SecureNote => CipherListViewType::SecureNote,
1599 CipherType::Card => CipherListViewType::Card(CardListView { brand: None }),
1600 CipherType::Identity => CipherListViewType::Identity,
1601 CipherType::SshKey => CipherListViewType::SshKey,
1602 CipherType::BankAccount => CipherListViewType::BankAccount(BankAccountListView {
1603 account_number: None,
1604 account_type: None,
1605 }),
1606 CipherType::Passport => CipherListViewType::Passport,
1607 CipherType::DriversLicense => CipherListViewType::DriversLicense,
1608 };
1609
1610 Ok(CipherListView {
1611 id: cipher.id,
1612 organization_id: cipher.organization_id,
1613 folder_id: cipher.folder_id,
1614 collection_ids: cipher.collection_ids.clone(),
1615 name,
1616 subtitle: String::new(),
1617 r#type,
1618 favorite: cipher.favorite,
1619 reprompt: cipher.reprompt,
1620 organization_use_totp: cipher.organization_use_totp,
1621 edit: cipher.edit,
1622 permissions: cipher.permissions,
1623 view_password: cipher.view_password,
1624 attachments: 0,
1625 has_old_attachments: false,
1626 creation_date: cipher.creation_date,
1627 deleted_date: cipher.deleted_date,
1628 revision_date: cipher.revision_date,
1629 archived_date: cipher.archived_date,
1630 copyable_fields: vec![],
1631 local_data: cipher.local_data.decrypt(ctx, ciphers_key).ok().flatten(),
1632 partial: true,
1633 #[cfg(feature = "wasm")]
1634 notes: None,
1635 #[cfg(feature = "wasm")]
1636 fields: None,
1637 #[cfg(feature = "wasm")]
1638 attachment_names: None,
1639 })
1640}
1641
1642impl Decryptable<KeySlotIds, SymmetricKeySlotId, CipherView> for Cipher {
1643 #[bitwarden_logging::instrument(err, fields(cipher_id = ?self.id, org_id = ?self.organization_id, kind = ?self.r#type))]
1644 fn decrypt(
1645 &self,
1646 ctx: &mut KeyStoreContext<KeySlotIds>,
1647 key: SymmetricKeySlotId,
1648 ) -> Result<CipherView, CryptoError> {
1649 if let Some(raw) = &self.partial_data {
1650 if self.organization_id.is_none() {
1654 return Err(CryptoError::RestrictedCipherRequiresOrganization);
1655 }
1656 return decrypt_restricted_cipher_view(self, raw, ctx, key, false);
1657 }
1658 match try_parse_blob(self) {
1659 Some(sealed) => decrypt_blob_cipher(self, &sealed, ctx, key).map_err(CryptoError::from),
1660 None => lenient_decrypt_cipher_view(self, ctx, key),
1661 }
1662 }
1663}
1664
1665impl Decryptable<KeySlotIds, SymmetricKeySlotId, CipherListView> for Cipher {
1666 fn decrypt(
1667 &self,
1668 ctx: &mut KeyStoreContext<KeySlotIds>,
1669 key: SymmetricKeySlotId,
1670 ) -> Result<CipherListView, CryptoError> {
1671 if let Some(raw) = &self.partial_data {
1672 if self.organization_id.is_none() {
1676 return Err(CryptoError::RestrictedCipherRequiresOrganization);
1677 }
1678 return decrypt_restricted_cipher_list_view(self, raw, ctx, key, false);
1679 }
1680 match try_parse_blob(self) {
1681 Some(sealed) => decrypt_blob_cipher(self, &sealed, ctx, key)?.to_list_view(),
1682 None => lenient_decrypt_cipher_list_view(self, ctx, key),
1683 }
1684 }
1685}
1686
1687impl IdentifyKey<SymmetricKeySlotId> for CipherView {
1688 fn key_identifier(&self) -> SymmetricKeySlotId {
1689 match self.organization_id {
1690 Some(organization_id) => SymmetricKeySlotId::Organization(organization_id),
1691 None => SymmetricKeySlotId::User,
1692 }
1693 }
1694}
1695
1696impl IdentifyKey<SymmetricKeySlotId> for CipherListView {
1697 fn key_identifier(&self) -> SymmetricKeySlotId {
1698 match self.organization_id {
1699 Some(organization_id) => SymmetricKeySlotId::Organization(organization_id),
1700 None => SymmetricKeySlotId::User,
1701 }
1702 }
1703}
1704
1705pub(crate) struct StrictDecrypt<T>(pub(crate) T);
1714
1715impl IdentifyKey<SymmetricKeySlotId> for StrictDecrypt<Cipher> {
1716 fn key_identifier(&self) -> SymmetricKeySlotId {
1717 self.0.key_identifier()
1718 }
1719}
1720
1721impl Decryptable<KeySlotIds, SymmetricKeySlotId, CipherView> for StrictDecrypt<Cipher> {
1722 #[bitwarden_logging::instrument(err, fields(cipher_id = ?self.0.id, org_id = ?self.0.organization_id, kind = ?self.0.r#type))]
1723 fn decrypt(
1724 &self,
1725 ctx: &mut KeyStoreContext<KeySlotIds>,
1726 key: SymmetricKeySlotId,
1727 ) -> Result<CipherView, CryptoError> {
1728 if let Some(raw) = &self.0.partial_data {
1729 if self.0.organization_id.is_none() {
1731 return Err(CryptoError::RestrictedCipherRequiresOrganization);
1732 }
1733 return decrypt_restricted_cipher_view(&self.0, raw, ctx, key, true);
1734 }
1735 match try_parse_blob(&self.0) {
1736 Some(sealed) => {
1737 decrypt_blob_cipher(&self.0, &sealed, ctx, key).map_err(CryptoError::from)
1738 }
1739 None => strict_decrypt_cipher_view(&self.0, ctx, key),
1740 }
1741 }
1742}
1743
1744fn strict_decrypt_cipher_view(
1747 cipher: &Cipher,
1748 ctx: &mut KeyStoreContext<KeySlotIds>,
1749 key: SymmetricKeySlotId,
1750) -> Result<CipherView, CryptoError> {
1751 let ciphers_key = Cipher::decrypt_cipher_key(ctx, key, &cipher.key)?;
1752
1753 let (attachments, attachment_decryption_failures) =
1755 attachment::decrypt_attachments_with_failures(
1756 cipher.attachments.as_deref().unwrap_or_default(),
1757 ctx,
1758 ciphers_key,
1759 );
1760
1761 let mut view = CipherView {
1762 partial: false,
1763 id: cipher.id,
1764 organization_id: cipher.organization_id,
1765 folder_id: cipher.folder_id,
1766 collection_ids: cipher.collection_ids.clone(),
1767 key: if cipher.key.is_some() {
1768 #[allow(deprecated)]
1769 Some(ctx.dangerous_get_symmetric_key(ciphers_key)?.clone())
1770 } else {
1771 None
1772 },
1773 name: cipher
1774 .name
1775 .as_ref()
1776 .ok_or(CryptoError::MissingField("name"))?
1777 .decrypt(ctx, ciphers_key)?,
1778 notes: cipher.notes.decrypt(ctx, ciphers_key)?,
1779 r#type: cipher.r#type,
1780 login: cipher
1781 .login
1782 .as_ref()
1783 .map(|l| StrictDecrypt(l).decrypt(ctx, ciphers_key))
1784 .transpose()?,
1785 identity: cipher
1786 .identity
1787 .as_ref()
1788 .map(|i| StrictDecrypt(i).decrypt(ctx, ciphers_key))
1789 .transpose()?,
1790 card: cipher
1791 .card
1792 .as_ref()
1793 .map(|c| StrictDecrypt(c).decrypt(ctx, ciphers_key))
1794 .transpose()?,
1795 secure_note: cipher.secure_note.decrypt(ctx, ciphers_key)?,
1796 ssh_key: cipher.ssh_key.decrypt(ctx, ciphers_key)?,
1797 bank_account: cipher.bank_account.decrypt(ctx, ciphers_key)?,
1798 drivers_license: cipher.drivers_license.decrypt(ctx, ciphers_key)?,
1799 passport: cipher.passport.decrypt(ctx, ciphers_key)?,
1800 favorite: cipher.favorite,
1801 reprompt: cipher.reprompt,
1802 organization_use_totp: cipher.organization_use_totp,
1803 edit: cipher.edit,
1804 permissions: cipher.permissions,
1805 view_password: cipher.view_password,
1806 local_data: cipher.local_data.decrypt(ctx, ciphers_key)?,
1807 attachments: Some(attachments),
1808 attachment_decryption_failures: Some(attachment_decryption_failures),
1809 fields: cipher
1810 .fields
1811 .as_ref()
1812 .map(|fields| {
1813 fields
1814 .iter()
1815 .map(|f| StrictDecrypt(f).decrypt(ctx, ciphers_key))
1816 .collect::<Result<Vec<_>, _>>()
1817 })
1818 .transpose()?,
1819 password_history: cipher.password_history.decrypt(ctx, ciphers_key)?,
1820 creation_date: cipher.creation_date,
1821 deleted_date: cipher.deleted_date,
1822 revision_date: cipher.revision_date,
1823 archived_date: cipher.archived_date,
1824 };
1825
1826 if view.key.is_some()
1829 || ctx.get_security_state_version() >= MINIMUM_ENFORCE_ICON_URI_HASH_VERSION
1830 {
1831 view.remove_invalid_checksums();
1832 }
1833
1834 Ok(view)
1835}
1836
1837impl Decryptable<KeySlotIds, SymmetricKeySlotId, CipherListView> for StrictDecrypt<Cipher> {
1838 fn decrypt(
1839 &self,
1840 ctx: &mut KeyStoreContext<KeySlotIds>,
1841 key: SymmetricKeySlotId,
1842 ) -> Result<CipherListView, CryptoError> {
1843 if let Some(raw) = &self.0.partial_data {
1844 if self.0.organization_id.is_none() {
1846 return Err(CryptoError::RestrictedCipherRequiresOrganization);
1847 }
1848 return decrypt_restricted_cipher_list_view(&self.0, raw, ctx, key, true);
1849 }
1850 match try_parse_blob(&self.0) {
1851 Some(sealed) => decrypt_blob_cipher(&self.0, &sealed, ctx, key)?.to_list_view(),
1852 None => strict_decrypt_cipher_list_view(&self.0, ctx, key),
1853 }
1854 }
1855}
1856
1857fn strict_decrypt_cipher_list_view(
1860 cipher: &Cipher,
1861 ctx: &mut KeyStoreContext<KeySlotIds>,
1862 key: SymmetricKeySlotId,
1863) -> Result<CipherListView, CryptoError> {
1864 let ciphers_key = Cipher::decrypt_cipher_key(ctx, key, &cipher.key)?;
1865
1866 Ok(CipherListView {
1867 partial: false,
1868 id: cipher.id,
1869 organization_id: cipher.organization_id,
1870 folder_id: cipher.folder_id,
1871 collection_ids: cipher.collection_ids.clone(),
1872 name: cipher
1873 .name
1874 .as_ref()
1875 .ok_or(CryptoError::MissingField("name"))?
1876 .decrypt(ctx, ciphers_key)?,
1877 subtitle: cipher.decrypt_subtitle(ctx, ciphers_key)?,
1878 r#type: match cipher.r#type {
1879 CipherType::Login => {
1880 let login = cipher
1881 .login
1882 .as_ref()
1883 .ok_or(CryptoError::MissingField("login"))?;
1884 CipherListViewType::Login(StrictDecrypt(login).decrypt(ctx, ciphers_key)?)
1885 }
1886 CipherType::SecureNote => CipherListViewType::SecureNote,
1887 CipherType::Card => {
1888 let card = cipher
1889 .card
1890 .as_ref()
1891 .ok_or(CryptoError::MissingField("card"))?;
1892 CipherListViewType::Card(StrictDecrypt(card).decrypt(ctx, ciphers_key)?)
1893 }
1894 CipherType::Identity => CipherListViewType::Identity,
1895 CipherType::SshKey => CipherListViewType::SshKey,
1896 CipherType::BankAccount => {
1897 let bank_account = cipher
1898 .bank_account
1899 .as_ref()
1900 .ok_or(CryptoError::MissingField("bank_account"))?;
1901 CipherListViewType::BankAccount(
1902 StrictDecrypt(bank_account).decrypt(ctx, ciphers_key)?,
1903 )
1904 }
1905 CipherType::Passport => CipherListViewType::Passport,
1906 CipherType::DriversLicense => CipherListViewType::DriversLicense,
1907 },
1908 favorite: cipher.favorite,
1909 reprompt: cipher.reprompt,
1910 organization_use_totp: cipher.organization_use_totp,
1911 edit: cipher.edit,
1912 permissions: cipher.permissions,
1913 view_password: cipher.view_password,
1914 attachments: cipher
1915 .attachments
1916 .as_ref()
1917 .map(|a| a.len() as u32)
1918 .unwrap_or(0),
1919 has_old_attachments: cipher
1920 .attachments
1921 .as_ref()
1922 .map(|a| a.iter().any(|att| att.key.is_none()))
1923 .unwrap_or(false),
1924 creation_date: cipher.creation_date,
1925 deleted_date: cipher.deleted_date,
1926 revision_date: cipher.revision_date,
1927 copyable_fields: cipher.get_copyable_fields(),
1928 local_data: cipher.local_data.decrypt(ctx, ciphers_key)?,
1929 archived_date: cipher.archived_date,
1930 #[cfg(feature = "wasm")]
1931 notes: cipher.notes.decrypt(ctx, ciphers_key)?,
1932 #[cfg(feature = "wasm")]
1933 fields: cipher
1934 .fields
1935 .as_ref()
1936 .map(|fields| {
1937 fields
1938 .iter()
1939 .map(|f| {
1940 StrictDecrypt(f)
1941 .decrypt(ctx, ciphers_key)
1942 .map(field::FieldListView::from)
1943 })
1944 .collect::<Result<Vec<_>, _>>()
1945 })
1946 .transpose()?,
1947 #[cfg(feature = "wasm")]
1948 attachment_names: cipher
1949 .attachments
1950 .as_ref()
1951 .map(|attachments| {
1952 attachments
1953 .iter()
1954 .map(|a| a.file_name.decrypt(ctx, ciphers_key))
1955 .collect::<Result<Vec<_>, _>>()
1956 })
1957 .transpose()?
1958 .map(|names| names.into_iter().flatten().collect()),
1959 })
1960}
1961
1962pub enum EncryptMode<T> {
1967 Blob(T),
1969 Legacy(T),
1971}
1972
1973impl<T> EncryptMode<T> {
1974 pub(crate) fn inner(&self) -> &T {
1975 match self {
1976 Self::Blob(t) | Self::Legacy(t) => t,
1977 }
1978 }
1979}
1980
1981impl<T> IdentifyKey<SymmetricKeySlotId> for EncryptMode<T>
1982where
1983 T: IdentifyKey<SymmetricKeySlotId>,
1984{
1985 fn key_identifier(&self) -> SymmetricKeySlotId {
1986 self.inner().key_identifier()
1987 }
1988}
1989
1990impl CompositeEncryptable<KeySlotIds, SymmetricKeySlotId, Cipher> for EncryptMode<CipherView> {
1991 fn encrypt_composite(
1992 &self,
1993 ctx: &mut KeyStoreContext<KeySlotIds>,
1994 key: SymmetricKeySlotId,
1995 ) -> Result<Cipher, CryptoError> {
1996 match self {
1997 Self::Blob(view) => {
2001 let mut owned = view.clone();
2002 encrypt_blob_cipher_with_wrapping_key(&mut owned, ctx, key)
2003 .map_err(CryptoError::from)
2004 }
2005 Self::Legacy(view) => {
2006 let mut owned = view.clone();
2007 owned.encrypt_legacy_field_encryption(ctx, key)
2008 }
2009 }
2010 }
2011}
2012
2013impl TryFrom<CipherDetailsResponseModel> for Cipher {
2014 type Error = VaultParseError;
2015
2016 fn try_from(cipher: CipherDetailsResponseModel) -> Result<Self, Self::Error> {
2017 Ok(Self {
2018 partial_data: cipher.partial_data,
2019 id: cipher.id.map(CipherId::new),
2020 organization_id: cipher.organization_id.map(OrganizationId::new),
2021 folder_id: cipher.folder_id.map(FolderId::new),
2022 collection_ids: cipher
2023 .collection_ids
2024 .unwrap_or_default()
2025 .into_iter()
2026 .map(CollectionId::new)
2027 .collect(),
2028 name: EncString::try_from_optional(cipher.name)?,
2029 notes: EncString::try_from_optional(cipher.notes)?,
2030 r#type: require!(cipher.r#type).try_into()?,
2031 login: cipher.login.map(|l| (*l).try_into()).transpose()?,
2032 identity: cipher.identity.map(|i| (*i).try_into()).transpose()?,
2033 card: cipher.card.map(|c| (*c).try_into()).transpose()?,
2034 secure_note: cipher.secure_note.map(|s| (*s).try_into()).transpose()?,
2035 ssh_key: cipher.ssh_key.map(|s| (*s).try_into()).transpose()?,
2036 bank_account: cipher.bank_account.map(|b| (*b).try_into()).transpose()?,
2037 drivers_license: cipher
2038 .drivers_license
2039 .map(|d| (*d).try_into())
2040 .transpose()?,
2041 passport: cipher.passport.map(|p| (*p).try_into()).transpose()?,
2042 favorite: cipher.favorite.unwrap_or(false),
2043 reprompt: cipher
2044 .reprompt
2045 .map(|r| r.try_into())
2046 .transpose()?
2047 .unwrap_or(CipherRepromptType::None),
2048 organization_use_totp: cipher.organization_use_totp.unwrap_or(true),
2049 edit: cipher.edit.unwrap_or(true),
2050 permissions: cipher.permissions.map(|p| (*p).try_into()).transpose()?,
2051 view_password: cipher.view_password.unwrap_or(true),
2052 local_data: None, attachments: cipher
2054 .attachments
2055 .map(|a| a.into_iter().map(|a| a.try_into()).collect())
2056 .transpose()?,
2057 fields: cipher
2058 .fields
2059 .map(|f| f.into_iter().map(|f| f.try_into()).collect())
2060 .transpose()?,
2061 password_history: cipher
2062 .password_history
2063 .map(|p| p.into_iter().map(|p| p.try_into()).collect())
2064 .transpose()?,
2065 creation_date: require!(cipher.creation_date).parse()?,
2066 deleted_date: cipher.deleted_date.map(|d| d.parse()).transpose()?,
2067 revision_date: require!(cipher.revision_date).parse()?,
2068 key: EncString::try_from_optional(cipher.key)?,
2069 archived_date: cipher.archived_date.map(|d| d.parse()).transpose()?,
2070 data: cipher.data,
2071 })
2072 }
2073}
2074
2075impl PartialCipher for CipherDetailsResponseModel {
2076 fn merge_with_cipher(self, cipher: Option<Cipher>) -> Result<Cipher, VaultParseError> {
2077 Ok(Cipher {
2078 local_data: cipher.and_then(|c| c.local_data),
2079 ..self.try_into()?
2080 })
2081 }
2082}
2083
2084impl TryFrom<bitwarden_api_api::models::CipherType> for CipherType {
2085 type Error = MissingFieldError;
2086
2087 fn try_from(t: bitwarden_api_api::models::CipherType) -> Result<Self, Self::Error> {
2088 Ok(match t {
2089 bitwarden_api_api::models::CipherType::Login => CipherType::Login,
2090 bitwarden_api_api::models::CipherType::SecureNote => CipherType::SecureNote,
2091 bitwarden_api_api::models::CipherType::Card => CipherType::Card,
2092 bitwarden_api_api::models::CipherType::Identity => CipherType::Identity,
2093 bitwarden_api_api::models::CipherType::SSHKey => CipherType::SshKey,
2094 bitwarden_api_api::models::CipherType::BankAccount => CipherType::BankAccount,
2095 bitwarden_api_api::models::CipherType::Passport => CipherType::Passport,
2096 bitwarden_api_api::models::CipherType::DriversLicense => CipherType::DriversLicense,
2097 bitwarden_api_api::models::CipherType::__Unknown(_) => {
2098 return Err(MissingFieldError("type"));
2099 }
2100 })
2101 }
2102}
2103
2104impl TryFrom<bitwarden_api_api::models::CipherRepromptType> for CipherRepromptType {
2105 type Error = MissingFieldError;
2106
2107 fn try_from(t: bitwarden_api_api::models::CipherRepromptType) -> Result<Self, Self::Error> {
2108 Ok(match t {
2109 bitwarden_api_api::models::CipherRepromptType::None => CipherRepromptType::None,
2110 bitwarden_api_api::models::CipherRepromptType::Password => CipherRepromptType::Password,
2111 bitwarden_api_api::models::CipherRepromptType::__Unknown(_) => {
2112 return Err(MissingFieldError("reprompt"));
2113 }
2114 })
2115 }
2116}
2117
2118pub(crate) trait PartialCipher {
2122 fn merge_with_cipher(self, cipher: Option<Cipher>) -> Result<Cipher, VaultParseError>;
2123}
2124
2125impl From<CipherType> for bitwarden_api_api::models::CipherType {
2126 fn from(t: CipherType) -> Self {
2127 match t {
2128 CipherType::Login => bitwarden_api_api::models::CipherType::Login,
2129 CipherType::SecureNote => bitwarden_api_api::models::CipherType::SecureNote,
2130 CipherType::Card => bitwarden_api_api::models::CipherType::Card,
2131 CipherType::Identity => bitwarden_api_api::models::CipherType::Identity,
2132 CipherType::SshKey => bitwarden_api_api::models::CipherType::SSHKey,
2133 CipherType::BankAccount => bitwarden_api_api::models::CipherType::BankAccount,
2134 CipherType::Passport => bitwarden_api_api::models::CipherType::Passport,
2135 CipherType::DriversLicense => bitwarden_api_api::models::CipherType::DriversLicense,
2136 }
2137 }
2138}
2139
2140impl From<CipherRepromptType> for bitwarden_api_api::models::CipherRepromptType {
2141 fn from(t: CipherRepromptType) -> Self {
2142 match t {
2143 CipherRepromptType::None => bitwarden_api_api::models::CipherRepromptType::None,
2144 CipherRepromptType::Password => bitwarden_api_api::models::CipherRepromptType::Password,
2145 }
2146 }
2147}
2148
2149impl PartialCipher for CipherResponseModel {
2150 fn merge_with_cipher(self, cipher: Option<Cipher>) -> Result<Cipher, VaultParseError> {
2151 Ok(Cipher {
2152 partial_data: self.partial_data,
2153 collection_ids: cipher
2154 .as_ref()
2155 .map(|c| c.collection_ids.clone())
2156 .unwrap_or_default(),
2157 local_data: cipher.and_then(|c| c.local_data),
2158 id: self.id.map(CipherId::new),
2159 organization_id: self.organization_id.map(OrganizationId::new),
2160 folder_id: self.folder_id.map(FolderId::new),
2161 name: self.name.map(|n| n.parse()).transpose()?,
2162 notes: EncString::try_from_optional(self.notes)?,
2163 r#type: require!(self.r#type).try_into()?,
2164 login: self.login.map(|l| (*l).try_into()).transpose()?,
2165 identity: self.identity.map(|i| (*i).try_into()).transpose()?,
2166 card: self.card.map(|c| (*c).try_into()).transpose()?,
2167 secure_note: self.secure_note.map(|s| (*s).try_into()).transpose()?,
2168 ssh_key: self.ssh_key.map(|s| (*s).try_into()).transpose()?,
2169 bank_account: self.bank_account.map(|b| (*b).try_into()).transpose()?,
2170 drivers_license: self.drivers_license.map(|d| (*d).try_into()).transpose()?,
2171 passport: self.passport.map(|p| (*p).try_into()).transpose()?,
2172 favorite: self.favorite.unwrap_or(false),
2173 reprompt: self
2174 .reprompt
2175 .map(|r| r.try_into())
2176 .transpose()?
2177 .unwrap_or(CipherRepromptType::None),
2178 organization_use_totp: self.organization_use_totp.unwrap_or(false),
2179 edit: self.edit.unwrap_or(false),
2180 permissions: self.permissions.map(|p| (*p).try_into()).transpose()?,
2181 view_password: self.view_password.unwrap_or(true),
2182 attachments: self
2183 .attachments
2184 .map(|a| a.into_iter().map(|a| a.try_into()).collect())
2185 .transpose()?,
2186 fields: self
2187 .fields
2188 .map(|f| f.into_iter().map(|f| f.try_into()).collect())
2189 .transpose()?,
2190 password_history: self
2191 .password_history
2192 .map(|p| p.into_iter().map(|p| p.try_into()).collect())
2193 .transpose()?,
2194 creation_date: require!(self.creation_date).parse()?,
2195 deleted_date: self.deleted_date.map(|d| d.parse()).transpose()?,
2196 revision_date: require!(self.revision_date).parse()?,
2197 key: EncString::try_from_optional(self.key)?,
2198 archived_date: self.archived_date.map(|d| d.parse()).transpose()?,
2199 data: self.data,
2200 })
2201 }
2202}
2203
2204impl TryFrom<CipherResponseModel> for Cipher {
2206 type Error = VaultParseError;
2207
2208 fn try_from(cipher: CipherResponseModel) -> Result<Self, Self::Error> {
2209 cipher.merge_with_cipher(None)
2210 }
2211}
2212
2213impl TryFrom<CipherMiniResponseModel> for Cipher {
2214 type Error = VaultParseError;
2215
2216 fn try_from(cipher: CipherMiniResponseModel) -> Result<Self, Self::Error> {
2217 cipher.merge_with_cipher(None)
2218 }
2219}
2220
2221impl PartialCipher for CipherMiniResponseModel {
2222 fn merge_with_cipher(self, cipher: Option<Cipher>) -> Result<Cipher, VaultParseError> {
2223 let cipher = cipher.as_ref();
2224 Ok(Cipher {
2225 partial_data: self.partial_data,
2226 id: self.id.map(CipherId::new),
2227 organization_id: self.organization_id.map(OrganizationId::new),
2228 key: EncString::try_from_optional(self.key)?,
2229 name: EncString::try_from_optional(self.name)?,
2230 notes: EncString::try_from_optional(self.notes)?,
2231 r#type: require!(self.r#type).try_into()?,
2232 login: self.login.map(|l| (*l).try_into()).transpose()?,
2233 identity: self.identity.map(|i| (*i).try_into()).transpose()?,
2234 card: self.card.map(|c| (*c).try_into()).transpose()?,
2235 secure_note: self.secure_note.map(|s| (*s).try_into()).transpose()?,
2236 ssh_key: self.ssh_key.map(|s| (*s).try_into()).transpose()?,
2237 bank_account: self.bank_account.map(|b| (*b).try_into()).transpose()?,
2238 drivers_license: self.drivers_license.map(|d| (*d).try_into()).transpose()?,
2239 passport: self.passport.map(|p| (*p).try_into()).transpose()?,
2240 reprompt: self
2241 .reprompt
2242 .map(|r| r.try_into())
2243 .transpose()?
2244 .unwrap_or(CipherRepromptType::None),
2245 organization_use_totp: self.organization_use_totp.unwrap_or(true),
2246 attachments: self
2247 .attachments
2248 .map(|a| a.into_iter().map(|a| a.try_into()).collect())
2249 .transpose()?,
2250 fields: self
2251 .fields
2252 .map(|f| f.into_iter().map(|f| f.try_into()).collect())
2253 .transpose()?,
2254 password_history: self
2255 .password_history
2256 .map(|p| p.into_iter().map(|p| p.try_into()).collect())
2257 .transpose()?,
2258 creation_date: require!(self.creation_date)
2259 .parse()
2260 .map_err(Into::<VaultParseError>::into)?,
2261 deleted_date: self
2262 .deleted_date
2263 .map(|d| d.parse())
2264 .transpose()
2265 .map_err(Into::<VaultParseError>::into)?,
2266 revision_date: require!(self.revision_date)
2267 .parse()
2268 .map_err(Into::<VaultParseError>::into)?,
2269 archived_date: cipher.map_or(Default::default(), |c| c.archived_date),
2270 folder_id: cipher.map_or(Default::default(), |c| c.folder_id),
2271 favorite: cipher.map_or(Default::default(), |c| c.favorite),
2272 edit: cipher.map_or(Default::default(), |c| c.edit),
2273 permissions: cipher.map_or(Default::default(), |c| c.permissions),
2274 view_password: cipher.is_none_or(|c| c.view_password),
2275 local_data: cipher.map_or(Default::default(), |c| c.local_data.clone()),
2276 data: self.data,
2277 collection_ids: cipher.map_or(Default::default(), |c| c.collection_ids.clone()),
2278 })
2279 }
2280}
2281
2282impl PartialCipher for CipherMiniDetailsResponseModel {
2283 fn merge_with_cipher(self, cipher: Option<Cipher>) -> Result<Cipher, VaultParseError> {
2284 let cipher = cipher.as_ref();
2285 Ok(Cipher {
2286 partial_data: self.partial_data,
2287 id: self.id.map(CipherId::new),
2288 organization_id: self.organization_id.map(OrganizationId::new),
2289 key: EncString::try_from_optional(self.key)?,
2290 name: EncString::try_from_optional(self.name)?,
2291 notes: EncString::try_from_optional(self.notes)?,
2292 r#type: require!(self.r#type).try_into()?,
2293 login: self.login.map(|l| (*l).try_into()).transpose()?,
2294 identity: self.identity.map(|i| (*i).try_into()).transpose()?,
2295 card: self.card.map(|c| (*c).try_into()).transpose()?,
2296 secure_note: self.secure_note.map(|s| (*s).try_into()).transpose()?,
2297 ssh_key: self.ssh_key.map(|s| (*s).try_into()).transpose()?,
2298 bank_account: self.bank_account.map(|b| (*b).try_into()).transpose()?,
2299 drivers_license: self.drivers_license.map(|d| (*d).try_into()).transpose()?,
2300 passport: self.passport.map(|p| (*p).try_into()).transpose()?,
2301 reprompt: self
2302 .reprompt
2303 .map(|r| r.try_into())
2304 .transpose()?
2305 .unwrap_or(CipherRepromptType::None),
2306 organization_use_totp: self.organization_use_totp.unwrap_or(true),
2307 attachments: self
2308 .attachments
2309 .map(|a| a.into_iter().map(|a| a.try_into()).collect())
2310 .transpose()?,
2311 fields: self
2312 .fields
2313 .map(|f| f.into_iter().map(|f| f.try_into()).collect())
2314 .transpose()?,
2315 password_history: self
2316 .password_history
2317 .map(|p| p.into_iter().map(|p| p.try_into()).collect())
2318 .transpose()?,
2319 creation_date: require!(self.creation_date)
2320 .parse()
2321 .map_err(Into::<VaultParseError>::into)?,
2322 deleted_date: self
2323 .deleted_date
2324 .map(|d| d.parse())
2325 .transpose()
2326 .map_err(Into::<VaultParseError>::into)?,
2327 revision_date: require!(self.revision_date)
2328 .parse()
2329 .map_err(Into::<VaultParseError>::into)?,
2330 collection_ids: self
2331 .collection_ids
2332 .into_iter()
2333 .flatten()
2334 .map(CollectionId::new)
2335 .collect(),
2336 archived_date: cipher.map_or(Default::default(), |c| c.archived_date),
2337 folder_id: cipher.map_or(Default::default(), |c| c.folder_id),
2338 favorite: cipher.map_or(Default::default(), |c| c.favorite),
2339 edit: cipher.map_or(Default::default(), |c| c.edit),
2340 permissions: cipher.map_or(Default::default(), |c| c.permissions),
2341 view_password: cipher.is_none_or(|c: &Cipher| c.view_password),
2342 data: cipher.map_or(Default::default(), |c| c.data.clone()),
2343 local_data: cipher.map_or(Default::default(), |c| c.local_data.clone()),
2344 })
2345 }
2346}
2347
2348#[cfg(test)]
2349mod tests {
2350
2351 use attachment::AttachmentView;
2352 use bitwarden_core::key_management::{
2353 create_test_crypto_with_user_and_org_key, create_test_crypto_with_user_key,
2354 };
2355 use bitwarden_crypto::{KeyStore, SymmetricCryptoKey, SymmetricKeyAlgorithm};
2356
2357 use super::*;
2358 use crate::{Fido2Credential, PasswordHistoryView, login::Fido2CredentialListView};
2359
2360 const TEST_ENC_STRING_1: &str = "2.xzDCDWqRBpHm42EilUvyVw==|nIrWV3l/EeTbWTnAznrK0Q==|sUj8ol2OTgvvTvD86a9i9XUP58hmtCEBqhck7xT5YNk=";
2362 const TEST_ENC_STRING_2: &str = "2.M7ZJ7EuFDXCq66gDTIyRIg==|B1V+jroo6+m/dpHx6g8DxA==|PIXPBCwyJ1ady36a7jbcLg346pm/7N/06W4UZxc1TUo=";
2363 const TEST_ENC_STRING_3: &str = "2.d3rzo0P8rxV9Hs1m1BmAjw==|JOwna6i0zs+K7ZghwrZRuw==|SJqKreLag1ID+g6H1OdmQr0T5zTrVWKzD6hGy3fDqB0=";
2364 const TEST_ENC_STRING_4: &str = "2.EBNGgnaMHeO/kYnI3A0jiA==|9YXlrgABP71ebZ5umurCJQ==|GDk5jxiqTYaU7e2AStCFGX+a1kgCIk8j0NEli7Jn0L4=";
2365 const TEST_ENC_STRING_5: &str = "2.hqdioUAc81FsKQmO1XuLQg==|oDRdsJrQjoFu9NrFVy8tcJBAFKBx95gHaXZnWdXbKpsxWnOr2sKipIG43pKKUFuq|3gKZMiboceIB5SLVOULKg2iuyu6xzos22dfJbvx0EHk=";
2366 const TEST_CIPHER_NAME: &str = "2.d3rzo0P8rxV9Hs1m1BmAjw==|JOwna6i0zs+K7ZghwrZRuw==|SJqKreLag1ID+g6H1OdmQr0T5zTrVWKzD6hGy3fDqB0=";
2367 const TEST_UUID: &str = "fd411a1a-fec8-4070-985d-0e6560860e69";
2368
2369 const RESTRICTED_ORG_UUID: &str = "3cf0d3ba-3ded-4bf3-a51c-b03fd9ac6e07";
2371 const RESTRICTED_ORG_KEY_B64: &str =
2372 "w2LO+nwV4oxwswVYCxlOfRUseXfvU03VzvKQHrqeklPgiMZrspUe6sOBToCnDn9Ay0tuCBn8ykVVRb7PWhub2Q==";
2373
2374 const RESTRICTED_LOGIN_ENVELOPE: &str = r#"{"name":"2.qip4DSwdOzU2KwY3jgDjUg==|CsGRQgTwAzmszz+dkk5xIg==|rmW/mlnHq2MulR9uNKclD+1UBFLfOimedkq5tPRSLOc=","uris":[{"uri":"2.2na8mpfA1B1OBTUHkDz+fw==|yTWB1nEf3EHIZgsDINM8JnTYyxf7KVZvXraIGAVOiEg=|i2swsODSjEMRaYNnBHAigdphZBBUg2lkPNo763fX12w=","uriChecksum":null,"match":null}]}"#;
2377 const RESTRICTED_LOGIN_ENVELOPE_WITH_PASSWORD: &str = r#"{"name":"2.qip4DSwdOzU2KwY3jgDjUg==|CsGRQgTwAzmszz+dkk5xIg==|rmW/mlnHq2MulR9uNKclD+1UBFLfOimedkq5tPRSLOc=","uris":[{"uri":"2.2na8mpfA1B1OBTUHkDz+fw==|yTWB1nEf3EHIZgsDINM8JnTYyxf7KVZvXraIGAVOiEg=|i2swsODSjEMRaYNnBHAigdphZBBUg2lkPNo763fX12w=","uriChecksum":null,"match":null}],"password":"2.cKf+VYTb7KF2ITGLDmGzig==|zC66OfcYpUB8V6jLB6GQvQ==|hnDFyYCAf6RPD4lPmXZCzEWzXwniRyFnCVrO0KZMPlc="}"#;
2379 const RESTRICTED_SECURE_NOTE_ENVELOPE: &str = r#"{"name":"2.EwVjyRAgPmUvRpyT68lbjQ==|73O9id1+DZevAB3K+2fXnA==|OoJhN3p9UgjQ4yk55OUBZ4nYQMlFcf9wTHPxrOPhQVI="}"#;
2380 const RESTRICTED_CARD_ENVELOPE: &str = r#"{"name":"2.HF21EOZVqF3eyeZtEgxaCg==|zuChVgXPqxipFE6zOBUBXQ==|gxyvw0+gMf5Grxk8EAhpLCBeXdA0kvea2maJmpLIUIw="}"#;
2381
2382 fn restricted_test_key_store() -> (OrganizationId, KeyStore<KeySlotIds>) {
2385 let org: OrganizationId = RESTRICTED_ORG_UUID.parse().unwrap();
2386 let org_key: SymmetricCryptoKey = RESTRICTED_ORG_KEY_B64.to_string().try_into().unwrap();
2387 let key_store = create_test_crypto_with_user_and_org_key(
2388 SymmetricCryptoKey::make(SymmetricKeyAlgorithm::Aes256CbcHmac),
2389 org,
2390 org_key,
2391 );
2392 (org, key_store)
2393 }
2394
2395 fn generate_cipher() -> CipherView {
2396 let test_id = "fd411a1a-fec8-4070-985d-0e6560860e69".parse().unwrap();
2397 CipherView {
2398 partial: false,
2399 r#type: CipherType::Login,
2400 login: Some(LoginView {
2401 username: Some("test_username".to_string()),
2402 password: Some("test_password".to_string()),
2403 password_revision_date: None,
2404 uris: None,
2405 totp: None,
2406 autofill_on_page_load: None,
2407 http_authentication_enabled: None,
2408 fido2_credentials: None,
2409 }),
2410 id: Some(test_id),
2411 organization_id: None,
2412 folder_id: None,
2413 collection_ids: vec![],
2414 key: None,
2415 name: "My test login".to_string(),
2416 notes: None,
2417 identity: None,
2418 card: None,
2419 secure_note: None,
2420 ssh_key: None,
2421 bank_account: None,
2422 drivers_license: None,
2423 passport: None,
2424 favorite: false,
2425 reprompt: CipherRepromptType::None,
2426 organization_use_totp: true,
2427 edit: true,
2428 permissions: None,
2429 view_password: true,
2430 local_data: None,
2431 attachments: None,
2432 attachment_decryption_failures: None,
2433 fields: None,
2434 password_history: None,
2435 creation_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
2436 deleted_date: None,
2437 revision_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
2438 archived_date: None,
2439 }
2440 }
2441
2442 fn generate_fido2(
2443 ctx: &mut KeyStoreContext<KeySlotIds>,
2444 key: SymmetricKeySlotId,
2445 ) -> Fido2Credential {
2446 Fido2Credential {
2447 credential_id: "123".to_string().encrypt(ctx, key).unwrap(),
2448 key_type: "public-key".to_string().encrypt(ctx, key).unwrap(),
2449 key_algorithm: "ECDSA".to_string().encrypt(ctx, key).unwrap(),
2450 key_curve: "P-256".to_string().encrypt(ctx, key).unwrap(),
2451 key_value: "123".to_string().encrypt(ctx, key).unwrap(),
2452 rp_id: "123".to_string().encrypt(ctx, key).unwrap(),
2453 user_handle: None,
2454 user_name: None,
2455 counter: "123".to_string().encrypt(ctx, key).unwrap(),
2456 rp_name: None,
2457 user_display_name: None,
2458 discoverable: "true".to_string().encrypt(ctx, key).unwrap(),
2459 creation_date: "2024-06-07T14:12:36.150Z".parse().unwrap(),
2460 }
2461 }
2462
2463 fn generate_fido2_view() -> Fido2CredentialView {
2464 Fido2CredentialView {
2465 credential_id: "123".to_string(),
2466 key_type: "public-key".to_string(),
2467 key_algorithm: "ECDSA".to_string(),
2468 key_curve: "P-256".to_string(),
2469 key_value: "123".to_string(),
2470 rp_id: "123".to_string(),
2471 user_handle: None,
2472 user_name: None,
2473 counter: "123".to_string(),
2474 rp_name: None,
2475 user_display_name: None,
2476 discoverable: "true".to_string(),
2477 creation_date: "2024-06-07T14:12:36.150Z".parse().unwrap(),
2478 }
2479 }
2480
2481 fn restricted_cipher(
2484 organization_id: OrganizationId,
2485 r#type: CipherType,
2486 partial_data: String,
2487 ) -> Cipher {
2488 Cipher {
2489 partial_data: Some(partial_data),
2490 id: Some(TEST_UUID.parse().unwrap()),
2491 organization_id: Some(organization_id),
2492 folder_id: None,
2493 collection_ids: vec![],
2494 key: None,
2495 name: None,
2496 notes: None,
2497 r#type,
2498 login: None,
2499 identity: None,
2500 card: None,
2501 secure_note: None,
2502 ssh_key: None,
2503 bank_account: None,
2504 drivers_license: None,
2505 passport: None,
2506 favorite: false,
2507 reprompt: CipherRepromptType::None,
2508 organization_use_totp: false,
2509 edit: true,
2510 permissions: None,
2511 view_password: true,
2512 local_data: None,
2513 attachments: None,
2514 fields: None,
2515 password_history: None,
2516 creation_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
2517 deleted_date: None,
2518 revision_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
2519 archived_date: None,
2520 data: None,
2521 }
2522 }
2523
2524 #[test]
2525 fn test_decrypt_restricted_cipher_list_view_login() {
2526 let (org, key_store) = restricted_test_key_store();
2527 let cipher = restricted_cipher(
2528 org,
2529 CipherType::Login,
2530 RESTRICTED_LOGIN_ENVELOPE.to_string(),
2531 );
2532 let view: CipherListView = key_store.decrypt(&cipher).unwrap();
2533
2534 assert!(view.partial);
2535 assert_eq!(view.name, "Restricted Name".to_string());
2536 assert!(view.subtitle.is_empty());
2537 assert!(view.copyable_fields.is_empty());
2538 assert_eq!(view.attachments, 0);
2539 match view.r#type {
2540 CipherListViewType::Login(login) => {
2541 assert_eq!(
2542 login.uris.unwrap()[0].uri.as_deref(),
2543 Some("https://example.com")
2544 );
2545 assert_eq!(login.username, None);
2546 assert_eq!(login.totp, None);
2547 assert!(!login.has_fido2);
2548 }
2549 other => panic!("expected Login list view, got {other:?}"),
2550 }
2551 }
2552
2553 #[test]
2554 fn test_decrypt_restricted_cipher_view_login_omits_secrets() {
2555 let (org, key_store) = restricted_test_key_store();
2556 let cipher = restricted_cipher(
2559 org,
2560 CipherType::Login,
2561 RESTRICTED_LOGIN_ENVELOPE_WITH_PASSWORD.to_string(),
2562 );
2563 let view: CipherView = key_store.decrypt(&cipher).unwrap();
2564
2565 assert!(view.partial);
2566 assert_eq!(view.name, "Restricted Name".to_string());
2567 let login = view
2568 .login
2569 .expect("login populated so the view can render a domain");
2570 assert_eq!(
2571 login.uris.unwrap()[0].uri.as_deref(),
2572 Some("https://example.com")
2573 );
2574 assert_eq!(login.username, None);
2575 assert_eq!(login.password, None);
2576 assert_eq!(login.totp, None);
2577 assert_eq!(view.notes, None);
2578 assert!(view.card.is_none());
2579 }
2580
2581 #[test]
2582 fn test_decrypt_restricted_non_login_name_only() {
2583 let (org, key_store) = restricted_test_key_store();
2584 let cipher = restricted_cipher(
2585 org,
2586 CipherType::SecureNote,
2587 RESTRICTED_SECURE_NOTE_ENVELOPE.to_string(),
2588 );
2589
2590 let list: CipherListView = key_store.decrypt(&cipher).unwrap();
2591 assert!(list.partial);
2592 assert_eq!(list.name, "Gated Note".to_string());
2593 assert_eq!(list.r#type, CipherListViewType::SecureNote);
2594
2595 let view: CipherView = key_store.decrypt(&cipher).unwrap();
2596 assert!(view.partial);
2597 assert_eq!(view.name, "Gated Note".to_string());
2598 assert!(view.login.is_none());
2599 assert!(view.secure_note.is_none());
2600 }
2601
2602 #[test]
2603 fn test_decrypt_restricted_malformed_envelope_fails_closed() {
2604 let (org, key_store) = restricted_test_key_store();
2605 let cipher = restricted_cipher(org, CipherType::Login, "not valid json".to_string());
2607
2608 let list: CipherListView = key_store.decrypt(&cipher).unwrap();
2609 assert!(list.partial);
2610 assert!(list.name.is_empty());
2611
2612 let view: CipherView = key_store.decrypt(&cipher).unwrap();
2613 assert!(view.partial);
2614 assert!(view.name.is_empty());
2615
2616 let strict_view: CipherView = key_store.decrypt(&StrictDecrypt(cipher.clone())).unwrap();
2619 assert!(strict_view.partial);
2620 assert!(strict_view.name.is_empty());
2621 }
2622
2623 #[test]
2624 fn test_decrypt_restricted_works_in_strict_mode() {
2625 let (org, key_store) = restricted_test_key_store();
2626 let cipher = restricted_cipher(org, CipherType::Card, RESTRICTED_CARD_ENVELOPE.to_string());
2629
2630 let list: CipherListView = key_store.decrypt(&StrictDecrypt(cipher.clone())).unwrap();
2631 assert!(list.partial);
2632 assert_eq!(list.name, "Restricted Card".to_string());
2633 assert_eq!(
2634 list.r#type,
2635 CipherListViewType::Card(CardListView { brand: None })
2636 );
2637
2638 let view: CipherView = key_store.decrypt(&StrictDecrypt(cipher)).unwrap();
2639 assert!(view.partial);
2640 assert!(view.card.is_none());
2641 }
2642
2643 #[test]
2644 fn test_decrypt_restricted_strict_propagates_field_decrypt_error() {
2645 let (org, key_store) = restricted_test_key_store();
2646 let wrong_key_store = create_test_crypto_with_user_key(SymmetricCryptoKey::make(
2649 SymmetricKeyAlgorithm::Aes256CbcHmac,
2650 ));
2651 let bad_name = "boom"
2652 .to_string()
2653 .encrypt(&mut wrong_key_store.context(), SymmetricKeySlotId::User)
2654 .unwrap();
2655 let envelope = serde_json::json!({ "name": bad_name }).to_string();
2656 let cipher = restricted_cipher(org, CipherType::Login, envelope);
2657
2658 let view: CipherView = key_store.decrypt(&cipher).unwrap();
2660 assert!(view.partial);
2661 assert!(view.name.is_empty());
2662
2663 let view_result: Result<CipherView, CryptoError> =
2665 key_store.decrypt(&StrictDecrypt(cipher.clone()));
2666 assert!(view_result.is_err());
2667 let list_result: Result<CipherListView, CryptoError> =
2668 key_store.decrypt(&StrictDecrypt(cipher));
2669 assert!(list_result.is_err());
2670 }
2671
2672 #[test]
2673 fn test_decrypt_restricted_non_org_cipher_fails_closed() {
2674 let (org, key_store) = restricted_test_key_store();
2677 let cipher = Cipher {
2678 organization_id: None,
2679 ..restricted_cipher(
2680 org,
2681 CipherType::SecureNote,
2682 RESTRICTED_SECURE_NOTE_ENVELOPE.to_string(),
2683 )
2684 };
2685
2686 let view_result: Result<CipherView, CryptoError> = key_store.decrypt(&cipher);
2687 assert!(matches!(
2688 view_result.unwrap_err(),
2689 CryptoError::RestrictedCipherRequiresOrganization
2690 ));
2691
2692 let list_result: Result<CipherListView, CryptoError> = key_store.decrypt(&cipher);
2693 assert!(matches!(
2694 list_result.unwrap_err(),
2695 CryptoError::RestrictedCipherRequiresOrganization
2696 ));
2697 }
2698
2699 #[test]
2700 fn test_decrypt_cipher_list_view() {
2701 let key: SymmetricCryptoKey = "w2LO+nwV4oxwswVYCxlOfRUseXfvU03VzvKQHrqeklPgiMZrspUe6sOBToCnDn9Ay0tuCBn8ykVVRb7PWhub2Q==".to_string().try_into().unwrap();
2702 let key_store = create_test_crypto_with_user_key(key);
2703
2704 let cipher = Cipher {
2705 partial_data: None,
2706 id: Some("090c19ea-a61a-4df6-8963-262b97bc6266".parse().unwrap()),
2707 organization_id: None,
2708 folder_id: None,
2709 collection_ids: vec![],
2710 key: None,
2711 name: Some(TEST_CIPHER_NAME.parse().unwrap()),
2712 notes: None,
2713 r#type: CipherType::Login,
2714 login: Some(Login {
2715 username: Some("2.EBNGgnaMHeO/kYnI3A0jiA==|9YXlrgABP71ebZ5umurCJQ==|GDk5jxiqTYaU7e2AStCFGX+a1kgCIk8j0NEli7Jn0L4=".parse().unwrap()),
2716 password: Some("2.M7ZJ7EuFDXCq66gDTIyRIg==|B1V+jroo6+m/dpHx6g8DxA==|PIXPBCwyJ1ady36a7jbcLg346pm/7N/06W4UZxc1TUo=".parse().unwrap()),
2717 password_revision_date: None,
2718 uris: None,
2719 totp: Some("2.hqdioUAc81FsKQmO1XuLQg==|oDRdsJrQjoFu9NrFVy8tcJBAFKBx95gHaXZnWdXbKpsxWnOr2sKipIG43pKKUFuq|3gKZMiboceIB5SLVOULKg2iuyu6xzos22dfJbvx0EHk=".parse().unwrap()),
2720 autofill_on_page_load: None,
2721 http_authentication_enabled: None,
2722 fido2_credentials: Some(vec![generate_fido2(&mut key_store.context(), SymmetricKeySlotId::User)]),
2723 }),
2724 identity: None,
2725 card: None,
2726 secure_note: None,
2727 ssh_key: None,
2728 bank_account: None,
2729 drivers_license: None,
2730 passport: None,
2731 favorite: false,
2732 reprompt: CipherRepromptType::None,
2733 organization_use_totp: false,
2734 edit: true,
2735 permissions: Some(CipherPermissions {
2736 delete: false,
2737 restore: false
2738 }),
2739 view_password: true,
2740 local_data: None,
2741 attachments: None,
2742 fields: None,
2743 password_history: None,
2744 creation_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
2745 deleted_date: None,
2746 revision_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
2747 archived_date: None,
2748 data: None,
2749 };
2750
2751 let view: CipherListView = key_store.decrypt(&cipher).unwrap();
2752
2753 assert_eq!(
2754 view,
2755 CipherListView {
2756 partial: false,
2757 id: cipher.id,
2758 organization_id: cipher.organization_id,
2759 folder_id: cipher.folder_id,
2760 collection_ids: cipher.collection_ids,
2761 name: "My test login".to_string(),
2762 subtitle: "test_username".to_string(),
2763 r#type: CipherListViewType::Login(LoginListView {
2764 fido2_credentials: Some(vec![Fido2CredentialListView {
2765 credential_id: "123".to_string(),
2766 rp_id: "123".to_string(),
2767 user_handle: None,
2768 user_name: None,
2769 user_display_name: None,
2770 counter: "123".to_string(),
2771 }]),
2772 has_fido2: true,
2773 username: Some("test_username".to_string()),
2774 totp: cipher.login.as_ref().unwrap().totp.as_ref().map(|t| t
2775 .decrypt(&mut key_store.context(), SymmetricKeySlotId::User)
2776 .unwrap()),
2777 uris: None,
2778 }),
2779 favorite: cipher.favorite,
2780 reprompt: cipher.reprompt,
2781 organization_use_totp: cipher.organization_use_totp,
2782 edit: cipher.edit,
2783 permissions: cipher.permissions,
2784 view_password: cipher.view_password,
2785 attachments: 0,
2786 has_old_attachments: false,
2787 creation_date: cipher.creation_date,
2788 deleted_date: cipher.deleted_date,
2789 revision_date: cipher.revision_date,
2790 copyable_fields: vec![
2791 CopyableCipherFields::LoginUsername,
2792 CopyableCipherFields::LoginPassword,
2793 CopyableCipherFields::LoginTotp
2794 ],
2795 local_data: None,
2796 archived_date: cipher.archived_date,
2797 #[cfg(feature = "wasm")]
2798 notes: None,
2799 #[cfg(feature = "wasm")]
2800 fields: None,
2801 #[cfg(feature = "wasm")]
2802 attachment_names: None,
2803 }
2804 )
2805 }
2806
2807 fn blob_cipher() -> Cipher {
2808 let key_store = create_test_crypto_with_user_key(SymmetricCryptoKey::make(
2809 SymmetricKeyAlgorithm::Aes256CbcHmac,
2810 ));
2811 let cipher: Cipher = key_store
2812 .encrypt(EncryptMode::Blob(generate_cipher()))
2813 .unwrap();
2814 assert!(cipher.data.is_some(), "expected a blob-shaped cipher");
2815 cipher
2816 }
2817
2818 #[test]
2819 fn test_encryption_context_to_cipher_with_id_request_preserves_data() {
2820 let cipher = blob_cipher();
2821 let expected = cipher.data.clone();
2822
2823 let request: CipherWithIdRequestModel = EncryptionContext {
2824 encrypted_for: UserId::new(TEST_UUID.parse().unwrap()),
2825 encrypted_by_key_id: Some("0102030405060708090a0b0c0d0e0f10".to_string()),
2826 cipher,
2827 }
2828 .try_into()
2829 .unwrap();
2830
2831 assert_eq!(request.data, expected);
2832 assert_eq!(
2833 request.encrypted_by_key_id.as_deref(),
2834 Some("0102030405060708090a0b0c0d0e0f10")
2835 );
2836 }
2837
2838 #[test]
2839 fn test_encryption_context_to_cipher_request_preserves_data() {
2840 let cipher = blob_cipher();
2841 let expected = cipher.data.clone();
2842
2843 let request: CipherRequestModel = EncryptionContext {
2844 encrypted_for: UserId::new(TEST_UUID.parse().unwrap()),
2845 encrypted_by_key_id: Some("0102030405060708090a0b0c0d0e0f10".to_string()),
2846 cipher,
2847 }
2848 .into();
2849
2850 assert_eq!(request.data, expected);
2851 assert_eq!(
2852 request.encrypted_by_key_id.as_deref(),
2853 Some("0102030405060708090a0b0c0d0e0f10")
2854 );
2855 }
2856
2857 #[test]
2860 fn test_encrypted_by_key_id_uses_user_key_for_personal_cipher() {
2861 let user_key = SymmetricCryptoKey::make(SymmetricKeyAlgorithm::XChaCha20Poly1305);
2862 let expected = user_key.key_id().unwrap().to_string();
2863 let key_store = create_test_crypto_with_user_key(user_key);
2864
2865 let view = generate_cipher();
2866 assert_eq!(view.key_identifier(), SymmetricKeySlotId::User);
2867
2868 let actual = key_store
2869 .context()
2870 .get_symmetric_key_id(view.key_identifier())
2871 .map(|id| id.to_string());
2872
2873 assert_eq!(actual.as_deref(), Some(expected.as_str()));
2874 assert_eq!(expected.len(), 32);
2876 assert!(expected.chars().all(|c| c.is_ascii_hexdigit()));
2877 assert_eq!(expected, expected.to_lowercase());
2878 }
2879
2880 #[test]
2882 fn test_encrypted_by_key_id_uses_org_key_for_org_cipher() {
2883 let org = OrganizationId::new_v4();
2884 let user_key = SymmetricCryptoKey::make(SymmetricKeyAlgorithm::XChaCha20Poly1305);
2885 let org_key = SymmetricCryptoKey::make(SymmetricKeyAlgorithm::XChaCha20Poly1305);
2886 let user_key_id = user_key.key_id().unwrap().to_string();
2887 let org_key_id = org_key.key_id().unwrap().to_string();
2888 assert_ne!(user_key_id, org_key_id);
2889
2890 let key_store = create_test_crypto_with_user_and_org_key(user_key, org, org_key);
2891
2892 let mut view = generate_cipher();
2893 view.organization_id = Some(org);
2894 assert_eq!(view.key_identifier(), SymmetricKeySlotId::Organization(org));
2895
2896 let actual = key_store
2897 .context()
2898 .get_symmetric_key_id(view.key_identifier())
2899 .map(|id| id.to_string());
2900
2901 assert_eq!(actual.as_deref(), Some(org_key_id.as_str()));
2902 }
2903
2904 #[test]
2907 fn test_encrypted_by_key_id_ignores_cipher_key() {
2908 let user_key = SymmetricCryptoKey::make(SymmetricKeyAlgorithm::XChaCha20Poly1305);
2909 let expected = user_key.key_id().unwrap().to_string();
2910 let key_store = create_test_crypto_with_user_key(user_key);
2911
2912 let mut view = generate_cipher();
2913 let _ = view.load_cipher_key_slot(&mut key_store.context()).unwrap();
2914 assert!(view.key.is_some());
2915
2916 let actual = key_store
2917 .context()
2918 .get_symmetric_key_id(view.key_identifier())
2919 .map(|id| id.to_string());
2920
2921 assert_eq!(actual.as_deref(), Some(expected.as_str()));
2922 }
2923
2924 #[test]
2927 fn test_encrypted_by_key_id_uses_derived_id_for_legacy_user_key() {
2928 let user_key = SymmetricCryptoKey::make(SymmetricKeyAlgorithm::Aes256CbcHmac);
2929 let expected = user_key
2930 .key_id()
2931 .expect("an AES-CBC-HMAC key derives a key id")
2932 .to_string();
2933 let key_store = create_test_crypto_with_user_key(user_key);
2934
2935 let view = generate_cipher();
2936 let actual = key_store
2937 .context()
2938 .get_symmetric_key_id(view.key_identifier())
2939 .map(|id| id.to_string());
2940
2941 assert_eq!(actual.as_deref(), Some(expected.as_str()));
2942 }
2943
2944 #[test]
2945 fn test_decrypt_cipher_fails_with_invalid_name() {
2946 let key_store = create_test_crypto_with_user_key(SymmetricCryptoKey::make(
2947 SymmetricKeyAlgorithm::Aes256CbcHmac,
2948 ));
2949
2950 let cipher = key_store
2952 .encrypt(EncryptMode::Legacy(generate_cipher()))
2953 .unwrap();
2954 let cipher = Cipher {
2955 name: Some(TEST_CIPHER_NAME.parse().unwrap()), ..cipher
2957 };
2958
2959 let lenient_result: Result<CipherView, _> = key_store.decrypt(&cipher);
2961 assert!(
2962 lenient_result.is_ok(),
2963 "Lenient decryption should succeed even when name is encrypted with a different key"
2964 );
2965 assert_eq!(
2966 lenient_result.unwrap().name,
2967 String::new(),
2968 "Lenient decryption should yield an empty name on error"
2969 );
2970
2971 let strict_result: Result<CipherView, _> = key_store.decrypt(&StrictDecrypt(cipher));
2973 assert!(
2974 strict_result.is_err(),
2975 "Strict decryption should fail when name is encrypted with a different key"
2976 );
2977 }
2978
2979 #[test]
2980 fn test_decrypt_cipher_fails_with_invalid_login() {
2981 let key_store = create_test_crypto_with_user_key(SymmetricCryptoKey::make(
2982 SymmetricKeyAlgorithm::Aes256CbcHmac,
2983 ));
2984
2985 let cipher = key_store
2987 .encrypt(EncryptMode::Legacy(generate_cipher()))
2988 .unwrap();
2989 let cipher = Cipher {
2990 login: Some(Login {
2991 username: Some(TEST_CIPHER_NAME.parse().unwrap()), ..cipher.login.unwrap()
2993 }),
2994 ..cipher
2995 };
2996
2997 let lenient_result: Result<CipherView, _> = key_store.decrypt(&cipher);
2999 assert!(
3000 lenient_result.is_ok(),
3001 "Lenient decryption should succeed even when login username is encrypted with a different key"
3002 );
3003 let lenient_view = lenient_result.unwrap();
3004 assert!(
3005 lenient_view.login.is_some(),
3006 "Lenient decryption should still return the login object"
3007 );
3008 assert!(
3009 lenient_view.login.unwrap().username.is_none(),
3010 "Lenient decryption should null out the failing username field"
3011 );
3012
3013 let strict_result: Result<CipherView, _> = key_store.decrypt(&StrictDecrypt(cipher));
3015 assert!(
3016 strict_result.is_err(),
3017 "Strict decryption should fail when login username is encrypted with a different key"
3018 );
3019 }
3020
3021 #[test]
3022 fn test_encrypt_legacy_fails_closed_for_partial_view() {
3023 let key_store = create_test_crypto_with_user_key(SymmetricCryptoKey::make(
3024 SymmetricKeyAlgorithm::Aes256CbcHmac,
3025 ));
3026
3027 let mut view = generate_cipher();
3028 view.partial = true;
3029
3030 let result = key_store.encrypt(EncryptMode::Legacy(view));
3031 assert!(matches!(result, Err(CryptoError::EncryptRestrictedView)));
3032 }
3033
3034 #[test]
3035 fn test_encrypt_blob_fails_closed_for_partial_view() {
3036 let key_store = create_test_crypto_with_user_key(SymmetricCryptoKey::make(
3037 SymmetricKeyAlgorithm::Aes256CbcHmac,
3038 ));
3039
3040 let mut view = generate_cipher();
3041 view.partial = true;
3042
3043 let result = key_store.encrypt(EncryptMode::Blob(view));
3044 assert!(matches!(result, Err(CryptoError::EncryptRestrictedView)));
3045 }
3046
3047 #[test]
3048 fn test_encrypt_succeeds_for_non_partial_view() {
3049 let key_store = create_test_crypto_with_user_key(SymmetricCryptoKey::make(
3050 SymmetricKeyAlgorithm::Aes256CbcHmac,
3051 ));
3052
3053 let view = generate_cipher();
3057 assert!(!view.partial);
3058
3059 let result = key_store.encrypt(EncryptMode::Legacy(view));
3060 assert!(result.is_ok());
3061 }
3062
3063 #[test]
3064 fn test_load_cipher_key_slot_ignores_attachments_without_key() {
3065 let key = SymmetricCryptoKey::make(SymmetricKeyAlgorithm::Aes256CbcHmac);
3066 let key_store = create_test_crypto_with_user_key(key);
3067
3068 let mut cipher = generate_cipher();
3069 let attachment = AttachmentView {
3070 id: None,
3071 url: None,
3072 size: None,
3073 size_name: None,
3074 file_name: Some("Attachment test name".into()),
3075 key: None,
3076 };
3077 cipher.attachments = Some(vec![attachment]);
3078
3079 let _ = cipher
3080 .load_cipher_key_slot(&mut key_store.context())
3081 .unwrap();
3082 assert!(cipher.attachments.unwrap()[0].key.is_none());
3083 }
3084
3085 #[test]
3086 fn test_validate_attachment_keys_with_cipher_key() {
3087 let old_key = SymmetricCryptoKey::make(SymmetricKeyAlgorithm::Aes256CbcHmac);
3088 let key_store = create_test_crypto_with_user_key(old_key);
3089 let mut ctx = key_store.context_mut();
3090
3091 let mut cipher = generate_cipher();
3092 let _ = cipher.load_cipher_key_slot(&mut ctx).unwrap();
3093
3094 cipher.validate_attachment_keys().unwrap();
3095
3096 assert!(cipher.key.is_some());
3097 }
3098
3099 #[test]
3101 fn test_validate_attachment_keys_without_attachments() {
3102 let mut cipher = generate_cipher();
3103 assert!(cipher.key.is_none());
3104 assert!(cipher.attachments.is_none());
3105
3106 cipher.validate_attachment_keys().unwrap();
3107 }
3108
3109 #[test]
3110 fn test_move_user_cipher_to_org() {
3111 let org = OrganizationId::new_v4();
3112 let key = SymmetricCryptoKey::make(SymmetricKeyAlgorithm::Aes256CbcHmac);
3113 let org_key = SymmetricCryptoKey::make(SymmetricKeyAlgorithm::Aes256CbcHmac);
3114 let key_store = create_test_crypto_with_user_and_org_key(key, org, org_key);
3115
3116 let mut cipher = generate_cipher();
3118 let _ = cipher
3119 .load_cipher_key_slot(&mut key_store.context())
3120 .unwrap();
3121
3122 cipher.move_to_organization(org).unwrap();
3123 assert_eq!(cipher.organization_id, Some(org));
3124
3125 let cipher_enc = key_store.encrypt(EncryptMode::Legacy(cipher)).unwrap();
3127 let cipher_dec: CipherView = key_store.decrypt(&cipher_enc).unwrap();
3128
3129 assert_eq!(cipher_dec.name, "My test login");
3130 }
3131
3132 #[test]
3133 fn test_move_user_cipher_to_org_manually() {
3134 let org = OrganizationId::new_v4();
3135 let key = SymmetricCryptoKey::make(SymmetricKeyAlgorithm::Aes256CbcHmac);
3136 let org_key = SymmetricCryptoKey::make(SymmetricKeyAlgorithm::Aes256CbcHmac);
3137 let key_store = create_test_crypto_with_user_and_org_key(key, org, org_key);
3138
3139 let mut cipher = generate_cipher();
3141 let _ = cipher
3142 .load_cipher_key_slot(&mut key_store.context())
3143 .unwrap();
3144
3145 cipher.organization_id = Some(org);
3146
3147 let cipher_enc = key_store.encrypt(EncryptMode::Legacy(cipher)).unwrap();
3150 let cipher_dec: CipherView = key_store.decrypt(&cipher_enc).unwrap();
3151 assert_eq!(cipher_dec.name, "My test login");
3152 }
3153
3154 #[test]
3155 fn test_move_user_cipher_with_attachment_without_key_to_org() {
3156 let org = OrganizationId::new_v4();
3157 let key = SymmetricCryptoKey::make(SymmetricKeyAlgorithm::Aes256CbcHmac);
3158 let org_key = SymmetricCryptoKey::make(SymmetricKeyAlgorithm::Aes256CbcHmac);
3159 let _key_store = create_test_crypto_with_user_and_org_key(key, org, org_key);
3160
3161 let mut cipher = generate_cipher();
3162 let attachment = AttachmentView {
3163 id: None,
3164 url: None,
3165 size: None,
3166 size_name: None,
3167 file_name: Some("Attachment test name".into()),
3168 key: None,
3169 };
3170 cipher.attachments = Some(vec![attachment]);
3171
3172 assert!(cipher.move_to_organization(org).is_err());
3174 }
3175
3176 #[test]
3177 fn test_move_user_cipher_with_attachment_with_key_to_org() {
3178 let org = OrganizationId::new_v4();
3179 let key = SymmetricCryptoKey::make(SymmetricKeyAlgorithm::Aes256CbcHmac);
3180 let org_key = SymmetricCryptoKey::make(SymmetricKeyAlgorithm::Aes256CbcHmac);
3181 let key_store = create_test_crypto_with_user_and_org_key(key, org, org_key);
3182
3183 let attachment_key_val = {
3185 let mut ctx = key_store.context();
3186 let attachment_key = ctx.generate_symmetric_key();
3187 #[allow(deprecated)]
3188 ctx.dangerous_get_symmetric_key(attachment_key)
3189 .unwrap()
3190 .clone()
3191 };
3192
3193 let mut cipher = generate_cipher();
3194 let attachment = AttachmentView {
3195 id: None,
3196 url: None,
3197 size: None,
3198 size_name: None,
3199 file_name: Some("Attachment test name".into()),
3200 key: Some(attachment_key_val.clone()),
3201 };
3202 cipher.attachments = Some(vec![attachment]);
3203 let cred = generate_fido2_view();
3204 cipher.login.as_mut().unwrap().fido2_credentials = Some(vec![cred]);
3205
3206 cipher.move_to_organization(org).unwrap();
3207
3208 assert!(cipher.key.is_none());
3209
3210 assert_eq!(
3212 cipher.attachments.unwrap()[0].key.clone().unwrap(),
3213 attachment_key_val
3214 );
3215
3216 let cred2 = cipher
3217 .login
3218 .unwrap()
3219 .fido2_credentials
3220 .unwrap()
3221 .first()
3222 .unwrap()
3223 .clone();
3224
3225 assert_eq!(cred2.credential_id, "123");
3226 }
3227
3228 #[test]
3229 fn test_move_user_cipher_with_key_with_attachment_with_key_to_org() {
3230 let org = OrganizationId::new_v4();
3231 let key = SymmetricCryptoKey::make(SymmetricKeyAlgorithm::Aes256CbcHmac);
3232 let org_key = SymmetricCryptoKey::make(SymmetricKeyAlgorithm::Aes256CbcHmac);
3233 let key_store = create_test_crypto_with_user_and_org_key(key, org, org_key);
3234
3235 let mut ctx = key_store.context();
3236
3237 let cipher_key = ctx.generate_symmetric_key();
3238 #[allow(deprecated)]
3239 let cipher_key_raw = ctx.dangerous_get_symmetric_key(cipher_key).unwrap().clone();
3240
3241 let attachment_key = ctx.generate_symmetric_key();
3243 #[allow(deprecated)]
3244 let attachment_key_raw = ctx
3245 .dangerous_get_symmetric_key(attachment_key)
3246 .unwrap()
3247 .clone();
3248
3249 let mut cipher = generate_cipher();
3250 cipher.key = Some(cipher_key_raw.clone());
3251
3252 let attachment = AttachmentView {
3253 id: None,
3254 url: None,
3255 size: None,
3256 size_name: None,
3257 file_name: Some("Attachment test name".into()),
3258 key: Some(attachment_key_raw.clone()),
3259 };
3260 cipher.attachments = Some(vec![attachment]);
3261
3262 let cred = generate_fido2_view();
3263 cipher.login.as_mut().unwrap().fido2_credentials = Some(vec![cred.clone()]);
3264
3265 cipher.move_to_organization(org).unwrap();
3266
3267 assert_eq!(cipher.key.clone().unwrap(), cipher_key_raw);
3269
3270 assert_eq!(
3272 cipher.attachments.unwrap()[0].key.as_ref().unwrap(),
3273 &attachment_key_raw
3274 );
3275
3276 let cred2 = cipher
3277 .login
3278 .unwrap()
3279 .fido2_credentials
3280 .unwrap()
3281 .first()
3282 .unwrap()
3283 .clone();
3284
3285 assert_eq!(cred2.credential_id, cred.credential_id);
3286 }
3287
3288 #[test]
3289 fn test_password_history_on_password_change() {
3290 use chrono::Utc;
3291
3292 let original_cipher = generate_cipher();
3293 let mut new_cipher = generate_cipher();
3294
3295 if let Some(ref mut login) = new_cipher.login {
3297 login.password = Some("new_password123".to_string());
3298 }
3299
3300 let start = Utc::now();
3301 new_cipher.update_password_history(&original_cipher);
3302 let end = Utc::now();
3303
3304 assert!(new_cipher.password_history.is_some());
3305 let history = new_cipher.password_history.unwrap();
3306 assert_eq!(history.len(), 1);
3307 assert_eq!(history[0].password, "test_password");
3308 assert!(
3309 history[0].last_used_date >= start && history[0].last_used_date <= end,
3310 "last_used_date was not set properly"
3311 );
3312 }
3313
3314 #[test]
3315 fn test_password_history_on_unchanged_password() {
3316 let original_cipher = generate_cipher();
3317 let mut new_cipher = generate_cipher();
3318
3319 new_cipher.update_password_history(&original_cipher);
3320
3321 assert!(
3323 new_cipher.password_history.is_none()
3324 || new_cipher.password_history.as_ref().unwrap().is_empty()
3325 );
3326 }
3327
3328 #[test]
3329 fn test_password_history_is_preserved() {
3330 use chrono::TimeZone;
3331
3332 let mut original_cipher = generate_cipher();
3333 original_cipher.password_history = Some(
3334 (0..4)
3335 .map(|i| PasswordHistoryView {
3336 password: format!("old_password_{}", i),
3337 last_used_date: chrono::Utc
3338 .with_ymd_and_hms(2025, i + 1, i + 1, i, i, i)
3339 .unwrap(),
3340 })
3341 .collect(),
3342 );
3343
3344 let mut new_cipher = generate_cipher();
3345
3346 new_cipher.update_password_history(&original_cipher);
3347
3348 assert!(new_cipher.password_history.is_some());
3349 let history = new_cipher.password_history.unwrap();
3350 assert_eq!(history.len(), 4);
3351
3352 assert_eq!(history[0].password, "old_password_0");
3353 assert_eq!(
3354 history[0].last_used_date,
3355 chrono::Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap()
3356 );
3357 assert_eq!(history[1].password, "old_password_1");
3358 assert_eq!(
3359 history[1].last_used_date,
3360 chrono::Utc.with_ymd_and_hms(2025, 2, 2, 1, 1, 1).unwrap()
3361 );
3362 assert_eq!(history[2].password, "old_password_2");
3363 assert_eq!(
3364 history[2].last_used_date,
3365 chrono::Utc.with_ymd_and_hms(2025, 3, 3, 2, 2, 2).unwrap()
3366 );
3367 assert_eq!(history[3].password, "old_password_3");
3368 assert_eq!(
3369 history[3].last_used_date,
3370 chrono::Utc.with_ymd_and_hms(2025, 4, 4, 3, 3, 3).unwrap()
3371 );
3372 }
3373
3374 #[test]
3375 fn test_populate_cipher_types_login_with_valid_data() {
3376 let mut cipher = Cipher {
3377 partial_data: None,
3378 id: Some(TEST_UUID.parse().unwrap()),
3379 organization_id: None,
3380 folder_id: None,
3381 collection_ids: vec![],
3382 key: None,
3383 name: Some(TEST_CIPHER_NAME.parse().unwrap()),
3384 notes: None,
3385 r#type: CipherType::Login,
3386 login: None,
3387 identity: None,
3388 card: None,
3389 secure_note: None,
3390 ssh_key: None,
3391 bank_account: None,
3392 drivers_license: None,
3393 passport: None,
3394 favorite: false,
3395 reprompt: CipherRepromptType::None,
3396 organization_use_totp: false,
3397 edit: true,
3398 view_password: true,
3399 permissions: None,
3400 local_data: None,
3401 attachments: None,
3402 fields: None,
3403 password_history: None,
3404 creation_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
3405 deleted_date: None,
3406 revision_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
3407 archived_date: None,
3408 data: Some(format!(
3409 r#"{{"version": 2, "username": "{}", "password": "{}", "organizationUseTotp": true, "favorite": false, "deletedDate": null}}"#,
3410 TEST_ENC_STRING_1, TEST_ENC_STRING_2
3411 )),
3412 };
3413
3414 cipher
3415 .populate_cipher_types()
3416 .expect("populate_cipher_types failed");
3417
3418 assert!(cipher.login.is_some());
3419 let login = cipher.login.unwrap();
3420 assert_eq!(login.username.unwrap().to_string(), TEST_ENC_STRING_1);
3421 assert_eq!(login.password.unwrap().to_string(), TEST_ENC_STRING_2);
3422 }
3423
3424 #[test]
3425 fn test_populate_cipher_types_secure_note() {
3426 let mut cipher = Cipher {
3427 partial_data: None,
3428 id: Some(TEST_UUID.parse().unwrap()),
3429 organization_id: None,
3430 folder_id: None,
3431 collection_ids: vec![],
3432 key: None,
3433 name: Some(TEST_CIPHER_NAME.parse().unwrap()),
3434 notes: None,
3435 r#type: CipherType::SecureNote,
3436 login: None,
3437 identity: None,
3438 card: None,
3439 secure_note: None,
3440 ssh_key: None,
3441 bank_account: None,
3442 drivers_license: None,
3443 passport: None,
3444 favorite: false,
3445 reprompt: CipherRepromptType::None,
3446 organization_use_totp: false,
3447 edit: true,
3448 view_password: true,
3449 permissions: None,
3450 local_data: None,
3451 attachments: None,
3452 fields: None,
3453 password_history: None,
3454 creation_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
3455 deleted_date: None,
3456 revision_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
3457 archived_date: None,
3458 data: Some(r#"{"type": 0, "organizationUseTotp": false, "favorite": false, "deletedDate": null}"#.to_string()),
3459 };
3460
3461 cipher
3462 .populate_cipher_types()
3463 .expect("populate_cipher_types failed");
3464
3465 assert!(cipher.secure_note.is_some());
3466 }
3467
3468 #[test]
3469 fn test_populate_cipher_types_card() {
3470 let mut cipher = Cipher {
3471 partial_data: None,
3472 id: Some(TEST_UUID.parse().unwrap()),
3473 organization_id: None,
3474 folder_id: None,
3475 collection_ids: vec![],
3476 key: None,
3477 name: Some(TEST_CIPHER_NAME.parse().unwrap()),
3478 notes: None,
3479 r#type: CipherType::Card,
3480 login: None,
3481 identity: None,
3482 card: None,
3483 secure_note: None,
3484 ssh_key: None,
3485 bank_account: None,
3486 drivers_license: None,
3487 passport: None,
3488 favorite: false,
3489 reprompt: CipherRepromptType::None,
3490 organization_use_totp: false,
3491 edit: true,
3492 view_password: true,
3493 permissions: None,
3494 local_data: None,
3495 attachments: None,
3496 fields: None,
3497 password_history: None,
3498 creation_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
3499 deleted_date: None,
3500 revision_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
3501 archived_date: None,
3502 data: Some(format!(
3503 r#"{{"cardholderName": "{}", "number": "{}", "expMonth": "{}", "expYear": "{}", "code": "{}", "brand": "{}", "organizationUseTotp": true, "favorite": false, "deletedDate": null}}"#,
3504 TEST_ENC_STRING_1,
3505 TEST_ENC_STRING_2,
3506 TEST_ENC_STRING_3,
3507 TEST_ENC_STRING_4,
3508 TEST_ENC_STRING_5,
3509 TEST_ENC_STRING_1
3510 )),
3511 };
3512
3513 cipher
3514 .populate_cipher_types()
3515 .expect("populate_cipher_types failed");
3516
3517 assert!(cipher.card.is_some());
3518 let card = cipher.card.unwrap();
3519 assert_eq!(
3520 card.cardholder_name.as_ref().unwrap().to_string(),
3521 TEST_ENC_STRING_1
3522 );
3523 assert_eq!(card.number.as_ref().unwrap().to_string(), TEST_ENC_STRING_2);
3524 assert_eq!(
3525 card.exp_month.as_ref().unwrap().to_string(),
3526 TEST_ENC_STRING_3
3527 );
3528 assert_eq!(
3529 card.exp_year.as_ref().unwrap().to_string(),
3530 TEST_ENC_STRING_4
3531 );
3532 assert_eq!(card.code.as_ref().unwrap().to_string(), TEST_ENC_STRING_5);
3533 assert_eq!(card.brand.as_ref().unwrap().to_string(), TEST_ENC_STRING_1);
3534 }
3535
3536 #[test]
3537 fn test_populate_cipher_types_identity() {
3538 let mut cipher = Cipher {
3539 partial_data: None,
3540 id: Some(TEST_UUID.parse().unwrap()),
3541 organization_id: None,
3542 folder_id: None,
3543 collection_ids: vec![],
3544 key: None,
3545 name: Some(TEST_CIPHER_NAME.parse().unwrap()),
3546 notes: None,
3547 r#type: CipherType::Identity,
3548 login: None,
3549 identity: None,
3550 card: None,
3551 secure_note: None,
3552 ssh_key: None,
3553 bank_account: None,
3554 drivers_license: None,
3555 passport: None,
3556 favorite: false,
3557 reprompt: CipherRepromptType::None,
3558 organization_use_totp: false,
3559 edit: true,
3560 view_password: true,
3561 permissions: None,
3562 local_data: None,
3563 attachments: None,
3564 fields: None,
3565 password_history: None,
3566 creation_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
3567 deleted_date: None,
3568 revision_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
3569 archived_date: None,
3570 data: Some(format!(
3571 r#"{{"firstName": "{}", "lastName": "{}", "email": "{}", "phone": "{}", "company": "{}", "address1": "{}", "city": "{}", "state": "{}", "postalCode": "{}", "country": "{}", "organizationUseTotp": false, "favorite": true, "deletedDate": null}}"#,
3572 TEST_ENC_STRING_1,
3573 TEST_ENC_STRING_2,
3574 TEST_ENC_STRING_3,
3575 TEST_ENC_STRING_4,
3576 TEST_ENC_STRING_5,
3577 TEST_ENC_STRING_1,
3578 TEST_ENC_STRING_2,
3579 TEST_ENC_STRING_3,
3580 TEST_ENC_STRING_4,
3581 TEST_ENC_STRING_5
3582 )),
3583 };
3584
3585 cipher
3586 .populate_cipher_types()
3587 .expect("populate_cipher_types failed");
3588
3589 assert!(cipher.identity.is_some());
3590 let identity = cipher.identity.unwrap();
3591 assert_eq!(
3592 identity.first_name.as_ref().unwrap().to_string(),
3593 TEST_ENC_STRING_1
3594 );
3595 assert_eq!(
3596 identity.last_name.as_ref().unwrap().to_string(),
3597 TEST_ENC_STRING_2
3598 );
3599 assert_eq!(
3600 identity.email.as_ref().unwrap().to_string(),
3601 TEST_ENC_STRING_3
3602 );
3603 assert_eq!(
3604 identity.phone.as_ref().unwrap().to_string(),
3605 TEST_ENC_STRING_4
3606 );
3607 assert_eq!(
3608 identity.company.as_ref().unwrap().to_string(),
3609 TEST_ENC_STRING_5
3610 );
3611 assert_eq!(
3612 identity.address1.as_ref().unwrap().to_string(),
3613 TEST_ENC_STRING_1
3614 );
3615 assert_eq!(
3616 identity.city.as_ref().unwrap().to_string(),
3617 TEST_ENC_STRING_2
3618 );
3619 assert_eq!(
3620 identity.state.as_ref().unwrap().to_string(),
3621 TEST_ENC_STRING_3
3622 );
3623 assert_eq!(
3624 identity.postal_code.as_ref().unwrap().to_string(),
3625 TEST_ENC_STRING_4
3626 );
3627 assert_eq!(
3628 identity.country.as_ref().unwrap().to_string(),
3629 TEST_ENC_STRING_5
3630 );
3631 }
3632
3633 #[test]
3634
3635 fn test_password_history_with_hidden_fields() {
3636 let mut original_cipher = generate_cipher();
3637 original_cipher.fields = Some(vec![FieldView {
3638 name: Some("Secret Key".to_string()),
3639 value: Some("old_secret_value".to_string()),
3640 r#type: crate::FieldType::Hidden,
3641 linked_id: None,
3642 }]);
3643
3644 let mut new_cipher = generate_cipher();
3645 new_cipher.fields = Some(vec![FieldView {
3646 name: Some("Secret Key".to_string()),
3647 value: Some("new_secret_value".to_string()),
3648 r#type: crate::FieldType::Hidden,
3649 linked_id: None,
3650 }]);
3651
3652 new_cipher.update_password_history(&original_cipher);
3653
3654 assert!(new_cipher.password_history.is_some());
3655 let history = new_cipher.password_history.unwrap();
3656 assert_eq!(history.len(), 1);
3657 assert_eq!(history[0].password, "Secret Key: old_secret_value");
3658 }
3659
3660 #[test]
3661 fn test_password_history_length_limit() {
3662 use crate::password_history::MAX_PASSWORD_HISTORY_ENTRIES;
3663
3664 let mut original_cipher = generate_cipher();
3665 original_cipher.password_history = Some(
3666 (0..10)
3667 .map(|i| PasswordHistoryView {
3668 password: format!("old_password_{}", i),
3669 last_used_date: chrono::Utc::now(),
3670 })
3671 .collect(),
3672 );
3673
3674 let mut new_cipher = original_cipher.clone();
3675 if let Some(ref mut login) = new_cipher.login {
3677 login.password = Some("brand_new_password".to_string());
3678 }
3679
3680 new_cipher.update_password_history(&original_cipher);
3681
3682 assert!(new_cipher.password_history.is_some());
3683 let history = new_cipher.password_history.unwrap();
3684
3685 assert_eq!(history.len(), MAX_PASSWORD_HISTORY_ENTRIES);
3687
3688 assert_eq!(history[0].password, "test_password");
3690 assert_eq!(history[1].password, "old_password_0");
3692 assert_eq!(history[2].password, "old_password_1");
3693 assert_eq!(history[3].password, "old_password_2");
3694 assert_eq!(history[4].password, "old_password_3");
3695 }
3696
3697 #[test]
3698 fn test_populate_cipher_types_ssh_key() {
3699 let mut cipher = Cipher {
3700 partial_data: None,
3701 id: Some(TEST_UUID.parse().unwrap()),
3702 organization_id: None,
3703 folder_id: None,
3704 collection_ids: vec![],
3705 key: None,
3706 name: Some(TEST_CIPHER_NAME.parse().unwrap()),
3707 notes: None,
3708 r#type: CipherType::SshKey,
3709 login: None,
3710 identity: None,
3711 card: None,
3712 secure_note: None,
3713 ssh_key: None,
3714 bank_account: None,
3715 drivers_license: None,
3716 passport: None,
3717 favorite: false,
3718 reprompt: CipherRepromptType::None,
3719 organization_use_totp: false,
3720 edit: true,
3721 view_password: true,
3722 permissions: None,
3723 local_data: None,
3724 attachments: None,
3725 fields: None,
3726 password_history: None,
3727 creation_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
3728 deleted_date: None,
3729 revision_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
3730 archived_date: None,
3731 data: Some(format!(
3732 r#"{{"privateKey": "{}", "publicKey": "{}", "fingerprint": "{}", "organizationUseTotp": true, "favorite": false, "deletedDate": null}}"#,
3733 TEST_ENC_STRING_1, TEST_ENC_STRING_2, TEST_ENC_STRING_3
3734 )),
3735 };
3736
3737 cipher
3738 .populate_cipher_types()
3739 .expect("populate_cipher_types failed");
3740
3741 assert!(cipher.ssh_key.is_some());
3742 let ssh_key = cipher.ssh_key.unwrap();
3743 assert_eq!(ssh_key.private_key.to_string(), TEST_ENC_STRING_1);
3744 assert_eq!(ssh_key.public_key.unwrap().to_string(), TEST_ENC_STRING_2);
3745 assert_eq!(ssh_key.fingerprint.unwrap().to_string(), TEST_ENC_STRING_3);
3746 }
3747
3748 #[test]
3749 fn test_populate_cipher_types_with_null_data() {
3750 let mut cipher = Cipher {
3751 partial_data: None,
3752 id: Some(TEST_UUID.parse().unwrap()),
3753 organization_id: None,
3754 folder_id: None,
3755 collection_ids: vec![],
3756 key: None,
3757 name: Some(TEST_CIPHER_NAME.parse().unwrap()),
3758 notes: None,
3759 r#type: CipherType::Login,
3760 login: None,
3761 identity: None,
3762 card: None,
3763 secure_note: None,
3764 ssh_key: None,
3765 bank_account: None,
3766 drivers_license: None,
3767 passport: None,
3768 favorite: false,
3769 reprompt: CipherRepromptType::None,
3770 organization_use_totp: false,
3771 edit: true,
3772 view_password: true,
3773 permissions: None,
3774 local_data: None,
3775 attachments: None,
3776 fields: None,
3777 password_history: None,
3778 creation_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
3779 deleted_date: None,
3780 revision_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
3781 archived_date: None,
3782 data: None,
3783 };
3784
3785 let result = cipher.populate_cipher_types();
3786 assert!(matches!(
3787 result,
3788 Err(VaultParseError::MissingField(MissingFieldError("data")))
3789 ));
3790 }
3791
3792 #[test]
3793 fn test_populate_cipher_types_with_invalid_json() {
3794 let mut cipher = Cipher {
3795 partial_data: None,
3796 id: Some(TEST_UUID.parse().unwrap()),
3797 organization_id: None,
3798 folder_id: None,
3799 collection_ids: vec![],
3800 key: None,
3801 name: Some(TEST_CIPHER_NAME.parse().unwrap()),
3802 notes: None,
3803 r#type: CipherType::Login,
3804 login: None,
3805 identity: None,
3806 card: None,
3807 secure_note: None,
3808 ssh_key: None,
3809 bank_account: None,
3810 drivers_license: None,
3811 passport: None,
3812 favorite: false,
3813 reprompt: CipherRepromptType::None,
3814 organization_use_totp: false,
3815 edit: true,
3816 view_password: true,
3817 permissions: None,
3818 local_data: None,
3819 attachments: None,
3820 fields: None,
3821 password_history: None,
3822 creation_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
3823 deleted_date: None,
3824 revision_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
3825 archived_date: None,
3826 data: Some("invalid json".to_string()),
3827 };
3828
3829 let result = cipher.populate_cipher_types();
3830
3831 assert!(matches!(result, Err(VaultParseError::SerdeJson(_))));
3832 }
3833
3834 #[test]
3835 fn test_decrypt_cipher_with_mixed_attachments() {
3836 let user_key: SymmetricCryptoKey = "w2LO+nwV4oxwswVYCxlOfRUseXfvU03VzvKQHrqeklPgiMZrspUe6sOBToCnDn9Ay0tuCBn8ykVVRb7PWhub2Q==".to_string().try_into().unwrap();
3837 let key_store = create_test_crypto_with_user_key(user_key);
3838
3839 let mut ctx = key_store.context();
3841 let valid1 = "valid_file_1.txt"
3842 .encrypt(&mut ctx, SymmetricKeySlotId::User)
3843 .unwrap();
3844 let valid2 = "valid_file_2.txt"
3845 .encrypt(&mut ctx, SymmetricKeySlotId::User)
3846 .unwrap();
3847
3848 let wrong_key: SymmetricCryptoKey = "QUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQQ==".to_string().try_into().unwrap();
3850 let wrong_key_store = create_test_crypto_with_user_key(wrong_key);
3851 let mut wrong_ctx = wrong_key_store.context();
3852 let corrupted = "corrupted_file.txt"
3853 .encrypt(&mut wrong_ctx, SymmetricKeySlotId::User)
3854 .unwrap();
3855
3856 let cipher = Cipher {
3857 partial_data: None,
3858 id: Some("090c19ea-a61a-4df6-8963-262b97bc6266".parse().unwrap()),
3859 organization_id: None,
3860 folder_id: None,
3861 collection_ids: vec![],
3862 key: None,
3863 name: Some(TEST_CIPHER_NAME.parse().unwrap()),
3864 notes: None,
3865 r#type: CipherType::Login,
3866 login: None,
3867 identity: None,
3868 card: None,
3869 secure_note: None,
3870 ssh_key: None,
3871 bank_account: None,
3872 drivers_license: None,
3873 passport: None,
3874 favorite: false,
3875 reprompt: CipherRepromptType::None,
3876 organization_use_totp: false,
3877 edit: true,
3878 permissions: None,
3879 view_password: true,
3880 local_data: None,
3881 attachments: Some(vec![
3882 attachment::Attachment {
3884 id: Some("valid-attachment".to_string()),
3885 url: Some("https://example.com/valid".to_string()),
3886 size: Some("100".to_string()),
3887 size_name: Some("100 Bytes".to_string()),
3888 file_name: Some(valid1),
3889 key: None,
3890 },
3891 attachment::Attachment {
3893 id: Some("corrupted-attachment".to_string()),
3894 url: Some("https://example.com/corrupted".to_string()),
3895 size: Some("200".to_string()),
3896 size_name: Some("200 Bytes".to_string()),
3897 file_name: Some(corrupted),
3898 key: None,
3899 },
3900 attachment::Attachment {
3902 id: Some("valid-attachment-2".to_string()),
3903 url: Some("https://example.com/valid2".to_string()),
3904 size: Some("150".to_string()),
3905 size_name: Some("150 Bytes".to_string()),
3906 file_name: Some(valid2),
3907 key: None,
3908 },
3909 ]),
3910 fields: None,
3911 password_history: None,
3912 creation_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
3913 deleted_date: None,
3914 revision_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
3915 archived_date: None,
3916 data: None,
3917 };
3918
3919 let view: CipherView = key_store.decrypt(&cipher).unwrap();
3920
3921 assert!(view.attachments.is_some());
3923 let successes = view.attachments.as_ref().unwrap();
3924 assert_eq!(successes.len(), 2);
3925 assert_eq!(successes[0].id, Some("valid-attachment".to_string()));
3926 assert_eq!(successes[1].id, Some("valid-attachment-2".to_string()));
3927
3928 assert!(view.attachment_decryption_failures.is_some());
3930 let failures = view.attachment_decryption_failures.as_ref().unwrap();
3931 assert_eq!(failures.len(), 1);
3932 assert_eq!(failures[0].id, Some("corrupted-attachment".to_string()));
3933 assert_eq!(failures[0].file_name, None);
3934 }
3935
3936 #[test]
3937 fn test_decrypt_cipher_list_view_passport() {
3938 let key_store = create_test_crypto_with_user_key(SymmetricCryptoKey::make(
3939 SymmetricKeyAlgorithm::Aes256CbcHmac,
3940 ));
3941
3942 let cipher_view = CipherView {
3943 r#type: CipherType::Passport,
3944 passport: Some(passport::PassportView {
3945 given_name: Some("Jane".to_string()),
3946 surname: Some("Doe".to_string()),
3947 passport_number: Some("P12345678".to_string()),
3948 ..Default::default()
3949 }),
3950 login: None,
3951 ..generate_cipher()
3952 };
3953
3954 let cipher: Cipher = key_store.encrypt(EncryptMode::Legacy(cipher_view)).unwrap();
3955 let list_view: CipherListView = key_store.decrypt(&cipher).unwrap();
3956
3957 assert_eq!(list_view.r#type, CipherListViewType::Passport);
3958 assert_eq!(list_view.subtitle, "Jane Doe");
3959 assert_eq!(
3960 list_view.copyable_fields,
3961 vec![
3962 CopyableCipherFields::PassportGivenName,
3963 CopyableCipherFields::PassportSurname,
3964 CopyableCipherFields::PassportPassportNumber,
3965 ]
3966 );
3967 }
3968
3969 #[test]
3970 fn test_decrypt_cipher_list_view_drivers_license() {
3971 let key_store = create_test_crypto_with_user_key(SymmetricCryptoKey::make(
3972 SymmetricKeyAlgorithm::Aes256CbcHmac,
3973 ));
3974
3975 let cipher_view = CipherView {
3976 r#type: CipherType::DriversLicense,
3977 drivers_license: Some(drivers_license::DriversLicenseView {
3978 first_name: Some("John".to_string()),
3979 last_name: Some("Doe".to_string()),
3980 license_number: Some("DL-987654".to_string()),
3981 ..Default::default()
3982 }),
3983 login: None,
3984 ..generate_cipher()
3985 };
3986
3987 let cipher: Cipher = key_store.encrypt(EncryptMode::Legacy(cipher_view)).unwrap();
3988 let list_view: CipherListView = key_store.decrypt(&cipher).unwrap();
3989
3990 assert_eq!(list_view.r#type, CipherListViewType::DriversLicense);
3991 assert_eq!(list_view.subtitle, "John Doe");
3992 assert_eq!(
3993 list_view.copyable_fields,
3994 vec![
3995 CopyableCipherFields::DriversLicenseFirstName,
3996 CopyableCipherFields::DriversLicenseLastName,
3997 CopyableCipherFields::DriversLicenseLicenseNumber,
3998 ]
3999 );
4000 }
4001
4002 #[test]
4003 fn test_cipher_view_encrypt_decrypt_passport() {
4004 let key_store = create_test_crypto_with_user_key(SymmetricCryptoKey::make(
4005 SymmetricKeyAlgorithm::Aes256CbcHmac,
4006 ));
4007
4008 let passport = passport::PassportView {
4009 given_name: Some("Jane".to_string()),
4010 surname: Some("Doe".to_string()),
4011 date_of_birth: chrono::NaiveDate::from_ymd_opt(1990, 1, 1),
4012 sex: Some("F".to_string()),
4013 birth_place: Some("New York".to_string()),
4014 nationality: Some("American".to_string()),
4015 issuing_country: Some("US".to_string()),
4016 passport_number: Some("P12345678".to_string()),
4017 passport_type: Some("P".to_string()),
4018 national_identification_number: Some("123-45-6789".to_string()),
4019 issuing_authority: Some("US State Department".to_string()),
4020 issue_date: chrono::NaiveDate::from_ymd_opt(2020, 1, 1),
4021 expiration_date: chrono::NaiveDate::from_ymd_opt(2030, 1, 1),
4022 };
4023
4024 let cipher_view = CipherView {
4025 r#type: CipherType::Passport,
4026 passport: Some(passport.clone()),
4027 login: None,
4028 ..generate_cipher()
4029 };
4030
4031 let encrypted: Cipher = key_store.encrypt(EncryptMode::Legacy(cipher_view)).unwrap();
4032 let decrypted: CipherView = key_store.decrypt(&encrypted).unwrap();
4033
4034 assert_eq!(decrypted.r#type, CipherType::Passport);
4035 assert_eq!(decrypted.passport, Some(passport));
4036 assert!(decrypted.login.is_none());
4037 }
4038
4039 #[test]
4040 fn test_cipher_view_encrypt_decrypt_drivers_license() {
4041 let key_store = create_test_crypto_with_user_key(SymmetricCryptoKey::make(
4042 SymmetricKeyAlgorithm::Aes256CbcHmac,
4043 ));
4044
4045 let dl = drivers_license::DriversLicenseView {
4046 first_name: Some("John".to_string()),
4047 middle_name: Some("Michael".to_string()),
4048 last_name: Some("Doe".to_string()),
4049 date_of_birth: chrono::NaiveDate::from_ymd_opt(1985, 6, 15),
4050 license_number: Some("DL-987654".to_string()),
4051 issuing_country: Some("US".to_string()),
4052 issuing_state: Some("NY".to_string()),
4053 issue_date: chrono::NaiveDate::from_ymd_opt(2020, 1, 1),
4054 expiration_date: chrono::NaiveDate::from_ymd_opt(2028, 1, 1),
4055 issuing_authority: Some("NY DMV".to_string()),
4056 license_class: Some("D".to_string()),
4057 };
4058
4059 let cipher_view = CipherView {
4060 r#type: CipherType::DriversLicense,
4061 drivers_license: Some(dl.clone()),
4062 login: None,
4063 ..generate_cipher()
4064 };
4065
4066 let encrypted: Cipher = key_store.encrypt(EncryptMode::Legacy(cipher_view)).unwrap();
4067 let decrypted: CipherView = key_store.decrypt(&encrypted).unwrap();
4068
4069 assert_eq!(decrypted.r#type, CipherType::DriversLicense);
4070 assert_eq!(decrypted.drivers_license, Some(dl));
4071 assert!(decrypted.login.is_none());
4072 }
4073
4074 #[test]
4075 fn test_try_from_cipher_mini_response_model_login() {
4076 use bitwarden_api_api::models::CipherLoginModel;
4077 use chrono::Utc;
4078
4079 let mini_response = CipherMiniResponseModel {
4080 id: Some(TEST_UUID.parse().unwrap()),
4081 organization_id: Some(TEST_UUID.parse().unwrap()),
4082 name: Some(TEST_CIPHER_NAME.to_string()),
4083 r#type: Some(bitwarden_api_api::models::CipherType::Login),
4084 login: Some(Box::new(CipherLoginModel {
4085 username: Some(TEST_CIPHER_NAME.to_string()),
4086 ..Default::default()
4087 })),
4088 creation_date: Some(Utc::now().to_rfc3339()),
4089 revision_date: Some(Utc::now().to_rfc3339()),
4090 ..Default::default()
4091 };
4092
4093 let cipher = Cipher::try_from(mini_response).unwrap();
4094
4095 assert_eq!(cipher.id, Some(TEST_UUID.parse().unwrap()));
4096 assert_eq!(
4097 cipher.organization_id,
4098 Some(TEST_UUID.parse::<OrganizationId>().unwrap())
4099 );
4100 assert_eq!(cipher.r#type, CipherType::Login);
4101 assert_eq!(cipher.name, Some(TEST_CIPHER_NAME.parse().unwrap()));
4102 assert_eq!(
4103 cipher.login.as_ref().unwrap().username,
4104 Some(TEST_CIPHER_NAME.parse().unwrap())
4105 );
4106 assert!(cipher.view_password);
4107 assert!(cipher.key.is_none());
4108 }
4109
4110 #[test]
4111 fn test_mini_response_model_view_password_defaults_to_true() {
4112 use chrono::Utc;
4113
4114 let mini_response = CipherMiniResponseModel {
4117 id: Some(TEST_UUID.parse().unwrap()),
4118 name: Some(TEST_CIPHER_NAME.to_string()),
4119 r#type: Some(bitwarden_api_api::models::CipherType::Login),
4120 creation_date: Some(Utc::now().to_rfc3339()),
4121 revision_date: Some(Utc::now().to_rfc3339()),
4122 ..Default::default()
4123 };
4124
4125 let cipher = mini_response.merge_with_cipher(None).unwrap();
4126 assert!(
4127 cipher.view_password,
4128 "view_password should default to true for CipherMiniResponseModel"
4129 );
4130
4131 let mini_details_response = CipherMiniDetailsResponseModel {
4133 id: Some(TEST_UUID.parse().unwrap()),
4134 name: Some(TEST_CIPHER_NAME.to_string()),
4135 r#type: Some(bitwarden_api_api::models::CipherType::Login),
4136 creation_date: Some(Utc::now().to_rfc3339()),
4137 revision_date: Some(Utc::now().to_rfc3339()),
4138 ..Default::default()
4139 };
4140
4141 let cipher = mini_details_response.merge_with_cipher(None).unwrap();
4142 assert!(
4143 cipher.view_password,
4144 "view_password should default to true for CipherMiniDetailsResponseModel"
4145 );
4146 }
4147
4148 #[test]
4152 fn test_merge_takes_partial_data_from_response() {
4153 use chrono::Utc;
4154
4155 let org: OrganizationId = RESTRICTED_ORG_UUID.parse().unwrap();
4156 let local_restricted = || {
4158 Some(restricted_cipher(
4159 org,
4160 CipherType::Login,
4161 RESTRICTED_LOGIN_ENVELOPE.to_string(),
4162 ))
4163 };
4164 let now = Utc::now().to_rfc3339();
4165
4166 macro_rules! assert_gating_from_response {
4167 ($model:ident) => {{
4168 let base = $model {
4169 id: Some(TEST_UUID.parse().unwrap()),
4170 organization_id: Some(org.to_string().parse().unwrap()),
4171 r#type: Some(bitwarden_api_api::models::CipherType::Login),
4172 creation_date: Some(now.clone()),
4173 revision_date: Some(now.clone()),
4174 ..Default::default()
4175 };
4176
4177 assert_eq!(
4179 base.clone()
4180 .merge_with_cipher(local_restricted())
4181 .unwrap()
4182 .partial_data,
4183 None,
4184 concat!(stringify!($model), ": full response must un-gate"),
4185 );
4186
4187 let restricted = $model {
4189 partial_data: Some(RESTRICTED_LOGIN_ENVELOPE.to_string()),
4190 ..base
4191 };
4192 assert_eq!(
4193 restricted
4194 .merge_with_cipher(None)
4195 .unwrap()
4196 .partial_data
4197 .as_deref(),
4198 Some(RESTRICTED_LOGIN_ENVELOPE),
4199 concat!(stringify!($model), ": restricted response must gate"),
4200 );
4201 }};
4202 }
4203
4204 assert_gating_from_response!(CipherResponseModel);
4205 assert_gating_from_response!(CipherDetailsResponseModel);
4206 assert_gating_from_response!(CipherMiniResponseModel);
4207 assert_gating_from_response!(CipherMiniDetailsResponseModel);
4208 }
4209
4210 mod cipher_decrypt_dispatch {
4213 use bitwarden_crypto::KeyStore;
4214
4215 use super::*;
4216 use crate::{
4217 BankAccountView, CardView, DriversLicenseView, IdentityView, PassportView,
4218 SecureNoteType, SecureNoteView, SshKeyView, cipher::blob::encrypt_blob_cipher,
4219 };
4220
4221 fn make_key_store() -> KeyStore<KeySlotIds> {
4222 create_test_crypto_with_user_key(SymmetricCryptoKey::make(
4223 SymmetricKeyAlgorithm::Aes256CbcHmac,
4224 ))
4225 }
4226
4227 fn encrypt_legacy(view: CipherView, key_store: &KeyStore<KeySlotIds>) -> Cipher {
4229 key_store.encrypt(EncryptMode::Legacy(view)).unwrap()
4230 }
4231
4232 fn encrypt_blob(mut view: CipherView, key_store: &KeyStore<KeySlotIds>) -> Cipher {
4234 let mut ctx = key_store.context_mut();
4235 encrypt_blob_cipher(&mut view, &mut ctx).unwrap()
4236 }
4237
4238 fn base_login_view() -> CipherView {
4239 let mut view = generate_cipher();
4240 view.name = "Test Login".to_string();
4241 view.login = Some(LoginView {
4242 username: Some("[email protected]".to_string()),
4243 password: Some("hunter2".to_string()),
4244 password_revision_date: None,
4245 uris: None,
4246 totp: Some("otpauth://totp/test?secret=SECRET".to_string()),
4247 autofill_on_page_load: None,
4248 http_authentication_enabled: None,
4249 fido2_credentials: None,
4250 });
4251 view
4252 }
4253
4254 #[test]
4256 fn dispatches_blob_to_cipher_view() {
4257 let key_store = make_key_store();
4258 let cipher = encrypt_blob(base_login_view(), &key_store);
4259
4260 let view: CipherView = key_store.decrypt(&cipher).unwrap();
4261
4262 assert_eq!(view.name, "Test Login");
4263 let login = view.login.expect("blob decrypt should restore login");
4264 assert_eq!(login.username.as_deref(), Some("[email protected]"));
4265 assert_eq!(login.password.as_deref(), Some("hunter2"));
4266 }
4267
4268 #[test]
4271 fn dispatches_legacy_to_cipher_view() {
4272 let key_store = make_key_store();
4273
4274 let cipher = encrypt_legacy(base_login_view(), &key_store);
4276 let view: CipherView = key_store.decrypt(&cipher).unwrap();
4277 assert_eq!(view.name, "Test Login");
4278 assert_eq!(
4279 view.login.unwrap().username.as_deref(),
4280 Some("[email protected]"),
4281 );
4282
4283 let cipher = encrypt_legacy(base_login_view(), &key_store);
4285 let view: CipherView = key_store.decrypt(&StrictDecrypt(cipher)).unwrap();
4286 assert_eq!(view.name, "Test Login");
4287 assert_eq!(
4288 view.login.unwrap().username.as_deref(),
4289 Some("[email protected]"),
4290 );
4291 }
4292
4293 #[test]
4298 fn blob_to_list_view_per_type() {
4299 let key_store = make_key_store();
4300
4301 {
4303 let list_view = decrypt_blob_list_view(&key_store, base_login_view());
4304 assert_eq!(list_view.name, "Test Login");
4305 assert_eq!(list_view.subtitle, "[email protected]");
4306 assert!(matches!(list_view.r#type, CipherListViewType::Login(_)));
4307 assert!(
4308 list_view
4309 .copyable_fields
4310 .contains(&CopyableCipherFields::LoginUsername)
4311 );
4312 assert!(
4313 list_view
4314 .copyable_fields
4315 .contains(&CopyableCipherFields::LoginPassword)
4316 );
4317 assert!(
4318 list_view
4319 .copyable_fields
4320 .contains(&CopyableCipherFields::LoginTotp)
4321 );
4322 }
4323
4324 {
4326 let mut view = generate_cipher();
4327 view.r#type = CipherType::Card;
4328 view.login = None;
4329 view.name = "My Card".to_string();
4330 view.card = Some(CardView {
4331 cardholder_name: Some("John Doe".to_string()),
4332 exp_month: Some("12".to_string()),
4333 exp_year: Some("2030".to_string()),
4334 code: Some("123".to_string()),
4335 brand: Some("Visa".to_string()),
4336 number: Some("4111111111111111".to_string()),
4337 });
4338 let list_view = decrypt_blob_list_view(&key_store, view);
4339 assert_eq!(list_view.name, "My Card");
4340 assert!(list_view.subtitle.contains("Visa"));
4341 assert!(list_view.subtitle.contains("1111"));
4342 match &list_view.r#type {
4343 CipherListViewType::Card(card) => {
4344 assert_eq!(card.brand.as_deref(), Some("Visa"))
4345 }
4346 other => panic!("expected Card, got {other:?}"),
4347 }
4348 assert!(
4349 list_view
4350 .copyable_fields
4351 .contains(&CopyableCipherFields::CardNumber)
4352 );
4353 assert!(
4354 list_view
4355 .copyable_fields
4356 .contains(&CopyableCipherFields::CardSecurityCode)
4357 );
4358 }
4359
4360 {
4362 let mut view = generate_cipher();
4363 view.r#type = CipherType::Identity;
4364 view.login = None;
4365 view.name = "My Identity".to_string();
4366 view.identity = Some(IdentityView {
4367 title: None,
4368 first_name: Some("Jane".to_string()),
4369 middle_name: None,
4370 last_name: Some("Doe".to_string()),
4371 address1: Some("123 Main St".to_string()),
4372 address2: None,
4373 address3: None,
4374 city: None,
4375 state: None,
4376 postal_code: None,
4377 country: None,
4378 company: None,
4379 email: Some("[email protected]".to_string()),
4380 phone: None,
4381 ssn: None,
4382 username: None,
4383 passport_number: None,
4384 license_number: None,
4385 });
4386 let list_view = decrypt_blob_list_view(&key_store, view);
4387 assert_eq!(list_view.name, "My Identity");
4388 assert!(list_view.subtitle.contains("Jane"));
4389 assert!(list_view.subtitle.contains("Doe"));
4390 assert!(matches!(list_view.r#type, CipherListViewType::Identity));
4391 assert!(
4392 list_view
4393 .copyable_fields
4394 .contains(&CopyableCipherFields::IdentityEmail)
4395 );
4396 assert!(
4397 list_view
4398 .copyable_fields
4399 .contains(&CopyableCipherFields::IdentityAddress)
4400 );
4401 }
4402
4403 {
4405 let mut view = generate_cipher();
4406 view.r#type = CipherType::SecureNote;
4407 view.login = None;
4408 view.name = "My Note".to_string();
4409 view.notes = Some("secret".to_string());
4410 view.secure_note = Some(SecureNoteView {
4411 r#type: SecureNoteType::Generic,
4412 });
4413 let list_view = decrypt_blob_list_view(&key_store, view);
4414 assert_eq!(list_view.name, "My Note");
4415 assert_eq!(list_view.subtitle, "");
4416 assert!(matches!(list_view.r#type, CipherListViewType::SecureNote));
4417 assert!(
4418 list_view
4419 .copyable_fields
4420 .contains(&CopyableCipherFields::SecureNotes)
4421 );
4422 }
4423
4424 {
4426 let mut view = generate_cipher();
4427 view.r#type = CipherType::SshKey;
4428 view.login = None;
4429 view.name = "My SSH".to_string();
4430 view.ssh_key = Some(SshKeyView {
4431 private_key: "-----BEGIN PRIVATE KEY-----".to_string(),
4432 public_key: "ssh-ed25519 AAAA".to_string(),
4433 fingerprint: "SHA256:abcdef".to_string(),
4434 });
4435 let list_view = decrypt_blob_list_view(&key_store, view);
4436 assert_eq!(list_view.name, "My SSH");
4437 assert_eq!(list_view.subtitle, "SHA256:abcdef");
4438 assert!(matches!(list_view.r#type, CipherListViewType::SshKey));
4439 assert!(
4440 list_view
4441 .copyable_fields
4442 .contains(&CopyableCipherFields::SshKey)
4443 );
4444 }
4445
4446 {
4448 let mut view = generate_cipher();
4449 view.r#type = CipherType::BankAccount;
4450 view.login = None;
4451 view.name = "My Bank Account".to_string();
4452 view.bank_account = Some(BankAccountView {
4453 bank_name: Some("Some Bank".to_string()),
4454 name_on_account: Some("Jane Doe".to_string()),
4455 account_number: Some("123456".to_string()),
4456 routing_number: Some("111000025".to_string()),
4457 branch_number: Some("001".to_string()),
4458 pin: Some("4321".to_string()),
4459 swift_code: Some("ABCDEF12".to_string()),
4460 iban: Some("DE89370400440532013000".to_string()),
4461 ..Default::default()
4462 });
4463 let list_view = decrypt_blob_list_view(&key_store, view);
4464 assert_eq!(list_view.name, "My Bank Account");
4465 assert_eq!(list_view.subtitle, "Some Bank");
4466 assert_eq!(
4467 list_view.r#type,
4468 CipherListViewType::BankAccount(BankAccountListView {
4469 account_number: Some("123456".to_string()),
4470 account_type: None,
4471 })
4472 );
4473 assert_eq!(
4474 list_view.copyable_fields,
4475 vec![
4476 CopyableCipherFields::BankAccountNameOnAccount,
4477 CopyableCipherFields::BankAccountAccountNumber,
4478 CopyableCipherFields::BankAccountRoutingNumber,
4479 CopyableCipherFields::BankAccountBranchNumber,
4480 CopyableCipherFields::BankAccountPin,
4481 CopyableCipherFields::BankAccountIban,
4482 CopyableCipherFields::BankAccountSwift,
4483 ]
4484 );
4485 }
4486 }
4487
4488 fn fully_populated_views() -> Vec<(&'static str, CipherView)> {
4495 let with_type = |r#type: CipherType, f: &dyn Fn(&mut CipherView)| {
4496 let mut view = generate_cipher();
4497 view.r#type = r#type;
4498 view.login = None;
4499 f(&mut view);
4500 view
4501 };
4502
4503 vec![
4504 ("Login", base_login_view()),
4505 (
4506 "Card",
4507 with_type(CipherType::Card, &|v| {
4508 v.card = Some(CardView {
4509 cardholder_name: Some("Jane Doe".to_string()),
4510 exp_month: Some("12".to_string()),
4511 exp_year: Some("2030".to_string()),
4512 code: Some("123".to_string()),
4513 brand: Some("Visa".to_string()),
4514 number: Some("4111111111111111".to_string()),
4515 });
4516 }),
4517 ),
4518 (
4519 "Identity",
4520 with_type(CipherType::Identity, &|v| {
4521 v.identity = Some(IdentityView {
4522 title: Some("Mx".to_string()),
4523 first_name: Some("Jane".to_string()),
4524 middle_name: Some("Q".to_string()),
4525 last_name: Some("Doe".to_string()),
4526 address1: Some("1 Main St".to_string()),
4527 address2: Some("Apt 2".to_string()),
4528 address3: Some("Floor 3".to_string()),
4529 city: Some("Anytown".to_string()),
4530 state: Some("CA".to_string()),
4531 postal_code: Some("90210".to_string()),
4532 country: Some("US".to_string()),
4533 company: Some("Acme".to_string()),
4534 email: Some("[email protected]".to_string()),
4535 phone: Some("555-0100".to_string()),
4536 ssn: Some("000-00-0000".to_string()),
4537 username: Some("jane".to_string()),
4538 passport_number: Some("X1234567".to_string()),
4539 license_number: Some("D1234567".to_string()),
4540 });
4541 }),
4542 ),
4543 (
4544 "SecureNote",
4545 with_type(CipherType::SecureNote, &|v| {
4546 v.notes = Some("a secret note".to_string());
4547 v.secure_note = Some(SecureNoteView {
4548 r#type: SecureNoteType::Generic,
4549 });
4550 }),
4551 ),
4552 (
4553 "SshKey",
4554 with_type(CipherType::SshKey, &|v| {
4555 v.ssh_key = Some(SshKeyView {
4556 private_key: "private".to_string(),
4557 public_key: "public".to_string(),
4558 fingerprint: "SHA256:abc".to_string(),
4559 });
4560 }),
4561 ),
4562 (
4563 "BankAccount",
4564 with_type(CipherType::BankAccount, &|v| {
4565 v.bank_account = Some(BankAccountView {
4566 bank_name: Some("Some Bank".to_string()),
4567 name_on_account: Some("Jane Doe".to_string()),
4568 account_type: Some("Checking".to_string()),
4569 account_number: Some("123456".to_string()),
4570 routing_number: Some("111000025".to_string()),
4571 branch_number: Some("001".to_string()),
4572 pin: Some("4321".to_string()),
4573 swift_code: Some("ABCDEF12".to_string()),
4574 iban: Some("DE89370400440532013000".to_string()),
4575 bank_contact_phone: Some("555-0199".to_string()),
4576 });
4577 }),
4578 ),
4579 (
4580 "DriversLicense",
4581 with_type(CipherType::DriversLicense, &|v| {
4582 v.drivers_license = Some(DriversLicenseView {
4583 first_name: Some("Jane".to_string()),
4584 middle_name: Some("Q".to_string()),
4585 last_name: Some("Doe".to_string()),
4586 date_of_birth: chrono::NaiveDate::from_ymd_opt(1990, 1, 1),
4587 license_number: Some("D1234567".to_string()),
4588 issuing_country: Some("US".to_string()),
4589 issuing_state: Some("CA".to_string()),
4590 issue_date: chrono::NaiveDate::from_ymd_opt(2020, 1, 1),
4591 expiration_date: chrono::NaiveDate::from_ymd_opt(2030, 1, 1),
4592 issuing_authority: Some("DMV".to_string()),
4593 license_class: Some("C".to_string()),
4594 });
4595 }),
4596 ),
4597 (
4598 "Passport",
4599 with_type(CipherType::Passport, &|v| {
4600 v.passport = Some(PassportView {
4601 surname: Some("Doe".to_string()),
4602 given_name: Some("Jane".to_string()),
4603 date_of_birth: chrono::NaiveDate::from_ymd_opt(1990, 1, 1),
4604 sex: Some("F".to_string()),
4605 birth_place: Some("Anytown".to_string()),
4606 nationality: Some("US".to_string()),
4607 issuing_country: Some("US".to_string()),
4608 passport_number: Some("X1234567".to_string()),
4609 passport_type: Some("P".to_string()),
4610 national_identification_number: Some("000-00-0000".to_string()),
4611 issuing_authority: Some("State Dept".to_string()),
4612 issue_date: chrono::NaiveDate::from_ymd_opt(2020, 1, 1),
4613 expiration_date: chrono::NaiveDate::from_ymd_opt(2030, 1, 1),
4614 });
4615 }),
4616 ),
4617 ]
4618 }
4619
4620 #[test]
4627 fn copyable_fields_parity_between_legacy_and_blob() {
4628 let key_store = make_key_store();
4629
4630 for (label, view) in fully_populated_views() {
4631 let legacy: CipherListView = key_store
4632 .decrypt(&encrypt_legacy(view.clone(), &key_store))
4633 .unwrap();
4634 let blob = decrypt_blob_list_view(&key_store, view);
4635
4636 assert_eq!(
4637 legacy.copyable_fields, blob.copyable_fields,
4638 "copyable_fields diverged between legacy and blob paths for {label}",
4639 );
4640 }
4641 }
4642
4643 #[test]
4647 fn login_list_view_preserves_totp_round_trip() {
4648 let key_store = make_key_store();
4649 let list_view = decrypt_blob_list_view(&key_store, base_login_view());
4650
4651 match &list_view.r#type {
4652 CipherListViewType::Login(login) => assert!(login.totp.is_some()),
4653 other => panic!("expected Login, got {other:?}"),
4654 }
4655 let totp = list_view.get_totp_key().unwrap();
4656 assert_eq!(totp.as_deref(), Some("otpauth://totp/test?secret=SECRET"));
4657 }
4658
4659 #[test]
4661 fn mixed_batch_decrypt_list() {
4662 let key_store = make_key_store();
4663 let blob = encrypt_blob(base_login_view(), &key_store);
4664 let legacy = encrypt_legacy(base_login_view(), &key_store);
4665
4666 let ciphers = vec![blob, legacy];
4667 let views: Vec<CipherListView> = key_store.decrypt_list(&ciphers).unwrap();
4668
4669 assert_eq!(views.len(), 2);
4670 for v in &views {
4671 assert_eq!(v.name, "Test Login");
4672 assert_eq!(v.subtitle, "[email protected]");
4673 }
4674 }
4675
4676 fn decrypt_blob_list_view(
4677 key_store: &KeyStore<KeySlotIds>,
4678 view: CipherView,
4679 ) -> CipherListView {
4680 let cipher = encrypt_blob(view, key_store);
4681 key_store.decrypt(&cipher).unwrap()
4682 }
4683
4684 fn failing_attachments() -> Vec<attachment::Attachment> {
4688 let wrong = create_test_crypto_with_user_key(SymmetricCryptoKey::make(
4689 SymmetricKeyAlgorithm::Aes256CbcHmac,
4690 ));
4691 let mut ctx = wrong.context();
4692 let mut enc = |s: &str| s.encrypt(&mut ctx, SymmetricKeySlotId::User).unwrap();
4693 vec![
4694 attachment::Attachment {
4695 id: Some("a1".to_string()),
4696 url: None,
4697 size: None,
4698 size_name: None,
4699 file_name: Some(enc("a1.txt")),
4700 key: Some(enc("k1")),
4701 },
4702 attachment::Attachment {
4703 id: Some("a2-old".to_string()),
4704 url: None,
4705 size: None,
4706 size_name: None,
4707 file_name: Some(enc("a2.txt")),
4708 key: None,
4709 },
4710 attachment::Attachment {
4711 id: Some("a3".to_string()),
4712 url: None,
4713 size: None,
4714 size_name: None,
4715 file_name: Some(enc("a3.txt")),
4716 key: Some(enc("k3")),
4717 },
4718 ]
4719 }
4720
4721 #[test]
4728 fn attachment_metrics_parity_with_failing_attachments() {
4729 let key_store = make_key_store();
4730
4731 let mut legacy = encrypt_legacy(base_login_view(), &key_store);
4732 legacy.attachments = Some(failing_attachments());
4733 let legacy_list: CipherListView = key_store.decrypt(&legacy).unwrap();
4734
4735 let mut blob = encrypt_blob(base_login_view(), &key_store);
4736 blob.attachments = Some(failing_attachments());
4737 let blob_list: CipherListView = key_store.decrypt(&blob).unwrap();
4738
4739 assert_eq!(legacy_list.attachments, 3);
4740 assert!(legacy_list.has_old_attachments);
4741 assert_eq!(blob_list.attachments, legacy_list.attachments);
4742 assert_eq!(
4743 blob_list.has_old_attachments,
4744 legacy_list.has_old_attachments,
4745 );
4746 }
4747 }
4748
4749 mod encrypt_mode {
4752 use bitwarden_crypto::{IdentifyKey, KeyStore};
4753
4754 use super::*;
4755
4756 fn make_key_store() -> KeyStore<KeySlotIds> {
4757 create_test_crypto_with_user_key(SymmetricCryptoKey::make(
4758 SymmetricKeyAlgorithm::Aes256CbcHmac,
4759 ))
4760 }
4761
4762 fn base_login_view() -> CipherView {
4763 let mut view = generate_cipher();
4764 view.name = "Round Trip".to_string();
4765 view.login = Some(LoginView {
4766 username: Some("[email protected]".to_string()),
4767 password: Some("hunter2".to_string()),
4768 password_revision_date: None,
4769 uris: None,
4770 totp: None,
4771 autofill_on_page_load: None,
4772 http_authentication_enabled: None,
4773 fido2_credentials: None,
4774 });
4775 view
4776 }
4777
4778 #[test]
4781 fn blob_variant_produces_blob_shaped_cipher() {
4782 let key_store = make_key_store();
4783 let mode = EncryptMode::Blob(base_login_view());
4784
4785 let cipher: Cipher = key_store.encrypt(mode).unwrap();
4786
4787 assert!(try_parse_blob(&cipher).is_some());
4788 assert!(cipher.data.is_some());
4789 assert!(cipher.login.is_none());
4790 assert!(cipher.card.is_none());
4791 assert!(cipher.identity.is_none());
4792 assert!(cipher.secure_note.is_none());
4793 assert!(cipher.ssh_key.is_none());
4794 assert!(cipher.bank_account.is_none());
4795 assert!(cipher.fields.is_none());
4796 assert!(cipher.password_history.is_none());
4797 assert!(cipher.notes.is_none());
4798 }
4799
4800 #[test]
4803 fn legacy_variant_produces_legacy_shaped_cipher() {
4804 let key_store = make_key_store();
4805 let mode = EncryptMode::Legacy(base_login_view());
4806
4807 let cipher: Cipher = key_store.encrypt(mode).unwrap();
4808
4809 assert!(try_parse_blob(&cipher).is_none());
4810 assert!(cipher.data.is_none());
4811 assert!(cipher.login.is_some());
4812 assert!(
4813 cipher.key.is_some(),
4814 "legacy encrypt must always emit a cipher key"
4815 );
4816 }
4817
4818 #[test]
4822 fn legacy_variant_wraps_cipher_key_under_explicit_key() {
4823 let key_store = make_key_store();
4824 let view = base_login_view();
4825 let mut ctx = key_store.context();
4826
4827 let new_key = ctx.add_local_symmetric_key(SymmetricCryptoKey::make(
4828 SymmetricKeyAlgorithm::Aes256CbcHmac,
4829 ));
4830 let cipher = EncryptMode::Legacy(view.clone())
4831 .encrypt_composite(&mut ctx, new_key)
4832 .unwrap();
4833
4834 let decrypted = lenient_decrypt_cipher_view(&cipher, &mut ctx, new_key).unwrap();
4837 assert_eq!(decrypted.name, view.name);
4838 assert_eq!(
4839 decrypted.login.as_ref().unwrap().password,
4840 view.login.as_ref().unwrap().password
4841 );
4842
4843 assert!(
4845 lenient_decrypt_cipher_view(&cipher, &mut ctx, view.key_identifier()).is_err(),
4846 "cipher key must not be wrapped under the view's own slot"
4847 );
4848 }
4849
4850 #[test]
4852 fn legacy_variant_preserves_existing_cipher_key() {
4853 let key_store = make_key_store();
4854 let mut view = base_login_view();
4855 let mut ctx = key_store.context();
4856
4857 let _ = view.load_cipher_key_slot(&mut ctx).unwrap();
4858 let original_key = view
4859 .key
4860 .clone()
4861 .expect("load_cipher_key_slot stores the key");
4862
4863 let wrapping_key = ctx.add_local_symmetric_key(SymmetricCryptoKey::make(
4864 SymmetricKeyAlgorithm::Aes256CbcHmac,
4865 ));
4866 let cipher = EncryptMode::Legacy(view)
4867 .encrypt_composite(&mut ctx, wrapping_key)
4868 .unwrap();
4869
4870 let unwrapped = ctx
4871 .unwrap_symmetric_key(wrapping_key, &cipher.key.expect("cipher key is emitted"))
4872 .unwrap();
4873 #[allow(deprecated)]
4874 let unwrapped_raw = ctx.dangerous_get_symmetric_key(unwrapped).unwrap().clone();
4875
4876 assert_eq!(
4877 unwrapped_raw, original_key,
4878 "encryption must wrap the view's existing cipher key, not a new one"
4879 );
4880 }
4881
4882 #[test]
4884 fn blob_variant_round_trips_through_decrypt() {
4885 let key_store = make_key_store();
4886 let original = base_login_view();
4887 let mode = EncryptMode::Blob(original.clone());
4888
4889 let cipher: Cipher = key_store.encrypt(mode).unwrap();
4890 let restored: CipherView = key_store.decrypt(&cipher).unwrap();
4891
4892 assert_eq!(restored.name, original.name);
4893 let login = restored.login.expect("round-trip should restore login");
4894 assert_eq!(login.username, original.login.as_ref().unwrap().username);
4895 assert_eq!(login.password, original.login.as_ref().unwrap().password);
4896 }
4897
4898 fn with_http_authentication(enabled: Option<bool>) -> CipherView {
4899 let mut view = base_login_view();
4900 if let Some(login) = view.login.as_mut() {
4901 login.http_authentication_enabled = enabled;
4902 }
4903 view
4904 }
4905
4906 #[test]
4908 fn blob_variant_round_trips_http_authentication_enabled() {
4909 let key_store = make_key_store();
4910
4911 let cipher: Cipher = key_store
4912 .encrypt(EncryptMode::Blob(with_http_authentication(Some(true))))
4913 .unwrap();
4914 let restored: CipherView = key_store.decrypt(&cipher).unwrap();
4915
4916 assert_eq!(
4917 restored.login.unwrap().http_authentication_enabled,
4918 Some(true)
4919 );
4920 }
4921
4922 #[test]
4924 fn blob_variant_stores_missing_http_authentication_enabled_as_off() {
4925 let key_store = make_key_store();
4926
4927 let cipher: Cipher = key_store
4928 .encrypt(EncryptMode::Blob(with_http_authentication(None)))
4929 .unwrap();
4930 let restored: CipherView = key_store.decrypt(&cipher).unwrap();
4931
4932 assert_eq!(
4933 restored.login.unwrap().http_authentication_enabled,
4934 Some(false)
4935 );
4936 }
4937
4938 #[test]
4941 fn legacy_variant_round_trips_http_authentication_enabled() {
4942 let key_store = make_key_store();
4943
4944 let cipher: Cipher = key_store
4945 .encrypt(EncryptMode::Legacy(with_http_authentication(Some(true))))
4946 .unwrap();
4947
4948 assert_eq!(
4949 cipher.login.as_ref().unwrap().http_authentication_enabled,
4950 Some(true)
4951 );
4952
4953 let lenient: CipherView = key_store.decrypt(&cipher).unwrap();
4954 assert_eq!(
4955 lenient.login.unwrap().http_authentication_enabled,
4956 Some(true)
4957 );
4958
4959 let strict: CipherView = key_store.decrypt(&StrictDecrypt(cipher)).unwrap();
4960 assert_eq!(
4961 strict.login.unwrap().http_authentication_enabled,
4962 Some(true)
4963 );
4964 }
4965
4966 #[test]
4968 fn legacy_variant_keeps_missing_http_authentication_enabled_unset() {
4969 let key_store = make_key_store();
4970
4971 let cipher: Cipher = key_store
4972 .encrypt(EncryptMode::Legacy(with_http_authentication(None)))
4973 .unwrap();
4974 let restored: CipherView = key_store.decrypt(&cipher).unwrap();
4975
4976 assert_eq!(restored.login.unwrap().http_authentication_enabled, None);
4977 }
4978
4979 #[test]
4982 fn legacy_http_authentication_enabled_survives_conversion_to_blob() {
4983 let key_store = make_key_store();
4984
4985 let legacy_cipher: Cipher = key_store
4986 .encrypt(EncryptMode::Legacy(with_http_authentication(Some(true))))
4987 .unwrap();
4988 let legacy_view: CipherView = key_store.decrypt(&legacy_cipher).unwrap();
4989
4990 let blob_cipher: Cipher = key_store.encrypt(EncryptMode::Blob(legacy_view)).unwrap();
4991 assert!(try_parse_blob(&blob_cipher).is_some());
4992 assert!(blob_cipher.login.is_none());
4993
4994 let restored: CipherView = key_store.decrypt(&blob_cipher).unwrap();
4995 assert_eq!(
4996 restored.login.unwrap().http_authentication_enabled,
4997 Some(true)
4998 );
4999 }
5000
5001 #[test]
5004 fn key_identifier_delegates_to_inner_view() {
5005 let view = base_login_view();
5006 let expected = view.key_identifier();
5007 let mode = EncryptMode::Blob(view);
5008 assert_eq!(mode.key_identifier(), expected);
5009 }
5010
5011 #[test]
5014 fn mixed_batch_encrypt_list_preserves_per_item_shape() {
5015 let key_store = make_key_store();
5016 let mut legacy_view = base_login_view();
5017 legacy_view.name = "Legacy".to_string();
5018 let mut blob_view = base_login_view();
5019 blob_view.name = "Blob".to_string();
5020
5021 let modes = vec![
5022 EncryptMode::Legacy(legacy_view),
5023 EncryptMode::Blob(blob_view),
5024 ];
5025 let ciphers: Vec<Cipher> = key_store.encrypt_list(&modes).unwrap();
5026
5027 assert_eq!(ciphers.len(), 2);
5028 assert!(
5029 try_parse_blob(&ciphers[0]).is_none(),
5030 "first item should be legacy"
5031 );
5032 assert!(
5033 try_parse_blob(&ciphers[1]).is_some(),
5034 "second item should be blob"
5035 );
5036 assert!(ciphers[0].login.is_some());
5037 assert!(ciphers[1].login.is_none());
5038 }
5039 }
5040}