Skip to main content

bitwarden_vault/cipher/
cipher.rs

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
71/// Helper trait for operations on cipher types.
72pub(super) trait CipherKind {
73    /// Returns the item's subtitle.
74    fn decrypt_subtitle(
75        &self,
76        ctx: &mut KeyStoreContext<KeySlotIds>,
77        key: SymmetricKeySlotId,
78    ) -> Result<String, CryptoError>;
79
80    /// Returns a list of populated fields for the cipher.
81    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    /// The Id of the user that encrypted the cipher. It should always represent a UserId, even for
119    /// Organization-owned ciphers
120    pub encrypted_for: UserId,
121    /// Hex-encoded id of the key the cipher's fields are wrapped under - the organization key for
122    /// Organization-owned ciphers, otherwise the user key - captured at the time the cipher was
123    /// encrypted. The server uses it to reject writes made under a wrong key.
124    #[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/// Encrypted cipher, as stored and synced.
286///
287/// # Encryption-format internal fields
288///
289/// Only metadata fields (ids, `key`, `type`, flags, permissions, dates, `attachments`,
290/// `local_data`) are stable to read. Fields marked "encryption-format internal" depend on the
291/// encryption format and must not be read or filtered on by clients:
292/// - Legacy field-level format: each field is individually encrypted.
293/// - Blob format: these fields are `None`; all sensitive data is sealed in `data`.
294///
295/// Decrypt to [`CipherView`] or [`CipherListView`] to inspect item contents (e.g. whether a
296/// login has a TOTP or passkey).
297#[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    /// Per-cipher key, wrapped under the owning user or organization key, that protects the
309    /// cipher's fields. Always set on ciphers the SDK encrypts; `None` only on legacy
310    /// ciphers that predates per-cipher keys.
311    pub key: Option<EncString>,
312
313    /// Encrypted item name. `None` for blob-encrypted ciphers, where the name lives inside
314    /// the sealed `data` blob; required on the legacy field-level format.
315    /// Encryption-format internal, not public API. See [`Cipher`].
316    pub name: Option<EncString>,
317    /// Encryption-format internal, not public API. See [`Cipher`].
318    pub notes: Option<EncString>,
319
320    pub r#type: CipherType,
321    /// Encryption-format internal, not public API. See [`Cipher`].
322    pub login: Option<Login>,
323    /// Encryption-format internal, not public API. See [`Cipher`].
324    pub identity: Option<identity::Identity>,
325    /// Encryption-format internal, not public API. See [`Cipher`].
326    pub card: Option<card::Card>,
327    /// Encryption-format internal, not public API. See [`Cipher`].
328    pub secure_note: Option<secure_note::SecureNote>,
329    /// Encryption-format internal, not public API. See [`Cipher`].
330    pub ssh_key: Option<ssh_key::SshKey>,
331    /// Encryption-format internal, not public API. See [`Cipher`].
332    pub bank_account: Option<bank_account::BankAccount>,
333    /// Encryption-format internal, not public API. See [`Cipher`].
334    pub drivers_license: Option<drivers_license::DriversLicense>,
335    /// Encryption-format internal, not public API. See [`Cipher`].
336    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    /// Encryption-format internal, not public API. See [`Cipher`].
348    pub fields: Option<Vec<field::Field>>,
349    /// Encryption-format internal, not public API. See [`Cipher`].
350    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    /// Sealed blob holding all sensitive data in the blob format; `None` on the legacy format.
357    /// Opaque, not public API. See [`Cipher`].
358    pub data: Option<String>,
359
360    /// Raw JSON envelope for a server-restricted (PAM-gated) cipher: only contains a sub-set of
361    /// non sensitive fields, all other fields are withheld by the server. Its presence marks the
362    /// cipher restricted; the decrypt path parses only these allowlisted fields and produces a
363    /// view with `partial = true`, never reading the secret payloads.
364    #[serde(default, skip_serializing_if = "Option::is_none")]
365    pub partial_data: Option<String>,
366}
367
368/// Represents the result of re-wrapping a cipher key, which can be needed when changing the
369/// ownership of a cipher or rotating keys.
370pub enum CipherKeyRewrapError {
371    NoCipherKey,
372    DecryptionFailure,
373    EncryptionFailure,
374}
375
376impl Cipher {
377    /// Re-wraps the encrypted cipher-key. This should be done when moving the cipher to a new
378    /// ownership (user to org), or when rotating the owning key. This mutates the cipher's key
379    /// field if successful, otherwise returns an error. Data stays encrypted the same way and
380    /// does not need to be re-uploaded to the server.
381    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    /// Returns `true` if this cipher's sensitive data is stored in the sealed-blob format.
404    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    /// Structural mapping from an encrypted [`Cipher`] to the API's expected
415    /// [`CipherRequestModel`]. No crypto — all encryption happened upstream in
416    /// `CipherView::encrypt_composite`. Callers are responsible for setting
417    /// `encrypted_for` and `encrypted_by_key_id` after the conversion.
418    ///
419    /// Fails with [`CryptoError::MissingField`] if any attachment has no `id`
420    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    /// Attachments that failed to decrypt. Only present when there are decryption failures.
506    #[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    /// True when this view was produced from a server-restricted (PAM-gated) cipher. Only a
516    /// sub-set of fields are populated; every secret field is absent. See
517    /// [`Cipher::partial_data`].
518    /// Such a view is fail-closed against re-encryption: passing it to any encrypt path returns
519    /// [`bitwarden_crypto::CryptoError::EncryptRestrictedView`] rather than silently stripping
520    /// secrets.
521    #[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/// Available fields on a cipher and can be copied from a the list view in the UI.
542#[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    /// The number of attachments
600    pub attachments: u32,
601    /// Indicates if the cipher has old attachments that need to be re-uploaded
602    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    /// Hints for the presentation layer for which fields can be copied.
610    pub copyable_fields: Vec<CopyableCipherFields>,
611
612    pub local_data: Option<LocalDataView>,
613
614    /// True when this view was produced from a server-restricted (PAM-gated) cipher. Only a
615    /// sub-set of fields are populated. See [`Cipher::partial_data`].
616    #[serde(default)]
617    pub partial: bool,
618
619    /// Decrypted cipher notes for search indexing.
620    #[cfg(feature = "wasm")]
621    pub notes: Option<String>,
622    /// Decrypted cipher fields for search indexing.
623    /// Only includes name and value (for text fields only).
624    #[cfg(feature = "wasm")]
625    pub fields: Option<Vec<field::FieldListView>>,
626    /// Decrypted attachment filenames for search indexing.
627    #[cfg(feature = "wasm")]
628    pub attachment_names: Option<Vec<String>>,
629}
630
631/// Represents the result of decrypting a list of ciphers.
632///
633/// This struct contains two vectors: `successes` and `failures`.
634/// `successes` contains the decrypted `CipherListView` objects,
635/// while `failures` contains the original `Cipher` objects that failed to decrypt.
636#[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    /// The decrypted `CipherListView` objects.
642    pub successes: Vec<CipherListView>,
643    /// The original `Cipher` objects that failed to decrypt.
644    pub failures: Vec<Cipher>,
645}
646
647/// Represents the result of decrypting a list of ciphers.
648///
649/// This struct contains two vectors: `successes` and `failures`.
650/// `successes` contains the decrypted `CipherView` objects,
651/// while `failures` contains the original `Cipher` objects that failed to decrypt.
652#[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    /// The decrypted `CipherView` objects.
658    pub successes: Vec<CipherView>,
659    /// The original `Cipher` objects that failed to decrypt.
660    pub failures: Vec<Cipher>,
661}
662
663/// Represents the result of fetching and decrypting all ciphers for an organization.
664///
665/// Contains the encrypted ciphers from the API alongside their decrypted list views.
666#[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    /// All encrypted ciphers returned from the API.
672    pub ciphers: Vec<Cipher>,
673    /// Successfully decrypted `CipherListView` objects.
674    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        // Fail closed: a restricted (partial) view has all secret fields stripped; re-encrypting it
693        // would overwrite the item's secrets with empty values. See
694        // `decrypt_restricted_cipher_view`.
695        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, // TODO: Do we need to repopulate this on this on the cipher?
736        })
737    }
738}
739
740/// Lenient `Cipher` → `CipherView` decryption body. Used by the default
741/// [`Decryptable`] impl on `Cipher` when the cipher is in the legacy field-level
742/// format. Callers funnel through that impl, which dispatches to the blob path
743/// for blob-shaped ciphers — invoking this directly on a blob cipher would
744/// silently return a `CipherView` with empty fields.
745pub(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    // Separate successful and failed attachment decryptions
753    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    // For compatibility we only remove URLs with invalid checksums if the cipher has a key
813    // or the user is on Crypto V2
814    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    /// Decrypt the individual encryption key for this cipher into the provided [KeyStoreContext]
825    /// and return it's identifier. Note that some ciphers do not have individual encryption
826    /// keys, in which case this will return the provided key identifier instead
827    ///
828    /// # Arguments
829    ///
830    /// * `ctx` - The key store context where the cipher key will be decrypted, if it exists
831    /// * `key` - The key to use to decrypt the cipher key, this should be the user or organization
832    ///   key
833    /// * `ciphers_key` - The encrypted cipher key
834    #[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    /// Builds the cryptographic material for a new attachment: a fresh key (raw and wrapped with
847    /// the cipher key) plus the encrypted file name.
848    ///
849    /// # Arguments
850    ///
851    /// * `ctx` - The key store context where the new attachment key will be registered
852    /// * `file_name` - The plaintext file name to encrypt with the cipher key
853    #[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    /// Temporary helper to return a [CipherKind] instance based on the cipher type.
872    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    /// Returns the decrypted subtitle for the cipher, if applicable.
886    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    /// Returns a list of copyable field names for this cipher,
897    /// based on the cipher type and populated properties.
898    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    /// This replaces the values provided by the API in the `login`, `secure_note`, `card`,
905    /// `identity`, `ssh_key`, `bank_account`, `passport`, and `drivers_license` fields,
906    /// relying instead on client-side parsing of the
907    /// `data` field.
908    #[allow(unused)] // Will be used by future changes to support cipher versioning.
909    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    /// Marks the cipher as soft deleted by setting `deletion_date` to now.
929    pub(crate) fn soft_delete(&mut self) {
930        self.deleted_date = Some(Utc::now());
931    }
932}
933impl CipherView {
934    /// Returns the context slot holding the cipher's own key, generating and storing one if the
935    /// view doesn't have it yet. Every cipher the SDK encrypts carries its own key.
936    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    /// Moves the cipher to an organization by assigning the organization ID to the cipher.
975    ///
976    /// # Arguments
977    /// * `organization_id` - The ID of the organization to move the cipher to
978    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    /// Validates that all attachments have keys, returning an error if any are missing.
989    ///
990    /// Key re-wrapping under the new wrapping key happens at encrypt time inside
991    /// `CompositeEncryptable` / `encrypt_legacy_field_encryption`.
992    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    /// Projects this [`CipherView`] into a [`CipherListView`].
1031    ///
1032    /// Used by the blob decryption path: blob ciphers are fully unsealed to a
1033    /// `CipherView` by [`decrypt_blob_cipher`], and this method then derives the
1034    /// list-view shape without re-decrypting any sensitive fields.
1035    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    /// Derives the list-view subtitle from the decrypted view fields.
1123    ///
1124    /// Mirrors the per-type logic that [`CipherKind::decrypt_subtitle`] runs against
1125    /// encrypted fields, but operates on the already-decrypted view.
1126    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    /// Derives copyable-field hints from the decrypted view fields.
1182    ///
1183    /// Mirrors the per-type logic that [`CipherKind::get_copyable_fields`] runs on
1184    /// encrypted types.
1185    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
1334/// Lenient `Cipher` → `CipherListView` decryption body. Used by the default
1335/// [`Decryptable`] impl on `Cipher`; see [`lenient_decrypt_cipher_view`] for rationale.
1336pub(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/// The server's reduced payload for a restricted (PAM-gated) cipher, produced by
1441/// `PartialCipherData.Strip` on the server.
1442///
1443/// This struct is the single authoritative allowlist for what a gated view may expose: the
1444/// encrypted name and, for logins, the encrypted URIs — nothing else. It is deliberately NOT
1445/// `deny_unknown_fields`: the server may decide to include additional non sensitive fields in the
1446/// future; these are silently dropped by the allowlist rather than surfaced onto the view or
1447/// failing the parse.
1448#[derive(Deserialize, Default)]
1449#[serde(rename_all = "camelCase")]
1450struct RestrictedCipherData {
1451    name: Option<EncString>,
1452    uris: Option<Vec<LoginUri>>,
1453}
1454
1455/// Decrypt the restricted `name`. An absent field is legitimate and stays empty in both modes; a
1456/// field that is present but fails to decrypt is a real decryption failure (wrong key / corruption
1457/// / tampering) — it propagates in strict mode and degrades to empty in lenient mode.
1458fn 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
1474/// Decrypt the restricted login `uris`. Absent → `None` in both modes; present-but-undecryptable →
1475/// error in strict mode, `None` in lenient mode. See [`decrypt_restricted_name`].
1476fn 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
1489/// Decrypt a restricted (PAM-gated) cipher into a [`CipherView`].
1490///
1491/// Parses `partial_data` and decrypts ONLY the allowlisted fields — the name and, for logins,
1492/// the URIs. It never reads the cipher's secret payloads (`login.password`, `card`, …), which
1493/// the server withholds anyway. Fail-closed: a malformed envelope always degrades to empty
1494/// rather than un-gating the row (the view is always `partial = true`). A field that is present
1495/// but fails to decrypt degrades to empty in lenient mode, but propagates as an error under
1496/// strict decryption (`strict = true`).
1497fn 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    // Only logins carry URIs; expose them so the partial view can render a domain
1510    // (favicon / launch). Every other login field stays absent.
1511    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        // A restricted view is never re-encrypted (the encrypt paths fail closed on `partial`),
1532        // so it carries no cipher key.
1533        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    // Drop URIs whose checksum doesn't validate — guards against a tampering server, mirroring
1564    // the full decrypt paths (same gate as `lenient_decrypt_cipher_view`).
1565    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
1574/// Decrypt a restricted (PAM-gated) cipher into a [`CipherListView`]. See
1575/// [`decrypt_restricted_cipher_view`] for the allowlist and fail-closed contract. The type
1576/// discriminant is preserved (so the row keeps its icon) but every type payload is empty apart
1577/// from a login's URIs.
1578fn 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            // Partial (PAM-gated) data is only ever produced for organization ciphers. Refuse the
1651            // restricted path for a personal cipher so a user item can never be exposed through the
1652            // weaker partial format. Fail closed.
1653            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            // Partial (PAM-gated) data is only ever produced for organization ciphers. Refuse the
1673            // restricted path for a personal cipher so a user item can never be exposed through the
1674            // weaker partial format. Fail closed.
1675            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
1705/// Generic wrapper that uses strict decryption: field decryption errors are propagated
1706/// instead of silently nulling out the affected fields.
1707///
1708/// This is a transitional type gated behind the `PM-34500-strict_cipher_decryption` feature flag.
1709/// It will eventually replace the default lenient [Decryptable] implementations.
1710///
1711/// TODO [PM-34531]: Remove StrictDecrypt and `PM-34500-strict_cipher_decryption` feature flag
1712/// after feature has fully rolled out.
1713pub(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            // See the org-gate note in the non-strict `Decryptable for Cipher` impl.
1730            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
1744/// Strict Cipher → CipherView decryption body, used by the `StrictDecrypt<Cipher>` impl
1745/// when the cipher is in the legacy field-level format.
1746fn 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    // Separate successful and failed attachment decryptions
1754    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    // For compatibility we only remove URLs with invalid checksums if the cipher has a key
1827    // or the user is on Crypto V2
1828    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            // See the org-gate note in the non-strict `Decryptable for Cipher` impl.
1845            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
1857/// Strict Cipher → CipherListView decryption body, used by the `StrictDecrypt<Cipher>`
1858/// impl when the cipher is in the legacy field-level format.
1859fn 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
1962/// Selects between blob and legacy encryption paths. The variant is chosen at
1963/// the [`CiphersClient`] layer via `should_use_blob_encryption`.
1964///
1965/// [`CiphersClient`]: crate::cipher::cipher_client::CiphersClient
1966pub enum EncryptMode<T> {
1967    /// Encrypt as a sealed blob (current format).
1968    Blob(T),
1969    /// Encrypt using the legacy field-level format.
1970    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            // Both paths take `&mut CipherView` to generate a cipher key when the view lacks one,
1998            // so we hand them a local clone. Both wrap it under the explicit `key`, letting
1999            // callers target a non-`User`/`Organization` slot (e.g. rotation's `Local` slot).
2000            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            // The server may send the IDs under the shared-folder name instead of
2023            // `collectionIds` (see `UseSharedFolderTerms`); accept either.
2024            collection_ids: cipher
2025                .collection_ids
2026                .or(cipher.shared_folder_ids)
2027                .unwrap_or_default()
2028                .into_iter()
2029                .map(CollectionId::new)
2030                .collect(),
2031            name: EncString::try_from_optional(cipher.name)?,
2032            notes: EncString::try_from_optional(cipher.notes)?,
2033            r#type: require!(cipher.r#type).try_into()?,
2034            login: cipher.login.map(|l| (*l).try_into()).transpose()?,
2035            identity: cipher.identity.map(|i| (*i).try_into()).transpose()?,
2036            card: cipher.card.map(|c| (*c).try_into()).transpose()?,
2037            secure_note: cipher.secure_note.map(|s| (*s).try_into()).transpose()?,
2038            ssh_key: cipher.ssh_key.map(|s| (*s).try_into()).transpose()?,
2039            bank_account: cipher.bank_account.map(|b| (*b).try_into()).transpose()?,
2040            drivers_license: cipher
2041                .drivers_license
2042                .map(|d| (*d).try_into())
2043                .transpose()?,
2044            passport: cipher.passport.map(|p| (*p).try_into()).transpose()?,
2045            favorite: cipher.favorite.unwrap_or(false),
2046            reprompt: cipher
2047                .reprompt
2048                .map(|r| r.try_into())
2049                .transpose()?
2050                .unwrap_or(CipherRepromptType::None),
2051            organization_use_totp: cipher.organization_use_totp.unwrap_or(true),
2052            edit: cipher.edit.unwrap_or(true),
2053            permissions: cipher.permissions.map(|p| (*p).try_into()).transpose()?,
2054            view_password: cipher.view_password.unwrap_or(true),
2055            local_data: None, // Not sent from server
2056            attachments: cipher
2057                .attachments
2058                .map(|a| a.into_iter().map(|a| a.try_into()).collect())
2059                .transpose()?,
2060            fields: cipher
2061                .fields
2062                .map(|f| f.into_iter().map(|f| f.try_into()).collect())
2063                .transpose()?,
2064            password_history: cipher
2065                .password_history
2066                .map(|p| p.into_iter().map(|p| p.try_into()).collect())
2067                .transpose()?,
2068            creation_date: require!(cipher.creation_date).parse()?,
2069            deleted_date: cipher.deleted_date.map(|d| d.parse()).transpose()?,
2070            revision_date: require!(cipher.revision_date).parse()?,
2071            key: EncString::try_from_optional(cipher.key)?,
2072            archived_date: cipher.archived_date.map(|d| d.parse()).transpose()?,
2073            data: cipher.data,
2074        })
2075    }
2076}
2077
2078impl PartialCipher for CipherDetailsResponseModel {
2079    fn merge_with_cipher(self, cipher: Option<Cipher>) -> Result<Cipher, VaultParseError> {
2080        Ok(Cipher {
2081            local_data: cipher.and_then(|c| c.local_data),
2082            ..self.try_into()?
2083        })
2084    }
2085}
2086
2087impl TryFrom<bitwarden_api_api::models::CipherType> for CipherType {
2088    type Error = MissingFieldError;
2089
2090    fn try_from(t: bitwarden_api_api::models::CipherType) -> Result<Self, Self::Error> {
2091        Ok(match t {
2092            bitwarden_api_api::models::CipherType::Login => CipherType::Login,
2093            bitwarden_api_api::models::CipherType::SecureNote => CipherType::SecureNote,
2094            bitwarden_api_api::models::CipherType::Card => CipherType::Card,
2095            bitwarden_api_api::models::CipherType::Identity => CipherType::Identity,
2096            bitwarden_api_api::models::CipherType::SSHKey => CipherType::SshKey,
2097            bitwarden_api_api::models::CipherType::BankAccount => CipherType::BankAccount,
2098            bitwarden_api_api::models::CipherType::Passport => CipherType::Passport,
2099            bitwarden_api_api::models::CipherType::DriversLicense => CipherType::DriversLicense,
2100            bitwarden_api_api::models::CipherType::__Unknown(_) => {
2101                return Err(MissingFieldError("type"));
2102            }
2103        })
2104    }
2105}
2106
2107impl TryFrom<bitwarden_api_api::models::CipherRepromptType> for CipherRepromptType {
2108    type Error = MissingFieldError;
2109
2110    fn try_from(t: bitwarden_api_api::models::CipherRepromptType) -> Result<Self, Self::Error> {
2111        Ok(match t {
2112            bitwarden_api_api::models::CipherRepromptType::None => CipherRepromptType::None,
2113            bitwarden_api_api::models::CipherRepromptType::Password => CipherRepromptType::Password,
2114            bitwarden_api_api::models::CipherRepromptType::__Unknown(_) => {
2115                return Err(MissingFieldError("reprompt"));
2116            }
2117        })
2118    }
2119}
2120
2121/// A trait for merging partial cipher data into a full cipher.
2122/// Used to convert from API response models to full Cipher structs,
2123/// without losing local data that may not be present in the API response.
2124pub(crate) trait PartialCipher {
2125    fn merge_with_cipher(self, cipher: Option<Cipher>) -> Result<Cipher, VaultParseError>;
2126}
2127
2128impl From<CipherType> for bitwarden_api_api::models::CipherType {
2129    fn from(t: CipherType) -> Self {
2130        match t {
2131            CipherType::Login => bitwarden_api_api::models::CipherType::Login,
2132            CipherType::SecureNote => bitwarden_api_api::models::CipherType::SecureNote,
2133            CipherType::Card => bitwarden_api_api::models::CipherType::Card,
2134            CipherType::Identity => bitwarden_api_api::models::CipherType::Identity,
2135            CipherType::SshKey => bitwarden_api_api::models::CipherType::SSHKey,
2136            CipherType::BankAccount => bitwarden_api_api::models::CipherType::BankAccount,
2137            CipherType::Passport => bitwarden_api_api::models::CipherType::Passport,
2138            CipherType::DriversLicense => bitwarden_api_api::models::CipherType::DriversLicense,
2139        }
2140    }
2141}
2142
2143impl From<CipherRepromptType> for bitwarden_api_api::models::CipherRepromptType {
2144    fn from(t: CipherRepromptType) -> Self {
2145        match t {
2146            CipherRepromptType::None => bitwarden_api_api::models::CipherRepromptType::None,
2147            CipherRepromptType::Password => bitwarden_api_api::models::CipherRepromptType::Password,
2148        }
2149    }
2150}
2151
2152impl PartialCipher for CipherResponseModel {
2153    fn merge_with_cipher(self, cipher: Option<Cipher>) -> Result<Cipher, VaultParseError> {
2154        Ok(Cipher {
2155            partial_data: self.partial_data,
2156            collection_ids: cipher
2157                .as_ref()
2158                .map(|c| c.collection_ids.clone())
2159                .unwrap_or_default(),
2160            local_data: cipher.and_then(|c| c.local_data),
2161            id: self.id.map(CipherId::new),
2162            organization_id: self.organization_id.map(OrganizationId::new),
2163            folder_id: self.folder_id.map(FolderId::new),
2164            name: self.name.map(|n| n.parse()).transpose()?,
2165            notes: EncString::try_from_optional(self.notes)?,
2166            r#type: require!(self.r#type).try_into()?,
2167            login: self.login.map(|l| (*l).try_into()).transpose()?,
2168            identity: self.identity.map(|i| (*i).try_into()).transpose()?,
2169            card: self.card.map(|c| (*c).try_into()).transpose()?,
2170            secure_note: self.secure_note.map(|s| (*s).try_into()).transpose()?,
2171            ssh_key: self.ssh_key.map(|s| (*s).try_into()).transpose()?,
2172            bank_account: self.bank_account.map(|b| (*b).try_into()).transpose()?,
2173            drivers_license: self.drivers_license.map(|d| (*d).try_into()).transpose()?,
2174            passport: self.passport.map(|p| (*p).try_into()).transpose()?,
2175            favorite: self.favorite.unwrap_or(false),
2176            reprompt: self
2177                .reprompt
2178                .map(|r| r.try_into())
2179                .transpose()?
2180                .unwrap_or(CipherRepromptType::None),
2181            organization_use_totp: self.organization_use_totp.unwrap_or(false),
2182            edit: self.edit.unwrap_or(false),
2183            permissions: self.permissions.map(|p| (*p).try_into()).transpose()?,
2184            view_password: self.view_password.unwrap_or(true),
2185            attachments: self
2186                .attachments
2187                .map(|a| a.into_iter().map(|a| a.try_into()).collect())
2188                .transpose()?,
2189            fields: self
2190                .fields
2191                .map(|f| f.into_iter().map(|f| f.try_into()).collect())
2192                .transpose()?,
2193            password_history: self
2194                .password_history
2195                .map(|p| p.into_iter().map(|p| p.try_into()).collect())
2196                .transpose()?,
2197            creation_date: require!(self.creation_date).parse()?,
2198            deleted_date: self.deleted_date.map(|d| d.parse()).transpose()?,
2199            revision_date: require!(self.revision_date).parse()?,
2200            key: EncString::try_from_optional(self.key)?,
2201            archived_date: self.archived_date.map(|d| d.parse()).transpose()?,
2202            data: self.data,
2203        })
2204    }
2205}
2206
2207/// Converts a response for a cipher without local state, e.g. one fetched through emergency access.
2208impl TryFrom<CipherResponseModel> for Cipher {
2209    type Error = VaultParseError;
2210
2211    fn try_from(cipher: CipherResponseModel) -> Result<Self, Self::Error> {
2212        cipher.merge_with_cipher(None)
2213    }
2214}
2215
2216impl TryFrom<CipherMiniResponseModel> for Cipher {
2217    type Error = VaultParseError;
2218
2219    fn try_from(cipher: CipherMiniResponseModel) -> Result<Self, Self::Error> {
2220        cipher.merge_with_cipher(None)
2221    }
2222}
2223
2224impl PartialCipher for CipherMiniResponseModel {
2225    fn merge_with_cipher(self, cipher: Option<Cipher>) -> Result<Cipher, VaultParseError> {
2226        let cipher = cipher.as_ref();
2227        Ok(Cipher {
2228            partial_data: self.partial_data,
2229            id: self.id.map(CipherId::new),
2230            organization_id: self.organization_id.map(OrganizationId::new),
2231            key: EncString::try_from_optional(self.key)?,
2232            name: EncString::try_from_optional(self.name)?,
2233            notes: EncString::try_from_optional(self.notes)?,
2234            r#type: require!(self.r#type).try_into()?,
2235            login: self.login.map(|l| (*l).try_into()).transpose()?,
2236            identity: self.identity.map(|i| (*i).try_into()).transpose()?,
2237            card: self.card.map(|c| (*c).try_into()).transpose()?,
2238            secure_note: self.secure_note.map(|s| (*s).try_into()).transpose()?,
2239            ssh_key: self.ssh_key.map(|s| (*s).try_into()).transpose()?,
2240            bank_account: self.bank_account.map(|b| (*b).try_into()).transpose()?,
2241            drivers_license: self.drivers_license.map(|d| (*d).try_into()).transpose()?,
2242            passport: self.passport.map(|p| (*p).try_into()).transpose()?,
2243            reprompt: self
2244                .reprompt
2245                .map(|r| r.try_into())
2246                .transpose()?
2247                .unwrap_or(CipherRepromptType::None),
2248            organization_use_totp: self.organization_use_totp.unwrap_or(true),
2249            attachments: self
2250                .attachments
2251                .map(|a| a.into_iter().map(|a| a.try_into()).collect())
2252                .transpose()?,
2253            fields: self
2254                .fields
2255                .map(|f| f.into_iter().map(|f| f.try_into()).collect())
2256                .transpose()?,
2257            password_history: self
2258                .password_history
2259                .map(|p| p.into_iter().map(|p| p.try_into()).collect())
2260                .transpose()?,
2261            creation_date: require!(self.creation_date)
2262                .parse()
2263                .map_err(Into::<VaultParseError>::into)?,
2264            deleted_date: self
2265                .deleted_date
2266                .map(|d| d.parse())
2267                .transpose()
2268                .map_err(Into::<VaultParseError>::into)?,
2269            revision_date: require!(self.revision_date)
2270                .parse()
2271                .map_err(Into::<VaultParseError>::into)?,
2272            archived_date: cipher.map_or(Default::default(), |c| c.archived_date),
2273            folder_id: cipher.map_or(Default::default(), |c| c.folder_id),
2274            favorite: cipher.map_or(Default::default(), |c| c.favorite),
2275            edit: cipher.map_or(Default::default(), |c| c.edit),
2276            permissions: cipher.map_or(Default::default(), |c| c.permissions),
2277            view_password: cipher.is_none_or(|c| c.view_password),
2278            local_data: cipher.map_or(Default::default(), |c| c.local_data.clone()),
2279            data: self.data,
2280            collection_ids: cipher.map_or(Default::default(), |c| c.collection_ids.clone()),
2281        })
2282    }
2283}
2284
2285impl PartialCipher for CipherMiniDetailsResponseModel {
2286    fn merge_with_cipher(self, cipher: Option<Cipher>) -> Result<Cipher, VaultParseError> {
2287        let cipher = cipher.as_ref();
2288        Ok(Cipher {
2289            partial_data: self.partial_data,
2290            id: self.id.map(CipherId::new),
2291            organization_id: self.organization_id.map(OrganizationId::new),
2292            key: EncString::try_from_optional(self.key)?,
2293            name: EncString::try_from_optional(self.name)?,
2294            notes: EncString::try_from_optional(self.notes)?,
2295            r#type: require!(self.r#type).try_into()?,
2296            login: self.login.map(|l| (*l).try_into()).transpose()?,
2297            identity: self.identity.map(|i| (*i).try_into()).transpose()?,
2298            card: self.card.map(|c| (*c).try_into()).transpose()?,
2299            secure_note: self.secure_note.map(|s| (*s).try_into()).transpose()?,
2300            ssh_key: self.ssh_key.map(|s| (*s).try_into()).transpose()?,
2301            bank_account: self.bank_account.map(|b| (*b).try_into()).transpose()?,
2302            drivers_license: self.drivers_license.map(|d| (*d).try_into()).transpose()?,
2303            passport: self.passport.map(|p| (*p).try_into()).transpose()?,
2304            reprompt: self
2305                .reprompt
2306                .map(|r| r.try_into())
2307                .transpose()?
2308                .unwrap_or(CipherRepromptType::None),
2309            organization_use_totp: self.organization_use_totp.unwrap_or(true),
2310            attachments: self
2311                .attachments
2312                .map(|a| a.into_iter().map(|a| a.try_into()).collect())
2313                .transpose()?,
2314            fields: self
2315                .fields
2316                .map(|f| f.into_iter().map(|f| f.try_into()).collect())
2317                .transpose()?,
2318            password_history: self
2319                .password_history
2320                .map(|p| p.into_iter().map(|p| p.try_into()).collect())
2321                .transpose()?,
2322            creation_date: require!(self.creation_date)
2323                .parse()
2324                .map_err(Into::<VaultParseError>::into)?,
2325            deleted_date: self
2326                .deleted_date
2327                .map(|d| d.parse())
2328                .transpose()
2329                .map_err(Into::<VaultParseError>::into)?,
2330            revision_date: require!(self.revision_date)
2331                .parse()
2332                .map_err(Into::<VaultParseError>::into)?,
2333            // The server may send the IDs under the shared-folder name instead of
2334            // `collectionIds` (see `UseSharedFolderTerms`); accept either.
2335            collection_ids: self
2336                .collection_ids
2337                .or(self.shared_folder_ids)
2338                .into_iter()
2339                .flatten()
2340                .map(CollectionId::new)
2341                .collect(),
2342            archived_date: cipher.map_or(Default::default(), |c| c.archived_date),
2343            folder_id: cipher.map_or(Default::default(), |c| c.folder_id),
2344            favorite: cipher.map_or(Default::default(), |c| c.favorite),
2345            edit: cipher.map_or(Default::default(), |c| c.edit),
2346            permissions: cipher.map_or(Default::default(), |c| c.permissions),
2347            view_password: cipher.is_none_or(|c: &Cipher| c.view_password),
2348            data: cipher.map_or(Default::default(), |c| c.data.clone()),
2349            local_data: cipher.map_or(Default::default(), |c| c.local_data.clone()),
2350        })
2351    }
2352}
2353
2354#[cfg(test)]
2355mod tests {
2356
2357    use attachment::AttachmentView;
2358    use bitwarden_core::key_management::{
2359        create_test_crypto_with_user_and_org_key, create_test_crypto_with_user_key,
2360    };
2361    use bitwarden_crypto::{KeyStore, SymmetricCryptoKey, SymmetricKeyAlgorithm};
2362
2363    use super::*;
2364    use crate::{Fido2Credential, PasswordHistoryView, login::Fido2CredentialListView};
2365
2366    // Test constants for encrypted strings
2367    const TEST_ENC_STRING_1: &str = "2.xzDCDWqRBpHm42EilUvyVw==|nIrWV3l/EeTbWTnAznrK0Q==|sUj8ol2OTgvvTvD86a9i9XUP58hmtCEBqhck7xT5YNk=";
2368    const TEST_ENC_STRING_2: &str = "2.M7ZJ7EuFDXCq66gDTIyRIg==|B1V+jroo6+m/dpHx6g8DxA==|PIXPBCwyJ1ady36a7jbcLg346pm/7N/06W4UZxc1TUo=";
2369    const TEST_ENC_STRING_3: &str = "2.d3rzo0P8rxV9Hs1m1BmAjw==|JOwna6i0zs+K7ZghwrZRuw==|SJqKreLag1ID+g6H1OdmQr0T5zTrVWKzD6hGy3fDqB0=";
2370    const TEST_ENC_STRING_4: &str = "2.EBNGgnaMHeO/kYnI3A0jiA==|9YXlrgABP71ebZ5umurCJQ==|GDk5jxiqTYaU7e2AStCFGX+a1kgCIk8j0NEli7Jn0L4=";
2371    const TEST_ENC_STRING_5: &str = "2.hqdioUAc81FsKQmO1XuLQg==|oDRdsJrQjoFu9NrFVy8tcJBAFKBx95gHaXZnWdXbKpsxWnOr2sKipIG43pKKUFuq|3gKZMiboceIB5SLVOULKg2iuyu6xzos22dfJbvx0EHk=";
2372    const TEST_CIPHER_NAME: &str = "2.d3rzo0P8rxV9Hs1m1BmAjw==|JOwna6i0zs+K7ZghwrZRuw==|SJqKreLag1ID+g6H1OdmQr0T5zTrVWKzD6hGy3fDqB0=";
2373    const TEST_UUID: &str = "fd411a1a-fec8-4070-985d-0e6560860e69";
2374
2375    /// Fixed org id + key for the restricted-cipher test vectors (partials are always org-owned).
2376    const RESTRICTED_ORG_UUID: &str = "3cf0d3ba-3ded-4bf3-a51c-b03fd9ac6e07";
2377    const RESTRICTED_ORG_KEY_B64: &str =
2378        "w2LO+nwV4oxwswVYCxlOfRUseXfvU03VzvKQHrqeklPgiMZrspUe6sOBToCnDn9Ay0tuCBn8ykVVRb7PWhub2Q==";
2379
2380    /// `partial_data` vectors: EncStrings encrypted once under [`RESTRICTED_ORG_KEY_B64`] and
2381    /// pinned, so decrypt runs against fixed ciphertext and the format can't silently break.
2382    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}]}"#;
2383    /// [`RESTRICTED_LOGIN_ENVELOPE`] plus an extra `password` field the allowlist must drop.
2384    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="}"#;
2385    const RESTRICTED_SECURE_NOTE_ENVELOPE: &str = r#"{"name":"2.EwVjyRAgPmUvRpyT68lbjQ==|73O9id1+DZevAB3K+2fXnA==|OoJhN3p9UgjQ4yk55OUBZ4nYQMlFcf9wTHPxrOPhQVI="}"#;
2386    const RESTRICTED_CARD_ENVELOPE: &str = r#"{"name":"2.HF21EOZVqF3eyeZtEgxaCg==|zuChVgXPqxipFE6zOBUBXQ==|gxyvw0+gMf5Grxk8EAhpLCBeXdA0kvea2maJmpLIUIw="}"#;
2387
2388    /// Key store for the restricted-cipher vectors: [`RESTRICTED_ORG_KEY_B64`] under
2389    /// [`RESTRICTED_ORG_UUID`] (the user key is unused — restricted decrypt is org-keyed).
2390    fn restricted_test_key_store() -> (OrganizationId, KeyStore<KeySlotIds>) {
2391        let org: OrganizationId = RESTRICTED_ORG_UUID.parse().unwrap();
2392        let org_key: SymmetricCryptoKey = RESTRICTED_ORG_KEY_B64.to_string().try_into().unwrap();
2393        let key_store = create_test_crypto_with_user_and_org_key(
2394            SymmetricCryptoKey::make(SymmetricKeyAlgorithm::Aes256CbcHmac),
2395            org,
2396            org_key,
2397        );
2398        (org, key_store)
2399    }
2400
2401    fn generate_cipher() -> CipherView {
2402        let test_id = "fd411a1a-fec8-4070-985d-0e6560860e69".parse().unwrap();
2403        CipherView {
2404            partial: false,
2405            r#type: CipherType::Login,
2406            login: Some(LoginView {
2407                username: Some("test_username".to_string()),
2408                password: Some("test_password".to_string()),
2409                password_revision_date: None,
2410                uris: None,
2411                totp: None,
2412                autofill_on_page_load: None,
2413                http_authentication_enabled: None,
2414                fido2_credentials: None,
2415            }),
2416            id: Some(test_id),
2417            organization_id: None,
2418            folder_id: None,
2419            collection_ids: vec![],
2420            key: None,
2421            name: "My test login".to_string(),
2422            notes: None,
2423            identity: None,
2424            card: None,
2425            secure_note: None,
2426            ssh_key: None,
2427            bank_account: None,
2428            drivers_license: None,
2429            passport: None,
2430            favorite: false,
2431            reprompt: CipherRepromptType::None,
2432            organization_use_totp: true,
2433            edit: true,
2434            permissions: None,
2435            view_password: true,
2436            local_data: None,
2437            attachments: None,
2438            attachment_decryption_failures: None,
2439            fields: None,
2440            password_history: None,
2441            creation_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
2442            deleted_date: None,
2443            revision_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
2444            archived_date: None,
2445        }
2446    }
2447
2448    fn generate_fido2(
2449        ctx: &mut KeyStoreContext<KeySlotIds>,
2450        key: SymmetricKeySlotId,
2451    ) -> Fido2Credential {
2452        Fido2Credential {
2453            credential_id: "123".to_string().encrypt(ctx, key).unwrap(),
2454            key_type: "public-key".to_string().encrypt(ctx, key).unwrap(),
2455            key_algorithm: "ECDSA".to_string().encrypt(ctx, key).unwrap(),
2456            key_curve: "P-256".to_string().encrypt(ctx, key).unwrap(),
2457            key_value: "123".to_string().encrypt(ctx, key).unwrap(),
2458            rp_id: "123".to_string().encrypt(ctx, key).unwrap(),
2459            user_handle: None,
2460            user_name: None,
2461            counter: "123".to_string().encrypt(ctx, key).unwrap(),
2462            rp_name: None,
2463            user_display_name: None,
2464            discoverable: "true".to_string().encrypt(ctx, key).unwrap(),
2465            creation_date: "2024-06-07T14:12:36.150Z".parse().unwrap(),
2466        }
2467    }
2468
2469    fn generate_fido2_view() -> Fido2CredentialView {
2470        Fido2CredentialView {
2471            credential_id: "123".to_string(),
2472            key_type: "public-key".to_string(),
2473            key_algorithm: "ECDSA".to_string(),
2474            key_curve: "P-256".to_string(),
2475            key_value: "123".to_string(),
2476            rp_id: "123".to_string(),
2477            user_handle: None,
2478            user_name: None,
2479            counter: "123".to_string(),
2480            rp_name: None,
2481            user_display_name: None,
2482            discoverable: "true".to_string(),
2483            creation_date: "2024-06-07T14:12:36.150Z".parse().unwrap(),
2484        }
2485    }
2486
2487    /// Builds a server-restricted (PAM-gated) cipher: no top-level secret fields, only the
2488    /// `partial_data` envelope. Org-owned, since partials always are.
2489    fn restricted_cipher(
2490        organization_id: OrganizationId,
2491        r#type: CipherType,
2492        partial_data: String,
2493    ) -> Cipher {
2494        Cipher {
2495            partial_data: Some(partial_data),
2496            id: Some(TEST_UUID.parse().unwrap()),
2497            organization_id: Some(organization_id),
2498            folder_id: None,
2499            collection_ids: vec![],
2500            key: None,
2501            name: None,
2502            notes: None,
2503            r#type,
2504            login: None,
2505            identity: None,
2506            card: None,
2507            secure_note: None,
2508            ssh_key: None,
2509            bank_account: None,
2510            drivers_license: None,
2511            passport: None,
2512            favorite: false,
2513            reprompt: CipherRepromptType::None,
2514            organization_use_totp: false,
2515            edit: true,
2516            permissions: None,
2517            view_password: true,
2518            local_data: None,
2519            attachments: None,
2520            fields: None,
2521            password_history: None,
2522            creation_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
2523            deleted_date: None,
2524            revision_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
2525            archived_date: None,
2526            data: None,
2527        }
2528    }
2529
2530    #[test]
2531    fn test_decrypt_restricted_cipher_list_view_login() {
2532        let (org, key_store) = restricted_test_key_store();
2533        let cipher = restricted_cipher(
2534            org,
2535            CipherType::Login,
2536            RESTRICTED_LOGIN_ENVELOPE.to_string(),
2537        );
2538        let view: CipherListView = key_store.decrypt(&cipher).unwrap();
2539
2540        assert!(view.partial);
2541        assert_eq!(view.name, "Restricted Name".to_string());
2542        assert!(view.subtitle.is_empty());
2543        assert!(view.copyable_fields.is_empty());
2544        assert_eq!(view.attachments, 0);
2545        match view.r#type {
2546            CipherListViewType::Login(login) => {
2547                assert_eq!(
2548                    login.uris.unwrap()[0].uri.as_deref(),
2549                    Some("https://example.com")
2550                );
2551                assert_eq!(login.username, None);
2552                assert_eq!(login.totp, None);
2553                assert!(!login.has_fido2);
2554            }
2555            other => panic!("expected Login list view, got {other:?}"),
2556        }
2557    }
2558
2559    #[test]
2560    fn test_decrypt_restricted_cipher_view_login_omits_secrets() {
2561        let (org, key_store) = restricted_test_key_store();
2562        // A rogue/over-sharing server also stuffs an encrypted password into the envelope; the
2563        // allowlist (`RestrictedCipherData`) must ignore anything outside name + uris.
2564        let cipher = restricted_cipher(
2565            org,
2566            CipherType::Login,
2567            RESTRICTED_LOGIN_ENVELOPE_WITH_PASSWORD.to_string(),
2568        );
2569        let view: CipherView = key_store.decrypt(&cipher).unwrap();
2570
2571        assert!(view.partial);
2572        assert_eq!(view.name, "Restricted Name".to_string());
2573        let login = view
2574            .login
2575            .expect("login populated so the view can render a domain");
2576        assert_eq!(
2577            login.uris.unwrap()[0].uri.as_deref(),
2578            Some("https://example.com")
2579        );
2580        assert_eq!(login.username, None);
2581        assert_eq!(login.password, None);
2582        assert_eq!(login.totp, None);
2583        assert_eq!(view.notes, None);
2584        assert!(view.card.is_none());
2585    }
2586
2587    #[test]
2588    fn test_decrypt_restricted_non_login_name_only() {
2589        let (org, key_store) = restricted_test_key_store();
2590        let cipher = restricted_cipher(
2591            org,
2592            CipherType::SecureNote,
2593            RESTRICTED_SECURE_NOTE_ENVELOPE.to_string(),
2594        );
2595
2596        let list: CipherListView = key_store.decrypt(&cipher).unwrap();
2597        assert!(list.partial);
2598        assert_eq!(list.name, "Gated Note".to_string());
2599        assert_eq!(list.r#type, CipherListViewType::SecureNote);
2600
2601        let view: CipherView = key_store.decrypt(&cipher).unwrap();
2602        assert!(view.partial);
2603        assert_eq!(view.name, "Gated Note".to_string());
2604        assert!(view.login.is_none());
2605        assert!(view.secure_note.is_none());
2606    }
2607
2608    #[test]
2609    fn test_decrypt_restricted_malformed_envelope_fails_closed() {
2610        let (org, key_store) = restricted_test_key_store();
2611        // A malformed envelope must not un-gate the row: it stays partial, just nameless.
2612        let cipher = restricted_cipher(org, CipherType::Login, "not valid json".to_string());
2613
2614        let list: CipherListView = key_store.decrypt(&cipher).unwrap();
2615        assert!(list.partial);
2616        assert!(list.name.is_empty());
2617
2618        let view: CipherView = key_store.decrypt(&cipher).unwrap();
2619        assert!(view.partial);
2620        assert!(view.name.is_empty());
2621
2622        // A malformed envelope is a wire-shape problem, not a crypto failure: lenient even in
2623        // strict mode.
2624        let strict_view: CipherView = key_store.decrypt(&StrictDecrypt(cipher.clone())).unwrap();
2625        assert!(strict_view.partial);
2626        assert!(strict_view.name.is_empty());
2627    }
2628
2629    #[test]
2630    fn test_decrypt_restricted_works_in_strict_mode() {
2631        let (org, key_store) = restricted_test_key_store();
2632        // A Card with no card payload would hit `MissingField("card")` under strict decrypt —
2633        // the restricted branch must short-circuit before that.
2634        let cipher = restricted_cipher(org, CipherType::Card, RESTRICTED_CARD_ENVELOPE.to_string());
2635
2636        let list: CipherListView = key_store.decrypt(&StrictDecrypt(cipher.clone())).unwrap();
2637        assert!(list.partial);
2638        assert_eq!(list.name, "Restricted Card".to_string());
2639        assert_eq!(
2640            list.r#type,
2641            CipherListViewType::Card(CardListView { brand: None })
2642        );
2643
2644        let view: CipherView = key_store.decrypt(&StrictDecrypt(cipher)).unwrap();
2645        assert!(view.partial);
2646        assert!(view.card.is_none());
2647    }
2648
2649    #[test]
2650    fn test_decrypt_restricted_strict_propagates_field_decrypt_error() {
2651        let (org, key_store) = restricted_test_key_store();
2652        // Encrypt a name under an UNRELATED key so it is present in the envelope but cannot be
2653        // decrypted with the organization key.
2654        let wrong_key_store = create_test_crypto_with_user_key(SymmetricCryptoKey::make(
2655            SymmetricKeyAlgorithm::Aes256CbcHmac,
2656        ));
2657        let bad_name = "boom"
2658            .to_string()
2659            .encrypt(&mut wrong_key_store.context(), SymmetricKeySlotId::User)
2660            .unwrap();
2661        let envelope = serde_json::json!({ "name": bad_name }).to_string();
2662        let cipher = restricted_cipher(org, CipherType::Login, envelope);
2663
2664        // Lenient degrades to an empty name, still gated.
2665        let view: CipherView = key_store.decrypt(&cipher).unwrap();
2666        assert!(view.partial);
2667        assert!(view.name.is_empty());
2668
2669        // Strict surfaces the present-but-undecryptable field as an error (both view and list).
2670        let view_result: Result<CipherView, CryptoError> =
2671            key_store.decrypt(&StrictDecrypt(cipher.clone()));
2672        assert!(view_result.is_err());
2673        let list_result: Result<CipherListView, CryptoError> =
2674            key_store.decrypt(&StrictDecrypt(cipher));
2675        assert!(list_result.is_err());
2676    }
2677
2678    #[test]
2679    fn test_decrypt_restricted_non_org_cipher_fails_closed() {
2680        // A personal cipher carrying `partial_data` must fail closed, never take the restricted
2681        // path.
2682        let (org, key_store) = restricted_test_key_store();
2683        let cipher = Cipher {
2684            organization_id: None,
2685            ..restricted_cipher(
2686                org,
2687                CipherType::SecureNote,
2688                RESTRICTED_SECURE_NOTE_ENVELOPE.to_string(),
2689            )
2690        };
2691
2692        let view_result: Result<CipherView, CryptoError> = key_store.decrypt(&cipher);
2693        assert!(matches!(
2694            view_result.unwrap_err(),
2695            CryptoError::RestrictedCipherRequiresOrganization
2696        ));
2697
2698        let list_result: Result<CipherListView, CryptoError> = key_store.decrypt(&cipher);
2699        assert!(matches!(
2700            list_result.unwrap_err(),
2701            CryptoError::RestrictedCipherRequiresOrganization
2702        ));
2703    }
2704
2705    #[test]
2706    fn test_decrypt_cipher_list_view() {
2707        let key: SymmetricCryptoKey = "w2LO+nwV4oxwswVYCxlOfRUseXfvU03VzvKQHrqeklPgiMZrspUe6sOBToCnDn9Ay0tuCBn8ykVVRb7PWhub2Q==".to_string().try_into().unwrap();
2708        let key_store = create_test_crypto_with_user_key(key);
2709
2710        let cipher = Cipher {
2711            partial_data: None,
2712            id: Some("090c19ea-a61a-4df6-8963-262b97bc6266".parse().unwrap()),
2713            organization_id: None,
2714            folder_id: None,
2715            collection_ids: vec![],
2716            key: None,
2717            name: Some(TEST_CIPHER_NAME.parse().unwrap()),
2718            notes: None,
2719            r#type: CipherType::Login,
2720            login: Some(Login {
2721                username: Some("2.EBNGgnaMHeO/kYnI3A0jiA==|9YXlrgABP71ebZ5umurCJQ==|GDk5jxiqTYaU7e2AStCFGX+a1kgCIk8j0NEli7Jn0L4=".parse().unwrap()),
2722                password: Some("2.M7ZJ7EuFDXCq66gDTIyRIg==|B1V+jroo6+m/dpHx6g8DxA==|PIXPBCwyJ1ady36a7jbcLg346pm/7N/06W4UZxc1TUo=".parse().unwrap()),
2723                password_revision_date: None,
2724                uris: None,
2725                totp: Some("2.hqdioUAc81FsKQmO1XuLQg==|oDRdsJrQjoFu9NrFVy8tcJBAFKBx95gHaXZnWdXbKpsxWnOr2sKipIG43pKKUFuq|3gKZMiboceIB5SLVOULKg2iuyu6xzos22dfJbvx0EHk=".parse().unwrap()),
2726                autofill_on_page_load: None,
2727                http_authentication_enabled: None,
2728                fido2_credentials: Some(vec![generate_fido2(&mut key_store.context(), SymmetricKeySlotId::User)]),
2729            }),
2730            identity: None,
2731            card: None,
2732            secure_note: None,
2733            ssh_key: None,
2734            bank_account: None,
2735            drivers_license: None,
2736            passport: None,
2737            favorite: false,
2738            reprompt: CipherRepromptType::None,
2739            organization_use_totp: false,
2740            edit: true,
2741            permissions: Some(CipherPermissions {
2742                delete: false,
2743                restore: false
2744            }),
2745            view_password: true,
2746            local_data: None,
2747            attachments: None,
2748            fields: None,
2749            password_history: None,
2750            creation_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
2751            deleted_date: None,
2752            revision_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
2753            archived_date: None,
2754            data: None,
2755        };
2756
2757        let view: CipherListView = key_store.decrypt(&cipher).unwrap();
2758
2759        assert_eq!(
2760            view,
2761            CipherListView {
2762                partial: false,
2763                id: cipher.id,
2764                organization_id: cipher.organization_id,
2765                folder_id: cipher.folder_id,
2766                collection_ids: cipher.collection_ids,
2767                name: "My test login".to_string(),
2768                subtitle: "test_username".to_string(),
2769                r#type: CipherListViewType::Login(LoginListView {
2770                    fido2_credentials: Some(vec![Fido2CredentialListView {
2771                        credential_id: "123".to_string(),
2772                        rp_id: "123".to_string(),
2773                        user_handle: None,
2774                        user_name: None,
2775                        user_display_name: None,
2776                        counter: "123".to_string(),
2777                    }]),
2778                    has_fido2: true,
2779                    username: Some("test_username".to_string()),
2780                    totp: cipher.login.as_ref().unwrap().totp.as_ref().map(|t| t
2781                        .decrypt(&mut key_store.context(), SymmetricKeySlotId::User)
2782                        .unwrap()),
2783                    uris: None,
2784                }),
2785                favorite: cipher.favorite,
2786                reprompt: cipher.reprompt,
2787                organization_use_totp: cipher.organization_use_totp,
2788                edit: cipher.edit,
2789                permissions: cipher.permissions,
2790                view_password: cipher.view_password,
2791                attachments: 0,
2792                has_old_attachments: false,
2793                creation_date: cipher.creation_date,
2794                deleted_date: cipher.deleted_date,
2795                revision_date: cipher.revision_date,
2796                copyable_fields: vec![
2797                    CopyableCipherFields::LoginUsername,
2798                    CopyableCipherFields::LoginPassword,
2799                    CopyableCipherFields::LoginTotp
2800                ],
2801                local_data: None,
2802                archived_date: cipher.archived_date,
2803                #[cfg(feature = "wasm")]
2804                notes: None,
2805                #[cfg(feature = "wasm")]
2806                fields: None,
2807                #[cfg(feature = "wasm")]
2808                attachment_names: None,
2809            }
2810        )
2811    }
2812
2813    fn blob_cipher() -> Cipher {
2814        let key_store = create_test_crypto_with_user_key(SymmetricCryptoKey::make(
2815            SymmetricKeyAlgorithm::Aes256CbcHmac,
2816        ));
2817        let cipher: Cipher = key_store
2818            .encrypt(EncryptMode::Blob(generate_cipher()))
2819            .unwrap();
2820        assert!(cipher.data.is_some(), "expected a blob-shaped cipher");
2821        cipher
2822    }
2823
2824    #[test]
2825    fn test_encryption_context_to_cipher_with_id_request_preserves_data() {
2826        let cipher = blob_cipher();
2827        let expected = cipher.data.clone();
2828
2829        let request: CipherWithIdRequestModel = EncryptionContext {
2830            encrypted_for: UserId::new(TEST_UUID.parse().unwrap()),
2831            encrypted_by_key_id: Some("0102030405060708090a0b0c0d0e0f10".to_string()),
2832            cipher,
2833        }
2834        .try_into()
2835        .unwrap();
2836
2837        assert_eq!(request.data, expected);
2838        assert_eq!(
2839            request.encrypted_by_key_id.as_deref(),
2840            Some("0102030405060708090a0b0c0d0e0f10")
2841        );
2842    }
2843
2844    #[test]
2845    fn test_encryption_context_to_cipher_request_preserves_data() {
2846        let cipher = blob_cipher();
2847        let expected = cipher.data.clone();
2848
2849        let request: CipherRequestModel = EncryptionContext {
2850            encrypted_for: UserId::new(TEST_UUID.parse().unwrap()),
2851            encrypted_by_key_id: Some("0102030405060708090a0b0c0d0e0f10".to_string()),
2852            cipher,
2853        }
2854        .into();
2855
2856        assert_eq!(request.data, expected);
2857        assert_eq!(
2858            request.encrypted_by_key_id.as_deref(),
2859            Some("0102030405060708090a0b0c0d0e0f10")
2860        );
2861    }
2862
2863    /// Personal ciphers report the user key's id. This mirrors the lookup the cipher client
2864    /// performs when populating `EncryptionContext::encrypted_by_key_id`.
2865    #[test]
2866    fn test_encrypted_by_key_id_uses_user_key_for_personal_cipher() {
2867        let user_key = SymmetricCryptoKey::make(SymmetricKeyAlgorithm::XChaCha20Poly1305);
2868        let expected = user_key.key_id().unwrap().to_string();
2869        let key_store = create_test_crypto_with_user_key(user_key);
2870
2871        let view = generate_cipher();
2872        assert_eq!(view.key_identifier(), SymmetricKeySlotId::User);
2873
2874        let actual = key_store
2875            .context()
2876            .get_symmetric_key_id(view.key_identifier())
2877            .map(|id| id.to_string());
2878
2879        assert_eq!(actual.as_deref(), Some(expected.as_str()));
2880        // The server only accepts a lowercase hex encoding of the 16 raw bytes.
2881        assert_eq!(expected.len(), 32);
2882        assert!(expected.chars().all(|c| c.is_ascii_hexdigit()));
2883        assert_eq!(expected, expected.to_lowercase());
2884    }
2885
2886    /// Organization-owned ciphers report the *organization* key's id, not the acting user's.
2887    #[test]
2888    fn test_encrypted_by_key_id_uses_org_key_for_org_cipher() {
2889        let org = OrganizationId::new_v4();
2890        let user_key = SymmetricCryptoKey::make(SymmetricKeyAlgorithm::XChaCha20Poly1305);
2891        let org_key = SymmetricCryptoKey::make(SymmetricKeyAlgorithm::XChaCha20Poly1305);
2892        let user_key_id = user_key.key_id().unwrap().to_string();
2893        let org_key_id = org_key.key_id().unwrap().to_string();
2894        assert_ne!(user_key_id, org_key_id);
2895
2896        let key_store = create_test_crypto_with_user_and_org_key(user_key, org, org_key);
2897
2898        let mut view = generate_cipher();
2899        view.organization_id = Some(org);
2900        assert_eq!(view.key_identifier(), SymmetricKeySlotId::Organization(org));
2901
2902        let actual = key_store
2903            .context()
2904            .get_symmetric_key_id(view.key_identifier())
2905            .map(|id| id.to_string());
2906
2907        assert_eq!(actual.as_deref(), Some(org_key_id.as_str()));
2908    }
2909
2910    /// A per-cipher key does not change the answer - the reported id is always the *wrapping* key
2911    /// the cipher key itself is sealed under.
2912    #[test]
2913    fn test_encrypted_by_key_id_ignores_cipher_key() {
2914        let user_key = SymmetricCryptoKey::make(SymmetricKeyAlgorithm::XChaCha20Poly1305);
2915        let expected = user_key.key_id().unwrap().to_string();
2916        let key_store = create_test_crypto_with_user_key(user_key);
2917
2918        let mut view = generate_cipher();
2919        let _ = view.load_cipher_key_slot(&mut key_store.context()).unwrap();
2920        assert!(view.key.is_some());
2921
2922        let actual = key_store
2923            .context()
2924            .get_symmetric_key_id(view.key_identifier())
2925            .map(|id| id.to_string());
2926
2927        assert_eq!(actual.as_deref(), Some(expected.as_str()));
2928    }
2929
2930    /// V1 accounts use AES-CBC-HMAC keys, which have no stored key id and derive one from their
2931    /// key material instead - so the field is still populated, with that derived id.
2932    #[test]
2933    fn test_encrypted_by_key_id_uses_derived_id_for_legacy_user_key() {
2934        let user_key = SymmetricCryptoKey::make(SymmetricKeyAlgorithm::Aes256CbcHmac);
2935        let expected = user_key
2936            .key_id()
2937            .expect("an AES-CBC-HMAC key derives a key id")
2938            .to_string();
2939        let key_store = create_test_crypto_with_user_key(user_key);
2940
2941        let view = generate_cipher();
2942        let actual = key_store
2943            .context()
2944            .get_symmetric_key_id(view.key_identifier())
2945            .map(|id| id.to_string());
2946
2947        assert_eq!(actual.as_deref(), Some(expected.as_str()));
2948    }
2949
2950    #[test]
2951    fn test_decrypt_cipher_fails_with_invalid_name() {
2952        let key_store = create_test_crypto_with_user_key(SymmetricCryptoKey::make(
2953            SymmetricKeyAlgorithm::Aes256CbcHmac,
2954        ));
2955
2956        // Encrypt a valid cipher, then swap name with an EncString from a different key
2957        let cipher = key_store
2958            .encrypt(EncryptMode::Legacy(generate_cipher()))
2959            .unwrap();
2960        let cipher = Cipher {
2961            name: Some(TEST_CIPHER_NAME.parse().unwrap()), // encrypted with a different key
2962            ..cipher
2963        };
2964
2965        // Default (lenient) decryption swallows the error, yielding an empty name
2966        let lenient_result: Result<CipherView, _> = key_store.decrypt(&cipher);
2967        assert!(
2968            lenient_result.is_ok(),
2969            "Lenient decryption should succeed even when name is encrypted with a different key"
2970        );
2971        assert_eq!(
2972            lenient_result.unwrap().name,
2973            String::new(),
2974            "Lenient decryption should yield an empty name on error"
2975        );
2976
2977        // Strict decryption propagates the error
2978        let strict_result: Result<CipherView, _> = key_store.decrypt(&StrictDecrypt(cipher));
2979        assert!(
2980            strict_result.is_err(),
2981            "Strict decryption should fail when name is encrypted with a different key"
2982        );
2983    }
2984
2985    #[test]
2986    fn test_decrypt_cipher_fails_with_invalid_login() {
2987        let key_store = create_test_crypto_with_user_key(SymmetricCryptoKey::make(
2988            SymmetricKeyAlgorithm::Aes256CbcHmac,
2989        ));
2990
2991        // Encrypt a valid cipher, then corrupt the login username
2992        let cipher = key_store
2993            .encrypt(EncryptMode::Legacy(generate_cipher()))
2994            .unwrap();
2995        let cipher = Cipher {
2996            login: Some(Login {
2997                username: Some(TEST_CIPHER_NAME.parse().unwrap()), // encrypted with a different key
2998                ..cipher.login.unwrap()
2999            }),
3000            ..cipher
3001        };
3002
3003        // Default (lenient) decryption swallows the error, yielding None for the username field
3004        let lenient_result: Result<CipherView, _> = key_store.decrypt(&cipher);
3005        assert!(
3006            lenient_result.is_ok(),
3007            "Lenient decryption should succeed even when login username is encrypted with a different key"
3008        );
3009        let lenient_view = lenient_result.unwrap();
3010        assert!(
3011            lenient_view.login.is_some(),
3012            "Lenient decryption should still return the login object"
3013        );
3014        assert!(
3015            lenient_view.login.unwrap().username.is_none(),
3016            "Lenient decryption should null out the failing username field"
3017        );
3018
3019        // Strict decryption propagates the error
3020        let strict_result: Result<CipherView, _> = key_store.decrypt(&StrictDecrypt(cipher));
3021        assert!(
3022            strict_result.is_err(),
3023            "Strict decryption should fail when login username is encrypted with a different key"
3024        );
3025    }
3026
3027    #[test]
3028    fn test_encrypt_legacy_fails_closed_for_partial_view() {
3029        let key_store = create_test_crypto_with_user_key(SymmetricCryptoKey::make(
3030            SymmetricKeyAlgorithm::Aes256CbcHmac,
3031        ));
3032
3033        let mut view = generate_cipher();
3034        view.partial = true;
3035
3036        let result = key_store.encrypt(EncryptMode::Legacy(view));
3037        assert!(matches!(result, Err(CryptoError::EncryptRestrictedView)));
3038    }
3039
3040    #[test]
3041    fn test_encrypt_blob_fails_closed_for_partial_view() {
3042        let key_store = create_test_crypto_with_user_key(SymmetricCryptoKey::make(
3043            SymmetricKeyAlgorithm::Aes256CbcHmac,
3044        ));
3045
3046        let mut view = generate_cipher();
3047        view.partial = true;
3048
3049        let result = key_store.encrypt(EncryptMode::Blob(view));
3050        assert!(matches!(result, Err(CryptoError::EncryptRestrictedView)));
3051    }
3052
3053    #[test]
3054    fn test_encrypt_succeeds_for_non_partial_view() {
3055        let key_store = create_test_crypto_with_user_key(SymmetricCryptoKey::make(
3056            SymmetricKeyAlgorithm::Aes256CbcHmac,
3057        ));
3058
3059        // Control: the same shape of view, but with `partial: false`, must still encrypt
3060        // successfully — proving the guard is specific to `partial` rather than some other
3061        // difference between test fixtures.
3062        let view = generate_cipher();
3063        assert!(!view.partial);
3064
3065        let result = key_store.encrypt(EncryptMode::Legacy(view));
3066        assert!(result.is_ok());
3067    }
3068
3069    #[test]
3070    fn test_load_cipher_key_slot_ignores_attachments_without_key() {
3071        let key = SymmetricCryptoKey::make(SymmetricKeyAlgorithm::Aes256CbcHmac);
3072        let key_store = create_test_crypto_with_user_key(key);
3073
3074        let mut cipher = generate_cipher();
3075        let attachment = AttachmentView {
3076            id: None,
3077            url: None,
3078            size: None,
3079            size_name: None,
3080            file_name: Some("Attachment test name".into()),
3081            key: None,
3082        };
3083        cipher.attachments = Some(vec![attachment]);
3084
3085        let _ = cipher
3086            .load_cipher_key_slot(&mut key_store.context())
3087            .unwrap();
3088        assert!(cipher.attachments.unwrap()[0].key.is_none());
3089    }
3090
3091    #[test]
3092    fn test_validate_attachment_keys_with_cipher_key() {
3093        let old_key = SymmetricCryptoKey::make(SymmetricKeyAlgorithm::Aes256CbcHmac);
3094        let key_store = create_test_crypto_with_user_key(old_key);
3095        let mut ctx = key_store.context_mut();
3096
3097        let mut cipher = generate_cipher();
3098        let _ = cipher.load_cipher_key_slot(&mut ctx).unwrap();
3099
3100        cipher.validate_attachment_keys().unwrap();
3101
3102        assert!(cipher.key.is_some());
3103    }
3104
3105    /// A keyless cipher with no attachments has nothing to orphan, so it must stay rotatable.
3106    #[test]
3107    fn test_validate_attachment_keys_without_attachments() {
3108        let mut cipher = generate_cipher();
3109        assert!(cipher.key.is_none());
3110        assert!(cipher.attachments.is_none());
3111
3112        cipher.validate_attachment_keys().unwrap();
3113    }
3114
3115    #[test]
3116    fn test_move_user_cipher_to_org() {
3117        let org = OrganizationId::new_v4();
3118        let key = SymmetricCryptoKey::make(SymmetricKeyAlgorithm::Aes256CbcHmac);
3119        let org_key = SymmetricCryptoKey::make(SymmetricKeyAlgorithm::Aes256CbcHmac);
3120        let key_store = create_test_crypto_with_user_and_org_key(key, org, org_key);
3121
3122        // Create a cipher with a user key
3123        let mut cipher = generate_cipher();
3124        let _ = cipher
3125            .load_cipher_key_slot(&mut key_store.context())
3126            .unwrap();
3127
3128        cipher.move_to_organization(org).unwrap();
3129        assert_eq!(cipher.organization_id, Some(org));
3130
3131        // Check that the cipher can be encrypted/decrypted with the new org key
3132        let cipher_enc = key_store.encrypt(EncryptMode::Legacy(cipher)).unwrap();
3133        let cipher_dec: CipherView = key_store.decrypt(&cipher_enc).unwrap();
3134
3135        assert_eq!(cipher_dec.name, "My test login");
3136    }
3137
3138    #[test]
3139    fn test_move_user_cipher_to_org_manually() {
3140        let org = OrganizationId::new_v4();
3141        let key = SymmetricCryptoKey::make(SymmetricKeyAlgorithm::Aes256CbcHmac);
3142        let org_key = SymmetricCryptoKey::make(SymmetricKeyAlgorithm::Aes256CbcHmac);
3143        let key_store = create_test_crypto_with_user_and_org_key(key, org, org_key);
3144
3145        // Create a cipher with a user key
3146        let mut cipher = generate_cipher();
3147        let _ = cipher
3148            .load_cipher_key_slot(&mut key_store.context())
3149            .unwrap();
3150
3151        cipher.organization_id = Some(org);
3152
3153        // The cipher key is now stored as raw bytes (not wrapped under the user key), so it can
3154        // be re-wrapped under any available key at encrypt time — this now succeeds.
3155        let cipher_enc = key_store.encrypt(EncryptMode::Legacy(cipher)).unwrap();
3156        let cipher_dec: CipherView = key_store.decrypt(&cipher_enc).unwrap();
3157        assert_eq!(cipher_dec.name, "My test login");
3158    }
3159
3160    #[test]
3161    fn test_move_user_cipher_with_attachment_without_key_to_org() {
3162        let org = OrganizationId::new_v4();
3163        let key = SymmetricCryptoKey::make(SymmetricKeyAlgorithm::Aes256CbcHmac);
3164        let org_key = SymmetricCryptoKey::make(SymmetricKeyAlgorithm::Aes256CbcHmac);
3165        let _key_store = create_test_crypto_with_user_and_org_key(key, org, org_key);
3166
3167        let mut cipher = generate_cipher();
3168        let attachment = AttachmentView {
3169            id: None,
3170            url: None,
3171            size: None,
3172            size_name: None,
3173            file_name: Some("Attachment test name".into()),
3174            key: None,
3175        };
3176        cipher.attachments = Some(vec![attachment]);
3177
3178        // Neither cipher nor attachment have keys, so the cipher can't be moved
3179        assert!(cipher.move_to_organization(org).is_err());
3180    }
3181
3182    #[test]
3183    fn test_move_user_cipher_with_attachment_with_key_to_org() {
3184        let org = OrganizationId::new_v4();
3185        let key = SymmetricCryptoKey::make(SymmetricKeyAlgorithm::Aes256CbcHmac);
3186        let org_key = SymmetricCryptoKey::make(SymmetricKeyAlgorithm::Aes256CbcHmac);
3187        let key_store = create_test_crypto_with_user_and_org_key(key, org, org_key);
3188
3189        // Attachment has a key stored as raw base64 on the view; the cipher itself has no key
3190        let attachment_key_val = {
3191            let mut ctx = key_store.context();
3192            let attachment_key = ctx.generate_symmetric_key();
3193            #[allow(deprecated)]
3194            ctx.dangerous_get_symmetric_key(attachment_key)
3195                .unwrap()
3196                .clone()
3197        };
3198
3199        let mut cipher = generate_cipher();
3200        let attachment = AttachmentView {
3201            id: None,
3202            url: None,
3203            size: None,
3204            size_name: None,
3205            file_name: Some("Attachment test name".into()),
3206            key: Some(attachment_key_val.clone()),
3207        };
3208        cipher.attachments = Some(vec![attachment]);
3209        let cred = generate_fido2_view();
3210        cipher.login.as_mut().unwrap().fido2_credentials = Some(vec![cred]);
3211
3212        cipher.move_to_organization(org).unwrap();
3213
3214        assert!(cipher.key.is_none());
3215
3216        // Attachment raw key bytes are preserved (re-wrapping happens at encrypt time)
3217        assert_eq!(
3218            cipher.attachments.unwrap()[0].key.clone().unwrap(),
3219            attachment_key_val
3220        );
3221
3222        let cred2 = cipher
3223            .login
3224            .unwrap()
3225            .fido2_credentials
3226            .unwrap()
3227            .first()
3228            .unwrap()
3229            .clone();
3230
3231        assert_eq!(cred2.credential_id, "123");
3232    }
3233
3234    #[test]
3235    fn test_move_user_cipher_with_key_with_attachment_with_key_to_org() {
3236        let org = OrganizationId::new_v4();
3237        let key = SymmetricCryptoKey::make(SymmetricKeyAlgorithm::Aes256CbcHmac);
3238        let org_key = SymmetricCryptoKey::make(SymmetricKeyAlgorithm::Aes256CbcHmac);
3239        let key_store = create_test_crypto_with_user_and_org_key(key, org, org_key);
3240
3241        let mut ctx = key_store.context();
3242
3243        let cipher_key = ctx.generate_symmetric_key();
3244        #[allow(deprecated)]
3245        let cipher_key_raw = ctx.dangerous_get_symmetric_key(cipher_key).unwrap().clone();
3246
3247        // Attachment has a key that is encrypted with the cipher key
3248        let attachment_key = ctx.generate_symmetric_key();
3249        #[allow(deprecated)]
3250        let attachment_key_raw = ctx
3251            .dangerous_get_symmetric_key(attachment_key)
3252            .unwrap()
3253            .clone();
3254
3255        let mut cipher = generate_cipher();
3256        cipher.key = Some(cipher_key_raw.clone());
3257
3258        let attachment = AttachmentView {
3259            id: None,
3260            url: None,
3261            size: None,
3262            size_name: None,
3263            file_name: Some("Attachment test name".into()),
3264            key: Some(attachment_key_raw.clone()),
3265        };
3266        cipher.attachments = Some(vec![attachment]);
3267
3268        let cred = generate_fido2_view();
3269        cipher.login.as_mut().unwrap().fido2_credentials = Some(vec![cred.clone()]);
3270
3271        cipher.move_to_organization(org).unwrap();
3272
3273        // Raw cipher key bytes are unchanged (re-wrapping happens at encrypt time)
3274        assert_eq!(cipher.key.clone().unwrap(), cipher_key_raw);
3275
3276        // Attachment raw key bytes are unchanged (re-wrapping happens at encrypt time)
3277        assert_eq!(
3278            cipher.attachments.unwrap()[0].key.as_ref().unwrap(),
3279            &attachment_key_raw
3280        );
3281
3282        let cred2 = cipher
3283            .login
3284            .unwrap()
3285            .fido2_credentials
3286            .unwrap()
3287            .first()
3288            .unwrap()
3289            .clone();
3290
3291        assert_eq!(cred2.credential_id, cred.credential_id);
3292    }
3293
3294    #[test]
3295    fn test_password_history_on_password_change() {
3296        use chrono::Utc;
3297
3298        let original_cipher = generate_cipher();
3299        let mut new_cipher = generate_cipher();
3300
3301        // Change password
3302        if let Some(ref mut login) = new_cipher.login {
3303            login.password = Some("new_password123".to_string());
3304        }
3305
3306        let start = Utc::now();
3307        new_cipher.update_password_history(&original_cipher);
3308        let end = Utc::now();
3309
3310        assert!(new_cipher.password_history.is_some());
3311        let history = new_cipher.password_history.unwrap();
3312        assert_eq!(history.len(), 1);
3313        assert_eq!(history[0].password, "test_password");
3314        assert!(
3315            history[0].last_used_date >= start && history[0].last_used_date <= end,
3316            "last_used_date was not set properly"
3317        );
3318    }
3319
3320    #[test]
3321    fn test_password_history_on_unchanged_password() {
3322        let original_cipher = generate_cipher();
3323        let mut new_cipher = generate_cipher();
3324
3325        new_cipher.update_password_history(&original_cipher);
3326
3327        // Password history should be empty since password didn't change
3328        assert!(
3329            new_cipher.password_history.is_none()
3330                || new_cipher.password_history.as_ref().unwrap().is_empty()
3331        );
3332    }
3333
3334    #[test]
3335    fn test_password_history_is_preserved() {
3336        use chrono::TimeZone;
3337
3338        let mut original_cipher = generate_cipher();
3339        original_cipher.password_history = Some(
3340            (0..4)
3341                .map(|i| PasswordHistoryView {
3342                    password: format!("old_password_{}", i),
3343                    last_used_date: chrono::Utc
3344                        .with_ymd_and_hms(2025, i + 1, i + 1, i, i, i)
3345                        .unwrap(),
3346                })
3347                .collect(),
3348        );
3349
3350        let mut new_cipher = generate_cipher();
3351
3352        new_cipher.update_password_history(&original_cipher);
3353
3354        assert!(new_cipher.password_history.is_some());
3355        let history = new_cipher.password_history.unwrap();
3356        assert_eq!(history.len(), 4);
3357
3358        assert_eq!(history[0].password, "old_password_0");
3359        assert_eq!(
3360            history[0].last_used_date,
3361            chrono::Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap()
3362        );
3363        assert_eq!(history[1].password, "old_password_1");
3364        assert_eq!(
3365            history[1].last_used_date,
3366            chrono::Utc.with_ymd_and_hms(2025, 2, 2, 1, 1, 1).unwrap()
3367        );
3368        assert_eq!(history[2].password, "old_password_2");
3369        assert_eq!(
3370            history[2].last_used_date,
3371            chrono::Utc.with_ymd_and_hms(2025, 3, 3, 2, 2, 2).unwrap()
3372        );
3373        assert_eq!(history[3].password, "old_password_3");
3374        assert_eq!(
3375            history[3].last_used_date,
3376            chrono::Utc.with_ymd_and_hms(2025, 4, 4, 3, 3, 3).unwrap()
3377        );
3378    }
3379
3380    #[test]
3381    fn test_populate_cipher_types_login_with_valid_data() {
3382        let mut cipher = Cipher {
3383            partial_data: None,
3384            id: Some(TEST_UUID.parse().unwrap()),
3385            organization_id: None,
3386            folder_id: None,
3387            collection_ids: vec![],
3388            key: None,
3389            name: Some(TEST_CIPHER_NAME.parse().unwrap()),
3390            notes: None,
3391            r#type: CipherType::Login,
3392            login: None,
3393            identity: None,
3394            card: None,
3395            secure_note: None,
3396            ssh_key: None,
3397            bank_account: None,
3398            drivers_license: None,
3399            passport: None,
3400            favorite: false,
3401            reprompt: CipherRepromptType::None,
3402            organization_use_totp: false,
3403            edit: true,
3404            view_password: true,
3405            permissions: None,
3406            local_data: None,
3407            attachments: None,
3408            fields: None,
3409            password_history: None,
3410            creation_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
3411            deleted_date: None,
3412            revision_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
3413            archived_date: None,
3414            data: Some(format!(
3415                r#"{{"version": 2, "username": "{}", "password": "{}", "organizationUseTotp": true, "favorite": false, "deletedDate": null}}"#,
3416                TEST_ENC_STRING_1, TEST_ENC_STRING_2
3417            )),
3418        };
3419
3420        cipher
3421            .populate_cipher_types()
3422            .expect("populate_cipher_types failed");
3423
3424        assert!(cipher.login.is_some());
3425        let login = cipher.login.unwrap();
3426        assert_eq!(login.username.unwrap().to_string(), TEST_ENC_STRING_1);
3427        assert_eq!(login.password.unwrap().to_string(), TEST_ENC_STRING_2);
3428    }
3429
3430    #[test]
3431    fn test_populate_cipher_types_secure_note() {
3432        let mut cipher = Cipher {
3433            partial_data: None,
3434            id: Some(TEST_UUID.parse().unwrap()),
3435            organization_id: None,
3436            folder_id: None,
3437            collection_ids: vec![],
3438            key: None,
3439            name: Some(TEST_CIPHER_NAME.parse().unwrap()),
3440            notes: None,
3441            r#type: CipherType::SecureNote,
3442            login: None,
3443            identity: None,
3444            card: None,
3445            secure_note: None,
3446            ssh_key: None,
3447            bank_account: None,
3448            drivers_license: None,
3449            passport: None,
3450            favorite: false,
3451            reprompt: CipherRepromptType::None,
3452            organization_use_totp: false,
3453            edit: true,
3454            view_password: true,
3455            permissions: None,
3456            local_data: None,
3457            attachments: None,
3458            fields: None,
3459            password_history: None,
3460            creation_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
3461            deleted_date: None,
3462            revision_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
3463            archived_date: None,
3464            data: Some(r#"{"type": 0, "organizationUseTotp": false, "favorite": false, "deletedDate": null}"#.to_string()),
3465        };
3466
3467        cipher
3468            .populate_cipher_types()
3469            .expect("populate_cipher_types failed");
3470
3471        assert!(cipher.secure_note.is_some());
3472    }
3473
3474    #[test]
3475    fn test_populate_cipher_types_card() {
3476        let mut cipher = Cipher {
3477            partial_data: None,
3478            id: Some(TEST_UUID.parse().unwrap()),
3479            organization_id: None,
3480            folder_id: None,
3481            collection_ids: vec![],
3482            key: None,
3483            name: Some(TEST_CIPHER_NAME.parse().unwrap()),
3484            notes: None,
3485            r#type: CipherType::Card,
3486            login: None,
3487            identity: None,
3488            card: None,
3489            secure_note: None,
3490            ssh_key: None,
3491            bank_account: None,
3492            drivers_license: None,
3493            passport: None,
3494            favorite: false,
3495            reprompt: CipherRepromptType::None,
3496            organization_use_totp: false,
3497            edit: true,
3498            view_password: true,
3499            permissions: None,
3500            local_data: None,
3501            attachments: None,
3502            fields: None,
3503            password_history: None,
3504            creation_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
3505            deleted_date: None,
3506            revision_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
3507            archived_date: None,
3508            data: Some(format!(
3509                r#"{{"cardholderName": "{}", "number": "{}", "expMonth": "{}", "expYear": "{}", "code": "{}", "brand": "{}", "organizationUseTotp": true, "favorite": false, "deletedDate": null}}"#,
3510                TEST_ENC_STRING_1,
3511                TEST_ENC_STRING_2,
3512                TEST_ENC_STRING_3,
3513                TEST_ENC_STRING_4,
3514                TEST_ENC_STRING_5,
3515                TEST_ENC_STRING_1
3516            )),
3517        };
3518
3519        cipher
3520            .populate_cipher_types()
3521            .expect("populate_cipher_types failed");
3522
3523        assert!(cipher.card.is_some());
3524        let card = cipher.card.unwrap();
3525        assert_eq!(
3526            card.cardholder_name.as_ref().unwrap().to_string(),
3527            TEST_ENC_STRING_1
3528        );
3529        assert_eq!(card.number.as_ref().unwrap().to_string(), TEST_ENC_STRING_2);
3530        assert_eq!(
3531            card.exp_month.as_ref().unwrap().to_string(),
3532            TEST_ENC_STRING_3
3533        );
3534        assert_eq!(
3535            card.exp_year.as_ref().unwrap().to_string(),
3536            TEST_ENC_STRING_4
3537        );
3538        assert_eq!(card.code.as_ref().unwrap().to_string(), TEST_ENC_STRING_5);
3539        assert_eq!(card.brand.as_ref().unwrap().to_string(), TEST_ENC_STRING_1);
3540    }
3541
3542    #[test]
3543    fn test_populate_cipher_types_identity() {
3544        let mut cipher = Cipher {
3545            partial_data: None,
3546            id: Some(TEST_UUID.parse().unwrap()),
3547            organization_id: None,
3548            folder_id: None,
3549            collection_ids: vec![],
3550            key: None,
3551            name: Some(TEST_CIPHER_NAME.parse().unwrap()),
3552            notes: None,
3553            r#type: CipherType::Identity,
3554            login: None,
3555            identity: None,
3556            card: None,
3557            secure_note: None,
3558            ssh_key: None,
3559            bank_account: None,
3560            drivers_license: None,
3561            passport: None,
3562            favorite: false,
3563            reprompt: CipherRepromptType::None,
3564            organization_use_totp: false,
3565            edit: true,
3566            view_password: true,
3567            permissions: None,
3568            local_data: None,
3569            attachments: None,
3570            fields: None,
3571            password_history: None,
3572            creation_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
3573            deleted_date: None,
3574            revision_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
3575            archived_date: None,
3576            data: Some(format!(
3577                r#"{{"firstName": "{}", "lastName": "{}", "email": "{}", "phone": "{}", "company": "{}", "address1": "{}", "city": "{}", "state": "{}", "postalCode": "{}", "country": "{}", "organizationUseTotp": false, "favorite": true, "deletedDate": null}}"#,
3578                TEST_ENC_STRING_1,
3579                TEST_ENC_STRING_2,
3580                TEST_ENC_STRING_3,
3581                TEST_ENC_STRING_4,
3582                TEST_ENC_STRING_5,
3583                TEST_ENC_STRING_1,
3584                TEST_ENC_STRING_2,
3585                TEST_ENC_STRING_3,
3586                TEST_ENC_STRING_4,
3587                TEST_ENC_STRING_5
3588            )),
3589        };
3590
3591        cipher
3592            .populate_cipher_types()
3593            .expect("populate_cipher_types failed");
3594
3595        assert!(cipher.identity.is_some());
3596        let identity = cipher.identity.unwrap();
3597        assert_eq!(
3598            identity.first_name.as_ref().unwrap().to_string(),
3599            TEST_ENC_STRING_1
3600        );
3601        assert_eq!(
3602            identity.last_name.as_ref().unwrap().to_string(),
3603            TEST_ENC_STRING_2
3604        );
3605        assert_eq!(
3606            identity.email.as_ref().unwrap().to_string(),
3607            TEST_ENC_STRING_3
3608        );
3609        assert_eq!(
3610            identity.phone.as_ref().unwrap().to_string(),
3611            TEST_ENC_STRING_4
3612        );
3613        assert_eq!(
3614            identity.company.as_ref().unwrap().to_string(),
3615            TEST_ENC_STRING_5
3616        );
3617        assert_eq!(
3618            identity.address1.as_ref().unwrap().to_string(),
3619            TEST_ENC_STRING_1
3620        );
3621        assert_eq!(
3622            identity.city.as_ref().unwrap().to_string(),
3623            TEST_ENC_STRING_2
3624        );
3625        assert_eq!(
3626            identity.state.as_ref().unwrap().to_string(),
3627            TEST_ENC_STRING_3
3628        );
3629        assert_eq!(
3630            identity.postal_code.as_ref().unwrap().to_string(),
3631            TEST_ENC_STRING_4
3632        );
3633        assert_eq!(
3634            identity.country.as_ref().unwrap().to_string(),
3635            TEST_ENC_STRING_5
3636        );
3637    }
3638
3639    #[test]
3640
3641    fn test_password_history_with_hidden_fields() {
3642        let mut original_cipher = generate_cipher();
3643        original_cipher.fields = Some(vec![FieldView {
3644            name: Some("Secret Key".to_string()),
3645            value: Some("old_secret_value".to_string()),
3646            r#type: crate::FieldType::Hidden,
3647            linked_id: None,
3648        }]);
3649
3650        let mut new_cipher = generate_cipher();
3651        new_cipher.fields = Some(vec![FieldView {
3652            name: Some("Secret Key".to_string()),
3653            value: Some("new_secret_value".to_string()),
3654            r#type: crate::FieldType::Hidden,
3655            linked_id: None,
3656        }]);
3657
3658        new_cipher.update_password_history(&original_cipher);
3659
3660        assert!(new_cipher.password_history.is_some());
3661        let history = new_cipher.password_history.unwrap();
3662        assert_eq!(history.len(), 1);
3663        assert_eq!(history[0].password, "Secret Key: old_secret_value");
3664    }
3665
3666    #[test]
3667    fn test_password_history_length_limit() {
3668        use crate::password_history::MAX_PASSWORD_HISTORY_ENTRIES;
3669
3670        let mut original_cipher = generate_cipher();
3671        original_cipher.password_history = Some(
3672            (0..10)
3673                .map(|i| PasswordHistoryView {
3674                    password: format!("old_password_{}", i),
3675                    last_used_date: chrono::Utc::now(),
3676                })
3677                .collect(),
3678        );
3679
3680        let mut new_cipher = original_cipher.clone();
3681        // Change password
3682        if let Some(ref mut login) = new_cipher.login {
3683            login.password = Some("brand_new_password".to_string());
3684        }
3685
3686        new_cipher.update_password_history(&original_cipher);
3687
3688        assert!(new_cipher.password_history.is_some());
3689        let history = new_cipher.password_history.unwrap();
3690
3691        // Should be limited to MAX_PASSWORD_HISTORY_ENTRIES
3692        assert_eq!(history.len(), MAX_PASSWORD_HISTORY_ENTRIES);
3693
3694        // Most recent change (original password) should be first
3695        assert_eq!(history[0].password, "test_password");
3696        // Followed by the oldest entries from the existing history
3697        assert_eq!(history[1].password, "old_password_0");
3698        assert_eq!(history[2].password, "old_password_1");
3699        assert_eq!(history[3].password, "old_password_2");
3700        assert_eq!(history[4].password, "old_password_3");
3701    }
3702
3703    #[test]
3704    fn test_populate_cipher_types_ssh_key() {
3705        let mut cipher = Cipher {
3706            partial_data: None,
3707            id: Some(TEST_UUID.parse().unwrap()),
3708            organization_id: None,
3709            folder_id: None,
3710            collection_ids: vec![],
3711            key: None,
3712            name: Some(TEST_CIPHER_NAME.parse().unwrap()),
3713            notes: None,
3714            r#type: CipherType::SshKey,
3715            login: None,
3716            identity: None,
3717            card: None,
3718            secure_note: None,
3719            ssh_key: None,
3720            bank_account: None,
3721            drivers_license: None,
3722            passport: None,
3723            favorite: false,
3724            reprompt: CipherRepromptType::None,
3725            organization_use_totp: false,
3726            edit: true,
3727            view_password: true,
3728            permissions: None,
3729            local_data: None,
3730            attachments: None,
3731            fields: None,
3732            password_history: None,
3733            creation_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
3734            deleted_date: None,
3735            revision_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
3736            archived_date: None,
3737            data: Some(format!(
3738                r#"{{"privateKey": "{}", "publicKey": "{}", "fingerprint": "{}", "organizationUseTotp": true, "favorite": false, "deletedDate": null}}"#,
3739                TEST_ENC_STRING_1, TEST_ENC_STRING_2, TEST_ENC_STRING_3
3740            )),
3741        };
3742
3743        cipher
3744            .populate_cipher_types()
3745            .expect("populate_cipher_types failed");
3746
3747        assert!(cipher.ssh_key.is_some());
3748        let ssh_key = cipher.ssh_key.unwrap();
3749        assert_eq!(ssh_key.private_key.to_string(), TEST_ENC_STRING_1);
3750        assert_eq!(ssh_key.public_key.unwrap().to_string(), TEST_ENC_STRING_2);
3751        assert_eq!(ssh_key.fingerprint.unwrap().to_string(), TEST_ENC_STRING_3);
3752    }
3753
3754    #[test]
3755    fn test_populate_cipher_types_with_null_data() {
3756        let mut cipher = Cipher {
3757            partial_data: None,
3758            id: Some(TEST_UUID.parse().unwrap()),
3759            organization_id: None,
3760            folder_id: None,
3761            collection_ids: vec![],
3762            key: None,
3763            name: Some(TEST_CIPHER_NAME.parse().unwrap()),
3764            notes: None,
3765            r#type: CipherType::Login,
3766            login: None,
3767            identity: None,
3768            card: None,
3769            secure_note: None,
3770            ssh_key: None,
3771            bank_account: None,
3772            drivers_license: None,
3773            passport: None,
3774            favorite: false,
3775            reprompt: CipherRepromptType::None,
3776            organization_use_totp: false,
3777            edit: true,
3778            view_password: true,
3779            permissions: None,
3780            local_data: None,
3781            attachments: None,
3782            fields: None,
3783            password_history: None,
3784            creation_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
3785            deleted_date: None,
3786            revision_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
3787            archived_date: None,
3788            data: None,
3789        };
3790
3791        let result = cipher.populate_cipher_types();
3792        assert!(matches!(
3793            result,
3794            Err(VaultParseError::MissingField(MissingFieldError("data")))
3795        ));
3796    }
3797
3798    #[test]
3799    fn test_populate_cipher_types_with_invalid_json() {
3800        let mut cipher = Cipher {
3801            partial_data: None,
3802            id: Some(TEST_UUID.parse().unwrap()),
3803            organization_id: None,
3804            folder_id: None,
3805            collection_ids: vec![],
3806            key: None,
3807            name: Some(TEST_CIPHER_NAME.parse().unwrap()),
3808            notes: None,
3809            r#type: CipherType::Login,
3810            login: None,
3811            identity: None,
3812            card: None,
3813            secure_note: None,
3814            ssh_key: None,
3815            bank_account: None,
3816            drivers_license: None,
3817            passport: None,
3818            favorite: false,
3819            reprompt: CipherRepromptType::None,
3820            organization_use_totp: false,
3821            edit: true,
3822            view_password: true,
3823            permissions: None,
3824            local_data: None,
3825            attachments: None,
3826            fields: None,
3827            password_history: None,
3828            creation_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
3829            deleted_date: None,
3830            revision_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
3831            archived_date: None,
3832            data: Some("invalid json".to_string()),
3833        };
3834
3835        let result = cipher.populate_cipher_types();
3836
3837        assert!(matches!(result, Err(VaultParseError::SerdeJson(_))));
3838    }
3839
3840    #[test]
3841    fn test_decrypt_cipher_with_mixed_attachments() {
3842        let user_key: SymmetricCryptoKey = "w2LO+nwV4oxwswVYCxlOfRUseXfvU03VzvKQHrqeklPgiMZrspUe6sOBToCnDn9Ay0tuCBn8ykVVRb7PWhub2Q==".to_string().try_into().unwrap();
3843        let key_store = create_test_crypto_with_user_key(user_key);
3844
3845        // Create properly encrypted attachments
3846        let mut ctx = key_store.context();
3847        let valid1 = "valid_file_1.txt"
3848            .encrypt(&mut ctx, SymmetricKeySlotId::User)
3849            .unwrap();
3850        let valid2 = "valid_file_2.txt"
3851            .encrypt(&mut ctx, SymmetricKeySlotId::User)
3852            .unwrap();
3853
3854        // Create corrupted attachment by encrypting with a random different key
3855        let wrong_key: SymmetricCryptoKey = "QUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQQ==".to_string().try_into().unwrap();
3856        let wrong_key_store = create_test_crypto_with_user_key(wrong_key);
3857        let mut wrong_ctx = wrong_key_store.context();
3858        let corrupted = "corrupted_file.txt"
3859            .encrypt(&mut wrong_ctx, SymmetricKeySlotId::User)
3860            .unwrap();
3861
3862        let cipher = Cipher {
3863            partial_data: None,
3864            id: Some("090c19ea-a61a-4df6-8963-262b97bc6266".parse().unwrap()),
3865            organization_id: None,
3866            folder_id: None,
3867            collection_ids: vec![],
3868            key: None,
3869            name: Some(TEST_CIPHER_NAME.parse().unwrap()),
3870            notes: None,
3871            r#type: CipherType::Login,
3872            login: None,
3873            identity: None,
3874            card: None,
3875            secure_note: None,
3876            ssh_key: None,
3877            bank_account: None,
3878            drivers_license: None,
3879            passport: None,
3880            favorite: false,
3881            reprompt: CipherRepromptType::None,
3882            organization_use_totp: false,
3883            edit: true,
3884            permissions: None,
3885            view_password: true,
3886            local_data: None,
3887            attachments: Some(vec![
3888                // Valid attachment
3889                attachment::Attachment {
3890                    id: Some("valid-attachment".to_string()),
3891                    url: Some("https://example.com/valid".to_string()),
3892                    size: Some("100".to_string()),
3893                    size_name: Some("100 Bytes".to_string()),
3894                    file_name: Some(valid1),
3895                    key: None,
3896                },
3897                // Corrupted attachment
3898                attachment::Attachment {
3899                    id: Some("corrupted-attachment".to_string()),
3900                    url: Some("https://example.com/corrupted".to_string()),
3901                    size: Some("200".to_string()),
3902                    size_name: Some("200 Bytes".to_string()),
3903                    file_name: Some(corrupted),
3904                    key: None,
3905                },
3906                // Another valid attachment
3907                attachment::Attachment {
3908                    id: Some("valid-attachment-2".to_string()),
3909                    url: Some("https://example.com/valid2".to_string()),
3910                    size: Some("150".to_string()),
3911                    size_name: Some("150 Bytes".to_string()),
3912                    file_name: Some(valid2),
3913                    key: None,
3914                },
3915            ]),
3916            fields: None,
3917            password_history: None,
3918            creation_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
3919            deleted_date: None,
3920            revision_date: "2024-01-30T17:55:36.150Z".parse().unwrap(),
3921            archived_date: None,
3922            data: None,
3923        };
3924
3925        let view: CipherView = key_store.decrypt(&cipher).unwrap();
3926
3927        // Should have 2 successful attachments
3928        assert!(view.attachments.is_some());
3929        let successes = view.attachments.as_ref().unwrap();
3930        assert_eq!(successes.len(), 2);
3931        assert_eq!(successes[0].id, Some("valid-attachment".to_string()));
3932        assert_eq!(successes[1].id, Some("valid-attachment-2".to_string()));
3933
3934        // Should have 1 failed attachment
3935        assert!(view.attachment_decryption_failures.is_some());
3936        let failures = view.attachment_decryption_failures.as_ref().unwrap();
3937        assert_eq!(failures.len(), 1);
3938        assert_eq!(failures[0].id, Some("corrupted-attachment".to_string()));
3939        assert_eq!(failures[0].file_name, None);
3940    }
3941
3942    #[test]
3943    fn test_decrypt_cipher_list_view_passport() {
3944        let key_store = create_test_crypto_with_user_key(SymmetricCryptoKey::make(
3945            SymmetricKeyAlgorithm::Aes256CbcHmac,
3946        ));
3947
3948        let cipher_view = CipherView {
3949            r#type: CipherType::Passport,
3950            passport: Some(passport::PassportView {
3951                given_name: Some("Jane".to_string()),
3952                surname: Some("Doe".to_string()),
3953                passport_number: Some("P12345678".to_string()),
3954                ..Default::default()
3955            }),
3956            login: None,
3957            ..generate_cipher()
3958        };
3959
3960        let cipher: Cipher = key_store.encrypt(EncryptMode::Legacy(cipher_view)).unwrap();
3961        let list_view: CipherListView = key_store.decrypt(&cipher).unwrap();
3962
3963        assert_eq!(list_view.r#type, CipherListViewType::Passport);
3964        assert_eq!(list_view.subtitle, "Jane Doe");
3965        assert_eq!(
3966            list_view.copyable_fields,
3967            vec![
3968                CopyableCipherFields::PassportGivenName,
3969                CopyableCipherFields::PassportSurname,
3970                CopyableCipherFields::PassportPassportNumber,
3971            ]
3972        );
3973    }
3974
3975    #[test]
3976    fn test_decrypt_cipher_list_view_drivers_license() {
3977        let key_store = create_test_crypto_with_user_key(SymmetricCryptoKey::make(
3978            SymmetricKeyAlgorithm::Aes256CbcHmac,
3979        ));
3980
3981        let cipher_view = CipherView {
3982            r#type: CipherType::DriversLicense,
3983            drivers_license: Some(drivers_license::DriversLicenseView {
3984                first_name: Some("John".to_string()),
3985                last_name: Some("Doe".to_string()),
3986                license_number: Some("DL-987654".to_string()),
3987                ..Default::default()
3988            }),
3989            login: None,
3990            ..generate_cipher()
3991        };
3992
3993        let cipher: Cipher = key_store.encrypt(EncryptMode::Legacy(cipher_view)).unwrap();
3994        let list_view: CipherListView = key_store.decrypt(&cipher).unwrap();
3995
3996        assert_eq!(list_view.r#type, CipherListViewType::DriversLicense);
3997        assert_eq!(list_view.subtitle, "John Doe");
3998        assert_eq!(
3999            list_view.copyable_fields,
4000            vec![
4001                CopyableCipherFields::DriversLicenseFirstName,
4002                CopyableCipherFields::DriversLicenseLastName,
4003                CopyableCipherFields::DriversLicenseLicenseNumber,
4004            ]
4005        );
4006    }
4007
4008    #[test]
4009    fn test_cipher_view_encrypt_decrypt_passport() {
4010        let key_store = create_test_crypto_with_user_key(SymmetricCryptoKey::make(
4011            SymmetricKeyAlgorithm::Aes256CbcHmac,
4012        ));
4013
4014        let passport = passport::PassportView {
4015            given_name: Some("Jane".to_string()),
4016            surname: Some("Doe".to_string()),
4017            date_of_birth: chrono::NaiveDate::from_ymd_opt(1990, 1, 1),
4018            sex: Some("F".to_string()),
4019            birth_place: Some("New York".to_string()),
4020            nationality: Some("American".to_string()),
4021            issuing_country: Some("US".to_string()),
4022            passport_number: Some("P12345678".to_string()),
4023            passport_type: Some("P".to_string()),
4024            national_identification_number: Some("123-45-6789".to_string()),
4025            issuing_authority: Some("US State Department".to_string()),
4026            issue_date: chrono::NaiveDate::from_ymd_opt(2020, 1, 1),
4027            expiration_date: chrono::NaiveDate::from_ymd_opt(2030, 1, 1),
4028        };
4029
4030        let cipher_view = CipherView {
4031            r#type: CipherType::Passport,
4032            passport: Some(passport.clone()),
4033            login: None,
4034            ..generate_cipher()
4035        };
4036
4037        let encrypted: Cipher = key_store.encrypt(EncryptMode::Legacy(cipher_view)).unwrap();
4038        let decrypted: CipherView = key_store.decrypt(&encrypted).unwrap();
4039
4040        assert_eq!(decrypted.r#type, CipherType::Passport);
4041        assert_eq!(decrypted.passport, Some(passport));
4042        assert!(decrypted.login.is_none());
4043    }
4044
4045    #[test]
4046    fn test_cipher_view_encrypt_decrypt_drivers_license() {
4047        let key_store = create_test_crypto_with_user_key(SymmetricCryptoKey::make(
4048            SymmetricKeyAlgorithm::Aes256CbcHmac,
4049        ));
4050
4051        let dl = drivers_license::DriversLicenseView {
4052            first_name: Some("John".to_string()),
4053            middle_name: Some("Michael".to_string()),
4054            last_name: Some("Doe".to_string()),
4055            date_of_birth: chrono::NaiveDate::from_ymd_opt(1985, 6, 15),
4056            license_number: Some("DL-987654".to_string()),
4057            issuing_country: Some("US".to_string()),
4058            issuing_state: Some("NY".to_string()),
4059            issue_date: chrono::NaiveDate::from_ymd_opt(2020, 1, 1),
4060            expiration_date: chrono::NaiveDate::from_ymd_opt(2028, 1, 1),
4061            issuing_authority: Some("NY DMV".to_string()),
4062            license_class: Some("D".to_string()),
4063        };
4064
4065        let cipher_view = CipherView {
4066            r#type: CipherType::DriversLicense,
4067            drivers_license: Some(dl.clone()),
4068            login: None,
4069            ..generate_cipher()
4070        };
4071
4072        let encrypted: Cipher = key_store.encrypt(EncryptMode::Legacy(cipher_view)).unwrap();
4073        let decrypted: CipherView = key_store.decrypt(&encrypted).unwrap();
4074
4075        assert_eq!(decrypted.r#type, CipherType::DriversLicense);
4076        assert_eq!(decrypted.drivers_license, Some(dl));
4077        assert!(decrypted.login.is_none());
4078    }
4079
4080    #[test]
4081    fn test_try_from_cipher_mini_response_model_login() {
4082        use bitwarden_api_api::models::CipherLoginModel;
4083        use chrono::Utc;
4084
4085        let mini_response = CipherMiniResponseModel {
4086            id: Some(TEST_UUID.parse().unwrap()),
4087            organization_id: Some(TEST_UUID.parse().unwrap()),
4088            name: Some(TEST_CIPHER_NAME.to_string()),
4089            r#type: Some(bitwarden_api_api::models::CipherType::Login),
4090            login: Some(Box::new(CipherLoginModel {
4091                username: Some(TEST_CIPHER_NAME.to_string()),
4092                ..Default::default()
4093            })),
4094            creation_date: Some(Utc::now().to_rfc3339()),
4095            revision_date: Some(Utc::now().to_rfc3339()),
4096            ..Default::default()
4097        };
4098
4099        let cipher = Cipher::try_from(mini_response).unwrap();
4100
4101        assert_eq!(cipher.id, Some(TEST_UUID.parse().unwrap()));
4102        assert_eq!(
4103            cipher.organization_id,
4104            Some(TEST_UUID.parse::<OrganizationId>().unwrap())
4105        );
4106        assert_eq!(cipher.r#type, CipherType::Login);
4107        assert_eq!(cipher.name, Some(TEST_CIPHER_NAME.parse().unwrap()));
4108        assert_eq!(
4109            cipher.login.as_ref().unwrap().username,
4110            Some(TEST_CIPHER_NAME.parse().unwrap())
4111        );
4112        assert!(cipher.view_password);
4113        assert!(cipher.key.is_none());
4114    }
4115
4116    #[test]
4117    fn test_mini_response_model_view_password_defaults_to_true() {
4118        use chrono::Utc;
4119
4120        // CipherMiniResponseModel does not include view_password from the API,
4121        // so when merge_with_cipher is called with None, it should default to true
4122        let mini_response = CipherMiniResponseModel {
4123            id: Some(TEST_UUID.parse().unwrap()),
4124            name: Some(TEST_CIPHER_NAME.to_string()),
4125            r#type: Some(bitwarden_api_api::models::CipherType::Login),
4126            creation_date: Some(Utc::now().to_rfc3339()),
4127            revision_date: Some(Utc::now().to_rfc3339()),
4128            ..Default::default()
4129        };
4130
4131        let cipher = mini_response.merge_with_cipher(None).unwrap();
4132        assert!(
4133            cipher.view_password,
4134            "view_password should default to true for CipherMiniResponseModel"
4135        );
4136
4137        // CipherMiniDetailsResponseModel should also default to true
4138        let mini_details_response = CipherMiniDetailsResponseModel {
4139            id: Some(TEST_UUID.parse().unwrap()),
4140            name: Some(TEST_CIPHER_NAME.to_string()),
4141            r#type: Some(bitwarden_api_api::models::CipherType::Login),
4142            creation_date: Some(Utc::now().to_rfc3339()),
4143            revision_date: Some(Utc::now().to_rfc3339()),
4144            ..Default::default()
4145        };
4146
4147        let cipher = mini_details_response.merge_with_cipher(None).unwrap();
4148        assert!(
4149            cipher.view_password,
4150            "view_password should default to true for CipherMiniDetailsResponseModel"
4151        );
4152    }
4153
4154    /// The shared-folder write endpoints send the IDs as `sharedFolderIds` and omit
4155    /// `collectionIds`. Both names must populate `Cipher::collection_ids`.
4156    #[test]
4157    fn test_details_response_collection_ids_accept_shared_folder_name() {
4158        use chrono::Utc;
4159
4160        let a = uuid::Uuid::new_v4();
4161        let b = uuid::Uuid::new_v4();
4162        let now = Utc::now().to_rfc3339();
4163        let ids = vec![CollectionId::new(a), CollectionId::new(b)];
4164
4165        macro_rules! assert_ids {
4166            ($model:ident) => {{
4167                let base = $model {
4168                    id: Some(TEST_UUID.parse().unwrap()),
4169                    r#type: Some(bitwarden_api_api::models::CipherType::Login),
4170                    creation_date: Some(now.clone()),
4171                    revision_date: Some(now.clone()),
4172                    ..Default::default()
4173                };
4174                let shared = $model {
4175                    shared_folder_ids: Some(vec![a, b]),
4176                    ..base.clone()
4177                };
4178                assert_eq!(
4179                    shared.merge_with_cipher(None).unwrap().collection_ids,
4180                    ids,
4181                    concat!(stringify!($model), ": sharedFolderIds")
4182                );
4183                let legacy = $model {
4184                    collection_ids: Some(vec![a, b]),
4185                    ..base.clone()
4186                };
4187                assert_eq!(
4188                    legacy.merge_with_cipher(None).unwrap().collection_ids,
4189                    ids,
4190                    concat!(stringify!($model), ": collectionIds")
4191                );
4192                // An explicit empty set from the server is respected.
4193                let empty = $model {
4194                    shared_folder_ids: Some(vec![]),
4195                    ..base
4196                };
4197                assert!(
4198                    empty
4199                        .merge_with_cipher(None)
4200                        .unwrap()
4201                        .collection_ids
4202                        .is_empty()
4203                );
4204            }};
4205        }
4206
4207        assert_ids!(CipherDetailsResponseModel);
4208        assert_ids!(CipherMiniDetailsResponseModel);
4209    }
4210
4211    /// PAM gating is authoritative from the server response: `merge_with_cipher` takes
4212    /// `partial_data` from the response, so it gates when the response carries the restricted
4213    /// envelope and un-gates when it does not — regardless of the local cipher's prior state.
4214    #[test]
4215    fn test_merge_takes_partial_data_from_response() {
4216        use chrono::Utc;
4217
4218        let org: OrganizationId = RESTRICTED_ORG_UUID.parse().unwrap();
4219        // A local cipher that is currently PAM-gated; the response's gating must win over it.
4220        let local_restricted = || {
4221            Some(restricted_cipher(
4222                org,
4223                CipherType::Login,
4224                RESTRICTED_LOGIN_ENVELOPE.to_string(),
4225            ))
4226        };
4227        let now = Utc::now().to_rfc3339();
4228
4229        macro_rules! assert_gating_from_response {
4230            ($model:ident) => {{
4231                let base = $model {
4232                    id: Some(TEST_UUID.parse().unwrap()),
4233                    organization_id: Some(org.to_string().parse().unwrap()),
4234                    r#type: Some(bitwarden_api_api::models::CipherType::Login),
4235                    creation_date: Some(now.clone()),
4236                    revision_date: Some(now.clone()),
4237                    ..Default::default()
4238                };
4239
4240                // A full response (no `partial_data`) un-gates a locally-restricted cipher.
4241                assert_eq!(
4242                    base.clone()
4243                        .merge_with_cipher(local_restricted())
4244                        .unwrap()
4245                        .partial_data,
4246                    None,
4247                    concat!(stringify!($model), ": full response must un-gate"),
4248                );
4249
4250                // A restricted response gates the row even when the local cipher was full.
4251                let restricted = $model {
4252                    partial_data: Some(RESTRICTED_LOGIN_ENVELOPE.to_string()),
4253                    ..base
4254                };
4255                assert_eq!(
4256                    restricted
4257                        .merge_with_cipher(None)
4258                        .unwrap()
4259                        .partial_data
4260                        .as_deref(),
4261                    Some(RESTRICTED_LOGIN_ENVELOPE),
4262                    concat!(stringify!($model), ": restricted response must gate"),
4263                );
4264            }};
4265        }
4266
4267        assert_gating_from_response!(CipherResponseModel);
4268        assert_gating_from_response!(CipherDetailsResponseModel);
4269        assert_gating_from_response!(CipherMiniResponseModel);
4270        assert_gating_from_response!(CipherMiniDetailsResponseModel);
4271    }
4272
4273    // ---------- Cipher Decryptable dispatch + CipherView::to_list_view ----------
4274
4275    mod cipher_decrypt_dispatch {
4276        use bitwarden_crypto::KeyStore;
4277
4278        use super::*;
4279        use crate::{
4280            BankAccountView, CardView, DriversLicenseView, IdentityView, PassportView,
4281            SecureNoteType, SecureNoteView, SshKeyView, cipher::blob::encrypt_blob_cipher,
4282        };
4283
4284        fn make_key_store() -> KeyStore<KeySlotIds> {
4285            create_test_crypto_with_user_key(SymmetricCryptoKey::make(
4286                SymmetricKeyAlgorithm::Aes256CbcHmac,
4287            ))
4288        }
4289
4290        /// Encrypt a view through the legacy field-level path.
4291        fn encrypt_legacy(view: CipherView, key_store: &KeyStore<KeySlotIds>) -> Cipher {
4292            key_store.encrypt(EncryptMode::Legacy(view)).unwrap()
4293        }
4294
4295        /// Encrypt a view through the blob path.
4296        fn encrypt_blob(mut view: CipherView, key_store: &KeyStore<KeySlotIds>) -> Cipher {
4297            let mut ctx = key_store.context_mut();
4298            encrypt_blob_cipher(&mut view, &mut ctx).unwrap()
4299        }
4300
4301        fn base_login_view() -> CipherView {
4302            let mut view = generate_cipher();
4303            view.name = "Test Login".to_string();
4304            view.login = Some(LoginView {
4305                username: Some("[email protected]".to_string()),
4306                password: Some("hunter2".to_string()),
4307                password_revision_date: None,
4308                uris: None,
4309                totp: Some("otpauth://totp/test?secret=SECRET".to_string()),
4310                autofill_on_page_load: None,
4311                http_authentication_enabled: None,
4312                fido2_credentials: None,
4313            });
4314            view
4315        }
4316
4317        /// Blob cipher → `CipherView` dispatch works end-to-end.
4318        #[test]
4319        fn dispatches_blob_to_cipher_view() {
4320            let key_store = make_key_store();
4321            let cipher = encrypt_blob(base_login_view(), &key_store);
4322
4323            let view: CipherView = key_store.decrypt(&cipher).unwrap();
4324
4325            assert_eq!(view.name, "Test Login");
4326            let login = view.login.expect("blob decrypt should restore login");
4327            assert_eq!(login.username.as_deref(), Some("[email protected]"));
4328            assert_eq!(login.password.as_deref(), Some("hunter2"));
4329        }
4330
4331        /// Legacy cipher → `CipherView` dispatch works via both default (lenient) and strict
4332        /// paths.
4333        #[test]
4334        fn dispatches_legacy_to_cipher_view() {
4335            let key_store = make_key_store();
4336
4337            // Default (lenient) path on `Cipher`.
4338            let cipher = encrypt_legacy(base_login_view(), &key_store);
4339            let view: CipherView = key_store.decrypt(&cipher).unwrap();
4340            assert_eq!(view.name, "Test Login");
4341            assert_eq!(
4342                view.login.unwrap().username.as_deref(),
4343                Some("[email protected]"),
4344            );
4345
4346            // Strict path via `StrictDecrypt<Cipher>`.
4347            let cipher = encrypt_legacy(base_login_view(), &key_store);
4348            let view: CipherView = key_store.decrypt(&StrictDecrypt(cipher)).unwrap();
4349            assert_eq!(view.name, "Test Login");
4350            assert_eq!(
4351                view.login.unwrap().username.as_deref(),
4352                Some("[email protected]"),
4353            );
4354        }
4355
4356        /// Blob ciphers of every type produce a well-formed `CipherListView`.
4357        ///
4358        /// Exercises each arm of [`CipherView::to_list_view`]: subtitle derivation,
4359        /// list-view type discriminant, and `copyable_fields`.
4360        #[test]
4361        fn blob_to_list_view_per_type() {
4362            let key_store = make_key_store();
4363
4364            // --- Login ---
4365            {
4366                let list_view = decrypt_blob_list_view(&key_store, base_login_view());
4367                assert_eq!(list_view.name, "Test Login");
4368                assert_eq!(list_view.subtitle, "[email protected]");
4369                assert!(matches!(list_view.r#type, CipherListViewType::Login(_)));
4370                assert!(
4371                    list_view
4372                        .copyable_fields
4373                        .contains(&CopyableCipherFields::LoginUsername)
4374                );
4375                assert!(
4376                    list_view
4377                        .copyable_fields
4378                        .contains(&CopyableCipherFields::LoginPassword)
4379                );
4380                assert!(
4381                    list_view
4382                        .copyable_fields
4383                        .contains(&CopyableCipherFields::LoginTotp)
4384                );
4385            }
4386
4387            // --- Card ---
4388            {
4389                let mut view = generate_cipher();
4390                view.r#type = CipherType::Card;
4391                view.login = None;
4392                view.name = "My Card".to_string();
4393                view.card = Some(CardView {
4394                    cardholder_name: Some("John Doe".to_string()),
4395                    exp_month: Some("12".to_string()),
4396                    exp_year: Some("2030".to_string()),
4397                    code: Some("123".to_string()),
4398                    brand: Some("Visa".to_string()),
4399                    number: Some("4111111111111111".to_string()),
4400                });
4401                let list_view = decrypt_blob_list_view(&key_store, view);
4402                assert_eq!(list_view.name, "My Card");
4403                assert!(list_view.subtitle.contains("Visa"));
4404                assert!(list_view.subtitle.contains("1111"));
4405                match &list_view.r#type {
4406                    CipherListViewType::Card(card) => {
4407                        assert_eq!(card.brand.as_deref(), Some("Visa"))
4408                    }
4409                    other => panic!("expected Card, got {other:?}"),
4410                }
4411                assert!(
4412                    list_view
4413                        .copyable_fields
4414                        .contains(&CopyableCipherFields::CardNumber)
4415                );
4416                assert!(
4417                    list_view
4418                        .copyable_fields
4419                        .contains(&CopyableCipherFields::CardSecurityCode)
4420                );
4421            }
4422
4423            // --- Identity ---
4424            {
4425                let mut view = generate_cipher();
4426                view.r#type = CipherType::Identity;
4427                view.login = None;
4428                view.name = "My Identity".to_string();
4429                view.identity = Some(IdentityView {
4430                    title: None,
4431                    first_name: Some("Jane".to_string()),
4432                    middle_name: None,
4433                    last_name: Some("Doe".to_string()),
4434                    address1: Some("123 Main St".to_string()),
4435                    address2: None,
4436                    address3: None,
4437                    city: None,
4438                    state: None,
4439                    postal_code: None,
4440                    country: None,
4441                    company: None,
4442                    email: Some("[email protected]".to_string()),
4443                    phone: None,
4444                    ssn: None,
4445                    username: None,
4446                    passport_number: None,
4447                    license_number: None,
4448                });
4449                let list_view = decrypt_blob_list_view(&key_store, view);
4450                assert_eq!(list_view.name, "My Identity");
4451                assert!(list_view.subtitle.contains("Jane"));
4452                assert!(list_view.subtitle.contains("Doe"));
4453                assert!(matches!(list_view.r#type, CipherListViewType::Identity));
4454                assert!(
4455                    list_view
4456                        .copyable_fields
4457                        .contains(&CopyableCipherFields::IdentityEmail)
4458                );
4459                assert!(
4460                    list_view
4461                        .copyable_fields
4462                        .contains(&CopyableCipherFields::IdentityAddress)
4463                );
4464            }
4465
4466            // --- SecureNote ---
4467            {
4468                let mut view = generate_cipher();
4469                view.r#type = CipherType::SecureNote;
4470                view.login = None;
4471                view.name = "My Note".to_string();
4472                view.notes = Some("secret".to_string());
4473                view.secure_note = Some(SecureNoteView {
4474                    r#type: SecureNoteType::Generic,
4475                });
4476                let list_view = decrypt_blob_list_view(&key_store, view);
4477                assert_eq!(list_view.name, "My Note");
4478                assert_eq!(list_view.subtitle, "");
4479                assert!(matches!(list_view.r#type, CipherListViewType::SecureNote));
4480                assert!(
4481                    list_view
4482                        .copyable_fields
4483                        .contains(&CopyableCipherFields::SecureNotes)
4484                );
4485            }
4486
4487            // --- SshKey ---
4488            {
4489                let mut view = generate_cipher();
4490                view.r#type = CipherType::SshKey;
4491                view.login = None;
4492                view.name = "My SSH".to_string();
4493                view.ssh_key = Some(SshKeyView {
4494                    private_key: "-----BEGIN PRIVATE KEY-----".to_string(),
4495                    public_key: "ssh-ed25519 AAAA".to_string(),
4496                    fingerprint: "SHA256:abcdef".to_string(),
4497                });
4498                let list_view = decrypt_blob_list_view(&key_store, view);
4499                assert_eq!(list_view.name, "My SSH");
4500                assert_eq!(list_view.subtitle, "SHA256:abcdef");
4501                assert!(matches!(list_view.r#type, CipherListViewType::SshKey));
4502                assert!(
4503                    list_view
4504                        .copyable_fields
4505                        .contains(&CopyableCipherFields::SshKey)
4506                );
4507            }
4508
4509            // --- BankAccount ---
4510            {
4511                let mut view = generate_cipher();
4512                view.r#type = CipherType::BankAccount;
4513                view.login = None;
4514                view.name = "My Bank Account".to_string();
4515                view.bank_account = Some(BankAccountView {
4516                    bank_name: Some("Some Bank".to_string()),
4517                    name_on_account: Some("Jane Doe".to_string()),
4518                    account_number: Some("123456".to_string()),
4519                    routing_number: Some("111000025".to_string()),
4520                    branch_number: Some("001".to_string()),
4521                    pin: Some("4321".to_string()),
4522                    swift_code: Some("ABCDEF12".to_string()),
4523                    iban: Some("DE89370400440532013000".to_string()),
4524                    ..Default::default()
4525                });
4526                let list_view = decrypt_blob_list_view(&key_store, view);
4527                assert_eq!(list_view.name, "My Bank Account");
4528                assert_eq!(list_view.subtitle, "Some Bank");
4529                assert_eq!(
4530                    list_view.r#type,
4531                    CipherListViewType::BankAccount(BankAccountListView {
4532                        account_number: Some("123456".to_string()),
4533                        account_type: None,
4534                    })
4535                );
4536                assert_eq!(
4537                    list_view.copyable_fields,
4538                    vec![
4539                        CopyableCipherFields::BankAccountNameOnAccount,
4540                        CopyableCipherFields::BankAccountAccountNumber,
4541                        CopyableCipherFields::BankAccountRoutingNumber,
4542                        CopyableCipherFields::BankAccountBranchNumber,
4543                        CopyableCipherFields::BankAccountPin,
4544                        CopyableCipherFields::BankAccountIban,
4545                        CopyableCipherFields::BankAccountSwift,
4546                    ]
4547                );
4548            }
4549        }
4550
4551        /// A fully-populated `CipherView` for every [`CipherType`], so that every
4552        /// presence-gated `copyable_fields` branch fires.
4553        ///
4554        /// Every optional field that influences `copyable_fields` is set; a new copyable
4555        /// field added to one decryption path but not the other will change one path's
4556        /// output and trip [`copyable_fields_parity_between_legacy_and_blob`].
4557        fn fully_populated_views() -> Vec<(&'static str, CipherView)> {
4558            let with_type = |r#type: CipherType, f: &dyn Fn(&mut CipherView)| {
4559                let mut view = generate_cipher();
4560                view.r#type = r#type;
4561                view.login = None;
4562                f(&mut view);
4563                view
4564            };
4565
4566            vec![
4567                ("Login", base_login_view()),
4568                (
4569                    "Card",
4570                    with_type(CipherType::Card, &|v| {
4571                        v.card = Some(CardView {
4572                            cardholder_name: Some("Jane Doe".to_string()),
4573                            exp_month: Some("12".to_string()),
4574                            exp_year: Some("2030".to_string()),
4575                            code: Some("123".to_string()),
4576                            brand: Some("Visa".to_string()),
4577                            number: Some("4111111111111111".to_string()),
4578                        });
4579                    }),
4580                ),
4581                (
4582                    "Identity",
4583                    with_type(CipherType::Identity, &|v| {
4584                        v.identity = Some(IdentityView {
4585                            title: Some("Mx".to_string()),
4586                            first_name: Some("Jane".to_string()),
4587                            middle_name: Some("Q".to_string()),
4588                            last_name: Some("Doe".to_string()),
4589                            address1: Some("1 Main St".to_string()),
4590                            address2: Some("Apt 2".to_string()),
4591                            address3: Some("Floor 3".to_string()),
4592                            city: Some("Anytown".to_string()),
4593                            state: Some("CA".to_string()),
4594                            postal_code: Some("90210".to_string()),
4595                            country: Some("US".to_string()),
4596                            company: Some("Acme".to_string()),
4597                            email: Some("[email protected]".to_string()),
4598                            phone: Some("555-0100".to_string()),
4599                            ssn: Some("000-00-0000".to_string()),
4600                            username: Some("jane".to_string()),
4601                            passport_number: Some("X1234567".to_string()),
4602                            license_number: Some("D1234567".to_string()),
4603                        });
4604                    }),
4605                ),
4606                (
4607                    "SecureNote",
4608                    with_type(CipherType::SecureNote, &|v| {
4609                        v.notes = Some("a secret note".to_string());
4610                        v.secure_note = Some(SecureNoteView {
4611                            r#type: SecureNoteType::Generic,
4612                        });
4613                    }),
4614                ),
4615                (
4616                    "SshKey",
4617                    with_type(CipherType::SshKey, &|v| {
4618                        v.ssh_key = Some(SshKeyView {
4619                            private_key: "private".to_string(),
4620                            public_key: "public".to_string(),
4621                            fingerprint: "SHA256:abc".to_string(),
4622                        });
4623                    }),
4624                ),
4625                (
4626                    "BankAccount",
4627                    with_type(CipherType::BankAccount, &|v| {
4628                        v.bank_account = Some(BankAccountView {
4629                            bank_name: Some("Some Bank".to_string()),
4630                            name_on_account: Some("Jane Doe".to_string()),
4631                            account_type: Some("Checking".to_string()),
4632                            account_number: Some("123456".to_string()),
4633                            routing_number: Some("111000025".to_string()),
4634                            branch_number: Some("001".to_string()),
4635                            pin: Some("4321".to_string()),
4636                            swift_code: Some("ABCDEF12".to_string()),
4637                            iban: Some("DE89370400440532013000".to_string()),
4638                            bank_contact_phone: Some("555-0199".to_string()),
4639                        });
4640                    }),
4641                ),
4642                (
4643                    "DriversLicense",
4644                    with_type(CipherType::DriversLicense, &|v| {
4645                        v.drivers_license = Some(DriversLicenseView {
4646                            first_name: Some("Jane".to_string()),
4647                            middle_name: Some("Q".to_string()),
4648                            last_name: Some("Doe".to_string()),
4649                            date_of_birth: chrono::NaiveDate::from_ymd_opt(1990, 1, 1),
4650                            license_number: Some("D1234567".to_string()),
4651                            issuing_country: Some("US".to_string()),
4652                            issuing_state: Some("CA".to_string()),
4653                            issue_date: chrono::NaiveDate::from_ymd_opt(2020, 1, 1),
4654                            expiration_date: chrono::NaiveDate::from_ymd_opt(2030, 1, 1),
4655                            issuing_authority: Some("DMV".to_string()),
4656                            license_class: Some("C".to_string()),
4657                        });
4658                    }),
4659                ),
4660                (
4661                    "Passport",
4662                    with_type(CipherType::Passport, &|v| {
4663                        v.passport = Some(PassportView {
4664                            surname: Some("Doe".to_string()),
4665                            given_name: Some("Jane".to_string()),
4666                            date_of_birth: chrono::NaiveDate::from_ymd_opt(1990, 1, 1),
4667                            sex: Some("F".to_string()),
4668                            birth_place: Some("Anytown".to_string()),
4669                            nationality: Some("US".to_string()),
4670                            issuing_country: Some("US".to_string()),
4671                            passport_number: Some("X1234567".to_string()),
4672                            passport_type: Some("P".to_string()),
4673                            national_identification_number: Some("000-00-0000".to_string()),
4674                            issuing_authority: Some("State Dept".to_string()),
4675                            issue_date: chrono::NaiveDate::from_ymd_opt(2020, 1, 1),
4676                            expiration_date: chrono::NaiveDate::from_ymd_opt(2030, 1, 1),
4677                        });
4678                    }),
4679                ),
4680            ]
4681        }
4682
4683        /// The legacy field-level path and the blob path independently derive
4684        /// `copyable_fields` — legacy from `Option<EncString>` presence on the encrypted
4685        /// kind, blob from `Option<String>` presence on the decrypted view. They must
4686        /// agree for identical input, or the same cipher renders differently depending on
4687        /// its storage format. This guards every type against drift without hardcoding the
4688        /// expected set per type.
4689        #[test]
4690        fn copyable_fields_parity_between_legacy_and_blob() {
4691            let key_store = make_key_store();
4692
4693            for (label, view) in fully_populated_views() {
4694                let legacy: CipherListView = key_store
4695                    .decrypt(&encrypt_legacy(view.clone(), &key_store))
4696                    .unwrap();
4697                let blob = decrypt_blob_list_view(&key_store, view);
4698
4699                assert_eq!(
4700                    legacy.copyable_fields, blob.copyable_fields,
4701                    "copyable_fields diverged between legacy and blob paths for {label}",
4702                );
4703            }
4704        }
4705
4706        /// Blob path unseals plaintext TOTP; the projection re-encrypts it under the
4707        /// cipher key so [`CipherListView::get_totp_key`] (which decrypts on demand)
4708        /// still returns the original plaintext.
4709        #[test]
4710        fn login_list_view_preserves_totp_round_trip() {
4711            let key_store = make_key_store();
4712            let list_view = decrypt_blob_list_view(&key_store, base_login_view());
4713
4714            match &list_view.r#type {
4715                CipherListViewType::Login(login) => assert!(login.totp.is_some()),
4716                other => panic!("expected Login, got {other:?}"),
4717            }
4718            let totp = list_view.get_totp_key().unwrap();
4719            assert_eq!(totp.as_deref(), Some("otpauth://totp/test?secret=SECRET"));
4720        }
4721
4722        /// `decrypt_list` handles a slice containing both blob and legacy ciphers
4723        #[test]
4724        fn mixed_batch_decrypt_list() {
4725            let key_store = make_key_store();
4726            let blob = encrypt_blob(base_login_view(), &key_store);
4727            let legacy = encrypt_legacy(base_login_view(), &key_store);
4728
4729            let ciphers = vec![blob, legacy];
4730            let views: Vec<CipherListView> = key_store.decrypt_list(&ciphers).unwrap();
4731
4732            assert_eq!(views.len(), 2);
4733            for v in &views {
4734                assert_eq!(v.name, "Test Login");
4735                assert_eq!(v.subtitle, "[email protected]");
4736            }
4737        }
4738
4739        fn decrypt_blob_list_view(
4740            key_store: &KeyStore<KeySlotIds>,
4741            view: CipherView,
4742        ) -> CipherListView {
4743            let cipher = encrypt_blob(view, key_store);
4744            key_store.decrypt(&cipher).unwrap()
4745        }
4746
4747        /// Three attachments whose `EncString`s are sealed under an unrelated
4748        /// key, so they fail to decrypt under any cipher key. The middle one has
4749        /// no wrapped key, marking it an "old" (v1) attachment.
4750        fn failing_attachments() -> Vec<attachment::Attachment> {
4751            let wrong = create_test_crypto_with_user_key(SymmetricCryptoKey::make(
4752                SymmetricKeyAlgorithm::Aes256CbcHmac,
4753            ));
4754            let mut ctx = wrong.context();
4755            let mut enc = |s: &str| s.encrypt(&mut ctx, SymmetricKeySlotId::User).unwrap();
4756            vec![
4757                attachment::Attachment {
4758                    id: Some("a1".to_string()),
4759                    url: None,
4760                    size: None,
4761                    size_name: None,
4762                    file_name: Some(enc("a1.txt")),
4763                    key: Some(enc("k1")),
4764                },
4765                attachment::Attachment {
4766                    id: Some("a2-old".to_string()),
4767                    url: None,
4768                    size: None,
4769                    size_name: None,
4770                    file_name: Some(enc("a2.txt")),
4771                    key: None,
4772                },
4773                attachment::Attachment {
4774                    id: Some("a3".to_string()),
4775                    url: None,
4776                    size: None,
4777                    size_name: None,
4778                    file_name: Some(enc("a3.txt")),
4779                    key: Some(enc("k3")),
4780                },
4781            ]
4782        }
4783
4784        /// Attachment metrics must agree across paths even when attachments fail
4785        /// to decrypt. The legacy path counts the encrypted server model directly;
4786        /// the blob path routes failures into `attachment_decryption_failures`, so
4787        /// the projection must count those too — otherwise a corrupt attachment
4788        /// makes the same cipher report a different `attachments` count and
4789        /// `has_old_attachments` flag depending on its storage format.
4790        #[test]
4791        fn attachment_metrics_parity_with_failing_attachments() {
4792            let key_store = make_key_store();
4793
4794            let mut legacy = encrypt_legacy(base_login_view(), &key_store);
4795            legacy.attachments = Some(failing_attachments());
4796            let legacy_list: CipherListView = key_store.decrypt(&legacy).unwrap();
4797
4798            let mut blob = encrypt_blob(base_login_view(), &key_store);
4799            blob.attachments = Some(failing_attachments());
4800            let blob_list: CipherListView = key_store.decrypt(&blob).unwrap();
4801
4802            assert_eq!(legacy_list.attachments, 3);
4803            assert!(legacy_list.has_old_attachments);
4804            assert_eq!(blob_list.attachments, legacy_list.attachments);
4805            assert_eq!(
4806                blob_list.has_old_attachments,
4807                legacy_list.has_old_attachments,
4808            );
4809        }
4810    }
4811
4812    // ---------- EncryptMode ----------
4813
4814    mod encrypt_mode {
4815        use bitwarden_crypto::{IdentifyKey, KeyStore};
4816
4817        use super::*;
4818
4819        fn make_key_store() -> KeyStore<KeySlotIds> {
4820            create_test_crypto_with_user_key(SymmetricCryptoKey::make(
4821                SymmetricKeyAlgorithm::Aes256CbcHmac,
4822            ))
4823        }
4824
4825        fn base_login_view() -> CipherView {
4826            let mut view = generate_cipher();
4827            view.name = "Round Trip".to_string();
4828            view.login = Some(LoginView {
4829                username: Some("[email protected]".to_string()),
4830                password: Some("hunter2".to_string()),
4831                password_revision_date: None,
4832                uris: None,
4833                totp: None,
4834                autofill_on_page_load: None,
4835                http_authentication_enabled: None,
4836                fido2_credentials: None,
4837            });
4838            view
4839        }
4840
4841        /// Blob variant produces a blob-shaped cipher: sealed `data`, placeholder
4842        /// `name`, and every per-type sensitive field cleared.
4843        #[test]
4844        fn blob_variant_produces_blob_shaped_cipher() {
4845            let key_store = make_key_store();
4846            let mode = EncryptMode::Blob(base_login_view());
4847
4848            let cipher: Cipher = key_store.encrypt(mode).unwrap();
4849
4850            assert!(try_parse_blob(&cipher).is_some());
4851            assert!(cipher.data.is_some());
4852            assert!(cipher.login.is_none());
4853            assert!(cipher.card.is_none());
4854            assert!(cipher.identity.is_none());
4855            assert!(cipher.secure_note.is_none());
4856            assert!(cipher.ssh_key.is_none());
4857            assert!(cipher.bank_account.is_none());
4858            assert!(cipher.fields.is_none());
4859            assert!(cipher.password_history.is_none());
4860            assert!(cipher.notes.is_none());
4861        }
4862
4863        /// Legacy variant produces a legacy-shaped cipher: `data` empty, and the
4864        /// matching per-type field populated.
4865        #[test]
4866        fn legacy_variant_produces_legacy_shaped_cipher() {
4867            let key_store = make_key_store();
4868            let mode = EncryptMode::Legacy(base_login_view());
4869
4870            let cipher: Cipher = key_store.encrypt(mode).unwrap();
4871
4872            assert!(try_parse_blob(&cipher).is_none());
4873            assert!(cipher.data.is_none());
4874            assert!(cipher.login.is_some());
4875            assert!(
4876                cipher.key.is_some(),
4877                "legacy encrypt must always emit a cipher key"
4878            );
4879        }
4880
4881        /// Legacy encryption must wrap the generated cipher key under the wrapping key it is
4882        /// handed, not the view's own `User`/`Organization` slot — key rotation passes a `Local`
4883        /// slot holding the new user key.
4884        #[test]
4885        fn legacy_variant_wraps_cipher_key_under_explicit_key() {
4886            let key_store = make_key_store();
4887            let view = base_login_view();
4888            let mut ctx = key_store.context();
4889
4890            let new_key = ctx.add_local_symmetric_key(SymmetricCryptoKey::make(
4891                SymmetricKeyAlgorithm::Aes256CbcHmac,
4892            ));
4893            let cipher = EncryptMode::Legacy(view.clone())
4894                .encrypt_composite(&mut ctx, new_key)
4895                .unwrap();
4896
4897            // The cipher key unwraps under the explicitly supplied key, and the data it protects
4898            // round-trips.
4899            let decrypted = lenient_decrypt_cipher_view(&cipher, &mut ctx, new_key).unwrap();
4900            assert_eq!(decrypted.name, view.name);
4901            assert_eq!(
4902                decrypted.login.as_ref().unwrap().password,
4903                view.login.as_ref().unwrap().password
4904            );
4905
4906            // It does not unwrap under the view's natural slot.
4907            assert!(
4908                lenient_decrypt_cipher_view(&cipher, &mut ctx, view.key_identifier()).is_err(),
4909                "cipher key must not be wrapped under the view's own slot"
4910            );
4911        }
4912
4913        /// An already-keyed view keeps its cipher key through encryption.
4914        #[test]
4915        fn legacy_variant_preserves_existing_cipher_key() {
4916            let key_store = make_key_store();
4917            let mut view = base_login_view();
4918            let mut ctx = key_store.context();
4919
4920            let _ = view.load_cipher_key_slot(&mut ctx).unwrap();
4921            let original_key = view
4922                .key
4923                .clone()
4924                .expect("load_cipher_key_slot stores the key");
4925
4926            let wrapping_key = ctx.add_local_symmetric_key(SymmetricCryptoKey::make(
4927                SymmetricKeyAlgorithm::Aes256CbcHmac,
4928            ));
4929            let cipher = EncryptMode::Legacy(view)
4930                .encrypt_composite(&mut ctx, wrapping_key)
4931                .unwrap();
4932
4933            let unwrapped = ctx
4934                .unwrap_symmetric_key(wrapping_key, &cipher.key.expect("cipher key is emitted"))
4935                .unwrap();
4936            #[allow(deprecated)]
4937            let unwrapped_raw = ctx.dangerous_get_symmetric_key(unwrapped).unwrap().clone();
4938
4939            assert_eq!(
4940                unwrapped_raw, original_key,
4941                "encryption must wrap the view's existing cipher key, not a new one"
4942            );
4943        }
4944
4945        /// Blob variant round-trips through decryption
4946        #[test]
4947        fn blob_variant_round_trips_through_decrypt() {
4948            let key_store = make_key_store();
4949            let original = base_login_view();
4950            let mode = EncryptMode::Blob(original.clone());
4951
4952            let cipher: Cipher = key_store.encrypt(mode).unwrap();
4953            let restored: CipherView = key_store.decrypt(&cipher).unwrap();
4954
4955            assert_eq!(restored.name, original.name);
4956            let login = restored.login.expect("round-trip should restore login");
4957            assert_eq!(login.username, original.login.as_ref().unwrap().username);
4958            assert_eq!(login.password, original.login.as_ref().unwrap().password);
4959        }
4960
4961        fn with_http_authentication(enabled: Option<bool>) -> CipherView {
4962            let mut view = base_login_view();
4963            if let Some(login) = view.login.as_mut() {
4964                login.http_authentication_enabled = enabled;
4965            }
4966            view
4967        }
4968
4969        /// The HTTP authentication setting is sealed in the blob and restored on decryption.
4970        #[test]
4971        fn blob_variant_round_trips_http_authentication_enabled() {
4972            let key_store = make_key_store();
4973
4974            let cipher: Cipher = key_store
4975                .encrypt(EncryptMode::Blob(with_http_authentication(Some(true))))
4976                .unwrap();
4977            let restored: CipherView = key_store.decrypt(&cipher).unwrap();
4978
4979            assert_eq!(
4980                restored.login.unwrap().http_authentication_enabled,
4981                Some(true)
4982            );
4983        }
4984
4985        /// A login without the HTTP authentication setting is stored with it turned off.
4986        #[test]
4987        fn blob_variant_stores_missing_http_authentication_enabled_as_off() {
4988            let key_store = make_key_store();
4989
4990            let cipher: Cipher = key_store
4991                .encrypt(EncryptMode::Blob(with_http_authentication(None)))
4992                .unwrap();
4993            let restored: CipherView = key_store.decrypt(&cipher).unwrap();
4994
4995            assert_eq!(
4996                restored.login.unwrap().http_authentication_enabled,
4997                Some(false)
4998            );
4999        }
5000
5001        /// The legacy field-level format stores the HTTP authentication setting unencrypted on the
5002        /// login, and both the lenient and strict decryption paths restore it.
5003        #[test]
5004        fn legacy_variant_round_trips_http_authentication_enabled() {
5005            let key_store = make_key_store();
5006
5007            let cipher: Cipher = key_store
5008                .encrypt(EncryptMode::Legacy(with_http_authentication(Some(true))))
5009                .unwrap();
5010
5011            assert_eq!(
5012                cipher.login.as_ref().unwrap().http_authentication_enabled,
5013                Some(true)
5014            );
5015
5016            let lenient: CipherView = key_store.decrypt(&cipher).unwrap();
5017            assert_eq!(
5018                lenient.login.unwrap().http_authentication_enabled,
5019                Some(true)
5020            );
5021
5022            let strict: CipherView = key_store.decrypt(&StrictDecrypt(cipher)).unwrap();
5023            assert_eq!(
5024                strict.login.unwrap().http_authentication_enabled,
5025                Some(true)
5026            );
5027        }
5028
5029        /// The legacy format keeps an unset HTTP authentication setting unset, unlike the blob.
5030        #[test]
5031        fn legacy_variant_keeps_missing_http_authentication_enabled_unset() {
5032            let key_store = make_key_store();
5033
5034            let cipher: Cipher = key_store
5035                .encrypt(EncryptMode::Legacy(with_http_authentication(None)))
5036                .unwrap();
5037            let restored: CipherView = key_store.decrypt(&cipher).unwrap();
5038
5039            assert_eq!(restored.login.unwrap().http_authentication_enabled, None);
5040        }
5041
5042        /// A legacy cipher re-encrypted in the blob format carries its HTTP authentication setting
5043        /// into the blob, through the decrypted view.
5044        #[test]
5045        fn legacy_http_authentication_enabled_survives_conversion_to_blob() {
5046            let key_store = make_key_store();
5047
5048            let legacy_cipher: Cipher = key_store
5049                .encrypt(EncryptMode::Legacy(with_http_authentication(Some(true))))
5050                .unwrap();
5051            let legacy_view: CipherView = key_store.decrypt(&legacy_cipher).unwrap();
5052
5053            let blob_cipher: Cipher = key_store.encrypt(EncryptMode::Blob(legacy_view)).unwrap();
5054            assert!(try_parse_blob(&blob_cipher).is_some());
5055            assert!(blob_cipher.login.is_none());
5056
5057            let restored: CipherView = key_store.decrypt(&blob_cipher).unwrap();
5058            assert_eq!(
5059                restored.login.unwrap().http_authentication_enabled,
5060                Some(true)
5061            );
5062        }
5063
5064        /// `key_identifier` must delegate to the inner view so `encrypt_list`
5065        /// selects the correct scope key.
5066        #[test]
5067        fn key_identifier_delegates_to_inner_view() {
5068            let view = base_login_view();
5069            let expected = view.key_identifier();
5070            let mode = EncryptMode::Blob(view);
5071            assert_eq!(mode.key_identifier(), expected);
5072        }
5073
5074        /// A mixed-batch `encrypt_list` preserves input order and produces a
5075        /// cipher shaped per-variant.
5076        #[test]
5077        fn mixed_batch_encrypt_list_preserves_per_item_shape() {
5078            let key_store = make_key_store();
5079            let mut legacy_view = base_login_view();
5080            legacy_view.name = "Legacy".to_string();
5081            let mut blob_view = base_login_view();
5082            blob_view.name = "Blob".to_string();
5083
5084            let modes = vec![
5085                EncryptMode::Legacy(legacy_view),
5086                EncryptMode::Blob(blob_view),
5087            ];
5088            let ciphers: Vec<Cipher> = key_store.encrypt_list(&modes).unwrap();
5089
5090            assert_eq!(ciphers.len(), 2);
5091            assert!(
5092                try_parse_blob(&ciphers[0]).is_none(),
5093                "first item should be legacy"
5094            );
5095            assert!(
5096                try_parse_blob(&ciphers[1]).is_some(),
5097                "second item should be blob"
5098            );
5099            assert!(ciphers[0].login.is_some());
5100            assert!(ciphers[1].login.is_none());
5101        }
5102    }
5103}