Skip to main content

bitwarden_vault/cipher/
login.rs

1use bitwarden_api_api::models::{CipherLoginModel, CipherLoginUriModel};
2use bitwarden_core::{
3    key_management::{KeySlotIds, SymmetricKeySlotId},
4    require,
5};
6use bitwarden_crypto::{
7    CompositeEncryptable, CryptoError, Decryptable, EncString, KeyStoreContext,
8    PrimitiveEncryptable,
9};
10use bitwarden_encoding::B64;
11use chrono::{DateTime, Utc};
12use serde::{Deserialize, Serialize};
13use serde_repr::{Deserialize_repr, Serialize_repr};
14use subtle::ConstantTimeEq;
15
16use super::cipher::{CipherKind, StrictDecrypt};
17use crate::{Cipher, PasswordHistoryView, VaultParseError, cipher::cipher::CopyableCipherFields};
18
19#[allow(missing_docs)]
20#[derive(Clone, Copy, Serialize_repr, Deserialize_repr, Debug, PartialEq)]
21#[repr(u8)]
22#[serde(rename_all = "camelCase", deny_unknown_fields)]
23#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
24#[bitwarden_ffi::wasm_object]
25pub enum UriMatchType {
26    Domain = 0,
27    Host = 1,
28    StartsWith = 2,
29    Exact = 3,
30    RegularExpression = 4,
31    Never = 5,
32}
33
34#[serde_with::skip_serializing_none]
35#[derive(Serialize, Deserialize, Debug, Clone)]
36#[serde(rename_all = "camelCase", deny_unknown_fields)]
37#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
38#[bitwarden_ffi::wasm_record]
39pub struct LoginUri {
40    pub uri: Option<EncString>,
41    pub r#match: Option<UriMatchType>,
42    pub uri_checksum: Option<EncString>,
43}
44
45#[serde_with::skip_serializing_none]
46#[allow(missing_docs)]
47#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
48#[serde(rename_all = "camelCase", deny_unknown_fields)]
49#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
50#[bitwarden_ffi::wasm_record]
51pub struct LoginUriView {
52    pub uri: Option<String>,
53    pub r#match: Option<UriMatchType>,
54    pub uri_checksum: Option<String>,
55}
56
57impl LoginUriView {
58    pub(crate) fn is_checksum_valid(&self) -> bool {
59        let Some(uri) = &self.uri else {
60            return false;
61        };
62        let Some(cs) = &self.uri_checksum else {
63            return false;
64        };
65        let Ok(cs) = B64::try_from(cs.as_str()) else {
66            return false;
67        };
68
69        use sha2::Digest;
70        let uri_hash = sha2::Sha256::new().chain_update(uri.as_bytes()).finalize();
71
72        uri_hash.as_slice().ct_eq(cs.as_bytes()).into()
73    }
74
75    pub(crate) fn generate_checksum(&mut self) {
76        if let Some(uri) = &self.uri {
77            use sha2::Digest;
78            let uri_hash = sha2::Sha256::new().chain_update(uri.as_bytes()).finalize();
79            let uri_hash = B64::from(uri_hash.as_slice()).to_string();
80            self.uri_checksum = Some(uri_hash);
81        }
82    }
83}
84
85#[serde_with::skip_serializing_none]
86#[allow(missing_docs)]
87#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
88#[serde(rename_all = "camelCase", deny_unknown_fields)]
89#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
90#[bitwarden_ffi::wasm_record]
91pub struct Fido2Credential {
92    pub credential_id: EncString,
93    pub key_type: EncString,
94    pub key_algorithm: EncString,
95    pub key_curve: EncString,
96    pub key_value: EncString,
97    pub rp_id: EncString,
98    pub user_handle: Option<EncString>,
99    pub user_name: Option<EncString>,
100    pub counter: EncString,
101    pub rp_name: Option<EncString>,
102    pub user_display_name: Option<EncString>,
103    pub discoverable: EncString,
104    pub creation_date: DateTime<Utc>,
105}
106
107#[serde_with::skip_serializing_none]
108#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
109#[serde(rename_all = "camelCase", deny_unknown_fields)]
110#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
111#[bitwarden_ffi::wasm_record]
112pub struct Fido2CredentialListView {
113    pub credential_id: String,
114    pub rp_id: String,
115    pub user_handle: Option<String>,
116    pub user_name: Option<String>,
117    pub user_display_name: Option<String>,
118    pub counter: String,
119}
120
121#[serde_with::skip_serializing_none]
122#[allow(missing_docs)]
123#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
124#[serde(rename_all = "camelCase", deny_unknown_fields)]
125#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
126#[bitwarden_ffi::wasm_record]
127pub struct Fido2CredentialView {
128    pub credential_id: String,
129    pub key_type: String,
130    pub key_algorithm: String,
131    pub key_curve: String,
132    /// The raw private key material for this passkey credential.
133    /// Callers that receive `Fido2CredentialView` over a binding boundary should
134    /// treat this field with the same care as any private key material.
135    pub key_value: String,
136    pub rp_id: String,
137    pub user_handle: Option<String>,
138    pub user_name: Option<String>,
139    pub counter: String,
140    pub rp_name: Option<String>,
141    pub user_display_name: Option<String>,
142    pub discoverable: String,
143    pub creation_date: DateTime<Utc>,
144}
145
146// This is mostly a copy of the Fido2CredentialView, but with the key exposed
147// Only meant to be used internally and not exposed to the outside world
148#[serde_with::skip_serializing_none]
149#[allow(missing_docs)]
150#[derive(Serialize, Deserialize, Debug, Clone)]
151#[serde(rename_all = "camelCase", deny_unknown_fields)]
152#[bitwarden_ffi::wasm_record]
153pub struct Fido2CredentialFullView {
154    pub credential_id: String,
155    pub key_type: String,
156    pub key_algorithm: String,
157    pub key_curve: String,
158    pub key_value: String,
159    pub rp_id: String,
160    pub user_handle: Option<String>,
161    pub user_name: Option<String>,
162    pub counter: String,
163    pub rp_name: Option<String>,
164    pub user_display_name: Option<String>,
165    pub discoverable: String,
166    pub creation_date: DateTime<Utc>,
167}
168
169// This is mostly a copy of the Fido2CredentialView, meant to be exposed to the clients
170// to let them select where to store the new credential. Note that it doesn't contain
171// the encrypted key as that is only filled when the cipher is selected
172#[serde_with::skip_serializing_none]
173#[allow(missing_docs)]
174#[derive(Serialize, Deserialize, Debug, Clone)]
175#[serde(rename_all = "camelCase", deny_unknown_fields)]
176#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
177#[bitwarden_ffi::wasm_record]
178pub struct Fido2CredentialNewView {
179    pub credential_id: String,
180    pub key_type: String,
181    pub key_algorithm: String,
182    pub key_curve: String,
183    pub rp_id: String,
184    pub user_handle: Option<String>,
185    pub user_name: Option<String>,
186    pub counter: String,
187    pub rp_name: Option<String>,
188    pub user_display_name: Option<String>,
189    pub creation_date: DateTime<Utc>,
190}
191
192impl From<Fido2CredentialFullView> for Fido2CredentialNewView {
193    fn from(value: Fido2CredentialFullView) -> Self {
194        Fido2CredentialNewView {
195            credential_id: value.credential_id,
196            key_type: value.key_type,
197            key_algorithm: value.key_algorithm,
198            key_curve: value.key_curve,
199            rp_id: value.rp_id,
200            user_handle: value.user_handle,
201            user_name: value.user_name,
202            counter: value.counter,
203            rp_name: value.rp_name,
204            user_display_name: value.user_display_name,
205            creation_date: value.creation_date,
206        }
207    }
208}
209
210impl CompositeEncryptable<KeySlotIds, SymmetricKeySlotId, Fido2Credential>
211    for Fido2CredentialFullView
212{
213    fn encrypt_composite(
214        &self,
215        ctx: &mut KeyStoreContext<KeySlotIds>,
216        key: SymmetricKeySlotId,
217    ) -> Result<Fido2Credential, CryptoError> {
218        Ok(Fido2Credential {
219            credential_id: self.credential_id.encrypt(ctx, key)?,
220            key_type: self.key_type.encrypt(ctx, key)?,
221            key_algorithm: self.key_algorithm.encrypt(ctx, key)?,
222            key_curve: self.key_curve.encrypt(ctx, key)?,
223            key_value: self.key_value.encrypt(ctx, key)?,
224            rp_id: self.rp_id.encrypt(ctx, key)?,
225            user_handle: self
226                .user_handle
227                .as_ref()
228                .map(|h| h.encrypt(ctx, key))
229                .transpose()?,
230            user_name: self.user_name.encrypt(ctx, key)?,
231            counter: self.counter.encrypt(ctx, key)?,
232            rp_name: self.rp_name.encrypt(ctx, key)?,
233            user_display_name: self.user_display_name.encrypt(ctx, key)?,
234            discoverable: self.discoverable.encrypt(ctx, key)?,
235            creation_date: self.creation_date,
236        })
237    }
238}
239
240impl Decryptable<KeySlotIds, SymmetricKeySlotId, Fido2CredentialFullView> for Fido2Credential {
241    fn decrypt(
242        &self,
243        ctx: &mut KeyStoreContext<KeySlotIds>,
244        key: SymmetricKeySlotId,
245    ) -> Result<Fido2CredentialFullView, CryptoError> {
246        Ok(Fido2CredentialFullView {
247            credential_id: self.credential_id.decrypt(ctx, key)?,
248            key_type: self.key_type.decrypt(ctx, key)?,
249            key_algorithm: self.key_algorithm.decrypt(ctx, key)?,
250            key_curve: self.key_curve.decrypt(ctx, key)?,
251            key_value: self.key_value.decrypt(ctx, key)?,
252            rp_id: self.rp_id.decrypt(ctx, key)?,
253            user_handle: self.user_handle.decrypt(ctx, key)?,
254            user_name: self.user_name.decrypt(ctx, key)?,
255            counter: self.counter.decrypt(ctx, key)?,
256            rp_name: self.rp_name.decrypt(ctx, key)?,
257            user_display_name: self.user_display_name.decrypt(ctx, key)?,
258            discoverable: self.discoverable.decrypt(ctx, key)?,
259            creation_date: self.creation_date,
260        })
261    }
262}
263
264impl From<Fido2CredentialView> for Fido2CredentialFullView {
265    fn from(v: Fido2CredentialView) -> Self {
266        Fido2CredentialFullView {
267            credential_id: v.credential_id,
268            key_type: v.key_type,
269            key_algorithm: v.key_algorithm,
270            key_curve: v.key_curve,
271            key_value: v.key_value,
272            rp_id: v.rp_id,
273            user_handle: v.user_handle,
274            user_name: v.user_name,
275            counter: v.counter,
276            rp_name: v.rp_name,
277            user_display_name: v.user_display_name,
278            discoverable: v.discoverable,
279            creation_date: v.creation_date,
280        }
281    }
282}
283
284impl From<Fido2CredentialFullView> for Fido2CredentialView {
285    fn from(v: Fido2CredentialFullView) -> Self {
286        Fido2CredentialView {
287            credential_id: v.credential_id,
288            key_type: v.key_type,
289            key_algorithm: v.key_algorithm,
290            key_curve: v.key_curve,
291            key_value: v.key_value,
292            rp_id: v.rp_id,
293            user_handle: v.user_handle,
294            user_name: v.user_name,
295            counter: v.counter,
296            rp_name: v.rp_name,
297            user_display_name: v.user_display_name,
298            discoverable: v.discoverable,
299            creation_date: v.creation_date,
300        }
301    }
302}
303
304impl From<&Fido2CredentialView> for Fido2CredentialListView {
305    fn from(v: &Fido2CredentialView) -> Self {
306        Fido2CredentialListView {
307            credential_id: v.credential_id.clone(),
308            rp_id: v.rp_id.clone(),
309            user_handle: v.user_handle.clone(),
310            user_name: v.user_name.clone(),
311            user_display_name: v.user_display_name.clone(),
312            counter: v.counter.clone(),
313        }
314    }
315}
316
317#[serde_with::skip_serializing_none]
318#[allow(missing_docs)]
319#[derive(Serialize, Deserialize, Debug, Clone)]
320#[serde(rename_all = "camelCase")]
321#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
322#[bitwarden_ffi::wasm_record]
323pub struct Login {
324    pub username: Option<EncString>,
325    pub password: Option<EncString>,
326    pub password_revision_date: Option<DateTime<Utc>>,
327
328    pub uris: Option<Vec<LoginUri>>,
329    pub totp: Option<EncString>,
330    pub autofill_on_page_load: Option<bool>,
331    /// Whether the login's credentials may answer HTTP authentication challenges. Stored
332    /// unencrypted, like `autofill_on_page_load`.
333    #[cfg_attr(feature = "uniffi", uniffi(default = None))]
334    pub http_authentication_enabled: Option<bool>,
335
336    pub fido2_credentials: Option<Vec<Fido2Credential>>,
337}
338
339#[serde_with::skip_serializing_none]
340#[allow(missing_docs)]
341#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
342#[serde(rename_all = "camelCase", deny_unknown_fields)]
343#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
344#[bitwarden_ffi::wasm_record]
345pub struct LoginView {
346    pub username: Option<String>,
347    pub password: Option<String>,
348    pub password_revision_date: Option<DateTime<Utc>>,
349
350    pub uris: Option<Vec<LoginUriView>>,
351    pub totp: Option<String>,
352    pub autofill_on_page_load: Option<bool>,
353    /// Whether the login's credentials may answer HTTP authentication challenges. Sealed in the
354    /// blob for blob-encrypted ciphers, and stored unencrypted on [`Login`] for ciphers in the
355    /// legacy field-level format.
356    #[cfg_attr(feature = "uniffi", uniffi(default = None))]
357    pub http_authentication_enabled: Option<bool>,
358
359    pub fido2_credentials: Option<Vec<Fido2CredentialView>>,
360}
361
362impl LoginView {
363    /// Generate checksums for all URIs in the login view
364    pub fn generate_checksums(&mut self) {
365        if let Some(uris) = &mut self.uris {
366            for uri in uris {
367                uri.generate_checksum();
368            }
369        }
370    }
371
372    /// Projects this [`LoginView`] into a [`LoginListView`].
373    pub(crate) fn to_list_view(&self) -> LoginListView {
374        LoginListView {
375            has_fido2: self.fido2_credentials.is_some(),
376            fido2_credentials: self
377                .fido2_credentials
378                .as_ref()
379                .map(|creds| creds.iter().map(Fido2CredentialListView::from).collect()),
380            username: self.username.clone(),
381            totp: self.totp.clone(),
382            uris: self.uris.clone(),
383        }
384    }
385
386    /// Compares this LoginView to the original, and returns any new password history items.
387    pub(crate) fn detect_password_change(
388        &mut self,
389        original: &Option<LoginView>,
390    ) -> Vec<PasswordHistoryView> {
391        let Some(original_login) = original else {
392            return vec![];
393        };
394
395        let original_password = original_login.password.as_deref().unwrap_or("");
396        let current_password = self.password.as_deref().unwrap_or("");
397
398        if original_password.is_empty() {
399            // No original password - set revision date only if adding new password
400            if !current_password.is_empty() {
401                self.password_revision_date = Some(Utc::now());
402            }
403            vec![]
404        } else if original_password == current_password {
405            // Password unchanged - preserve original revision date
406            self.password_revision_date = original_login.password_revision_date;
407            vec![]
408        } else {
409            // Password changed - update revision date and track change
410            self.password_revision_date = Some(Utc::now());
411            vec![PasswordHistoryView::new_password(original_password)]
412        }
413    }
414}
415
416#[serde_with::skip_serializing_none]
417#[allow(missing_docs)]
418#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
419#[serde(rename_all = "camelCase", deny_unknown_fields)]
420#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
421#[bitwarden_ffi::wasm_record]
422pub struct LoginListView {
423    pub fido2_credentials: Option<Vec<Fido2CredentialListView>>,
424    pub has_fido2: bool,
425    pub username: Option<String>,
426    pub totp: Option<String>,
427    pub uris: Option<Vec<LoginUriView>>,
428}
429
430impl CompositeEncryptable<KeySlotIds, SymmetricKeySlotId, LoginUri> for LoginUriView {
431    fn encrypt_composite(
432        &self,
433        ctx: &mut KeyStoreContext<KeySlotIds>,
434        key: SymmetricKeySlotId,
435    ) -> Result<LoginUri, CryptoError> {
436        Ok(LoginUri {
437            uri: self.uri.encrypt(ctx, key)?,
438            r#match: self.r#match,
439            uri_checksum: self.uri_checksum.encrypt(ctx, key)?,
440        })
441    }
442}
443
444impl CompositeEncryptable<KeySlotIds, SymmetricKeySlotId, Login> for LoginView {
445    fn encrypt_composite(
446        &self,
447        ctx: &mut KeyStoreContext<KeySlotIds>,
448        key: SymmetricKeySlotId,
449    ) -> Result<Login, CryptoError> {
450        Ok(Login {
451            username: self.username.encrypt(ctx, key)?,
452            password: self.password.encrypt(ctx, key)?,
453            password_revision_date: self.password_revision_date,
454            uris: self.uris.encrypt_composite(ctx, key)?,
455            totp: self
456                .totp
457                .clone()
458                .filter(|s| !s.is_empty())
459                .encrypt(ctx, key)?,
460            autofill_on_page_load: self.autofill_on_page_load,
461            http_authentication_enabled: self.http_authentication_enabled,
462            fido2_credentials: self
463                .fido2_credentials
464                .as_ref()
465                .map(|creds| {
466                    creds
467                        .iter()
468                        .map(|v| Fido2CredentialFullView::from(v.clone()))
469                        .collect::<Vec<_>>()
470                        .encrypt_composite(ctx, key)
471                })
472                .transpose()?,
473        })
474    }
475}
476
477impl Decryptable<KeySlotIds, SymmetricKeySlotId, LoginUriView> for LoginUri {
478    fn decrypt(
479        &self,
480        ctx: &mut KeyStoreContext<KeySlotIds>,
481        key: SymmetricKeySlotId,
482    ) -> Result<LoginUriView, CryptoError> {
483        Ok(LoginUriView {
484            uri: self.uri.decrypt(ctx, key)?,
485            r#match: self.r#match,
486            uri_checksum: self.uri_checksum.decrypt(ctx, key)?,
487        })
488    }
489}
490
491impl Decryptable<KeySlotIds, SymmetricKeySlotId, LoginView> for Login {
492    fn decrypt(
493        &self,
494        ctx: &mut KeyStoreContext<KeySlotIds>,
495        key: SymmetricKeySlotId,
496    ) -> Result<LoginView, CryptoError> {
497        Ok(LoginView {
498            username: self.username.decrypt(ctx, key).ok().flatten(),
499            password: self.password.decrypt(ctx, key).ok().flatten(),
500            password_revision_date: self.password_revision_date,
501            uris: self.uris.decrypt(ctx, key).ok().flatten(),
502            totp: self.totp.decrypt(ctx, key).ok().flatten(),
503            autofill_on_page_load: self.autofill_on_page_load,
504            http_authentication_enabled: self.http_authentication_enabled,
505            fido2_credentials: self
506                .fido2_credentials
507                .as_ref()
508                .and_then(|c| c.decrypt(ctx, key).ok()),
509        })
510    }
511}
512
513impl Decryptable<KeySlotIds, SymmetricKeySlotId, LoginListView> for Login {
514    fn decrypt(
515        &self,
516        ctx: &mut KeyStoreContext<KeySlotIds>,
517        key: SymmetricKeySlotId,
518    ) -> Result<LoginListView, CryptoError> {
519        Ok(LoginListView {
520            fido2_credentials: self
521                .fido2_credentials
522                .as_ref()
523                .and_then(|fido2_credentials| fido2_credentials.decrypt(ctx, key).ok()),
524            has_fido2: self.fido2_credentials.is_some(),
525            username: self.username.decrypt(ctx, key).ok().flatten(),
526            totp: self.totp.decrypt(ctx, key).ok().flatten(),
527            uris: self.uris.decrypt(ctx, key).ok().flatten(),
528        })
529    }
530}
531
532impl Decryptable<KeySlotIds, SymmetricKeySlotId, LoginView> for StrictDecrypt<&Login> {
533    fn decrypt(
534        &self,
535        ctx: &mut KeyStoreContext<KeySlotIds>,
536        key: SymmetricKeySlotId,
537    ) -> Result<LoginView, CryptoError> {
538        Ok(LoginView {
539            username: self.0.username.decrypt(ctx, key)?,
540            password: self.0.password.decrypt(ctx, key)?,
541            password_revision_date: self.0.password_revision_date,
542            uris: self.0.uris.decrypt(ctx, key)?,
543            totp: self.0.totp.decrypt(ctx, key)?,
544            autofill_on_page_load: self.0.autofill_on_page_load,
545            http_authentication_enabled: self.0.http_authentication_enabled,
546            fido2_credentials: self
547                .0
548                .fido2_credentials
549                .as_ref()
550                .map(|c| c.decrypt(ctx, key))
551                .transpose()?,
552        })
553    }
554}
555
556impl Decryptable<KeySlotIds, SymmetricKeySlotId, LoginListView> for StrictDecrypt<&Login> {
557    fn decrypt(
558        &self,
559        ctx: &mut KeyStoreContext<KeySlotIds>,
560        key: SymmetricKeySlotId,
561    ) -> Result<LoginListView, CryptoError> {
562        Ok(LoginListView {
563            fido2_credentials: self
564                .0
565                .fido2_credentials
566                .as_ref()
567                .map(|fido2_credentials| fido2_credentials.decrypt(ctx, key))
568                .transpose()?,
569            has_fido2: self.0.fido2_credentials.is_some(),
570            username: self.0.username.decrypt(ctx, key)?,
571            totp: self.0.totp.decrypt(ctx, key)?,
572            uris: self.0.uris.decrypt(ctx, key)?,
573        })
574    }
575}
576
577impl Decryptable<KeySlotIds, SymmetricKeySlotId, Fido2CredentialView> for Fido2Credential {
578    fn decrypt(
579        &self,
580        ctx: &mut KeyStoreContext<KeySlotIds>,
581        key: SymmetricKeySlotId,
582    ) -> Result<Fido2CredentialView, CryptoError> {
583        Ok(Fido2CredentialView {
584            credential_id: self.credential_id.decrypt(ctx, key)?,
585            key_type: self.key_type.decrypt(ctx, key)?,
586            key_algorithm: self.key_algorithm.decrypt(ctx, key)?,
587            key_curve: self.key_curve.decrypt(ctx, key)?,
588            key_value: self.key_value.decrypt(ctx, key)?,
589            rp_id: self.rp_id.decrypt(ctx, key)?,
590            user_handle: self.user_handle.decrypt(ctx, key)?,
591            user_name: self.user_name.decrypt(ctx, key)?,
592            counter: self.counter.decrypt(ctx, key)?,
593            rp_name: self.rp_name.decrypt(ctx, key)?,
594            user_display_name: self.user_display_name.decrypt(ctx, key)?,
595            discoverable: self.discoverable.decrypt(ctx, key)?,
596            creation_date: self.creation_date,
597        })
598    }
599}
600
601impl Decryptable<KeySlotIds, SymmetricKeySlotId, Fido2CredentialListView> for Fido2Credential {
602    fn decrypt(
603        &self,
604        ctx: &mut KeyStoreContext<KeySlotIds>,
605        key: SymmetricKeySlotId,
606    ) -> Result<Fido2CredentialListView, CryptoError> {
607        Ok(Fido2CredentialListView {
608            credential_id: self.credential_id.decrypt(ctx, key)?,
609            rp_id: self.rp_id.decrypt(ctx, key)?,
610            user_handle: self.user_handle.decrypt(ctx, key)?,
611            user_name: self.user_name.decrypt(ctx, key)?,
612            user_display_name: self.user_display_name.decrypt(ctx, key)?,
613            counter: self.counter.decrypt(ctx, key)?,
614        })
615    }
616}
617
618impl TryFrom<CipherLoginModel> for Login {
619    type Error = VaultParseError;
620
621    fn try_from(login: CipherLoginModel) -> Result<Self, Self::Error> {
622        Ok(Self {
623            username: EncString::try_from_optional(login.username)?,
624            password: EncString::try_from_optional(login.password)?,
625            password_revision_date: login
626                .password_revision_date
627                .map(|d| d.parse())
628                .transpose()?,
629            uris: login
630                .uris
631                .map(|v| v.into_iter().map(|u| u.try_into()).collect())
632                .transpose()?,
633            totp: EncString::try_from_optional(login.totp)?,
634            autofill_on_page_load: login.autofill_on_page_load,
635            http_authentication_enabled: login.http_authentication_enabled,
636            fido2_credentials: login
637                .fido2_credentials
638                .map(|v| v.into_iter().map(|c| c.try_into()).collect())
639                .transpose()?,
640        })
641    }
642}
643
644impl TryFrom<CipherLoginUriModel> for LoginUri {
645    type Error = VaultParseError;
646
647    fn try_from(uri: CipherLoginUriModel) -> Result<Self, Self::Error> {
648        Ok(Self {
649            uri: EncString::try_from_optional(uri.uri)?,
650            r#match: uri.r#match.map(|m| m.try_into()).transpose()?,
651            uri_checksum: EncString::try_from_optional(uri.uri_checksum)?,
652        })
653    }
654}
655
656impl TryFrom<bitwarden_api_api::models::UriMatchType> for UriMatchType {
657    type Error = bitwarden_core::MissingFieldError;
658
659    fn try_from(value: bitwarden_api_api::models::UriMatchType) -> Result<Self, Self::Error> {
660        Ok(match value {
661            bitwarden_api_api::models::UriMatchType::Domain => Self::Domain,
662            bitwarden_api_api::models::UriMatchType::Host => Self::Host,
663            bitwarden_api_api::models::UriMatchType::StartsWith => Self::StartsWith,
664            bitwarden_api_api::models::UriMatchType::Exact => Self::Exact,
665            bitwarden_api_api::models::UriMatchType::RegularExpression => Self::RegularExpression,
666            bitwarden_api_api::models::UriMatchType::Never => Self::Never,
667            bitwarden_api_api::models::UriMatchType::__Unknown(_) => {
668                return Err(bitwarden_core::MissingFieldError("match"));
669            }
670        })
671    }
672}
673
674impl TryFrom<bitwarden_api_api::models::CipherFido2CredentialModel> for Fido2Credential {
675    type Error = VaultParseError;
676
677    fn try_from(
678        value: bitwarden_api_api::models::CipherFido2CredentialModel,
679    ) -> Result<Self, Self::Error> {
680        Ok(Self {
681            credential_id: require!(value.credential_id).parse()?,
682            key_type: require!(value.key_type).parse()?,
683            key_algorithm: require!(value.key_algorithm).parse()?,
684            key_curve: require!(value.key_curve).parse()?,
685            key_value: require!(value.key_value).parse()?,
686            rp_id: require!(value.rp_id).parse()?,
687            user_handle: EncString::try_from_optional(value.user_handle)
688                .ok()
689                .flatten(),
690            user_name: EncString::try_from_optional(value.user_name).ok().flatten(),
691            counter: require!(value.counter).parse()?,
692            rp_name: EncString::try_from_optional(value.rp_name).ok().flatten(),
693            user_display_name: EncString::try_from_optional(value.user_display_name)
694                .ok()
695                .flatten(),
696            discoverable: require!(value.discoverable).parse()?,
697            creation_date: value.creation_date.parse()?,
698        })
699    }
700}
701
702impl From<LoginUri> for bitwarden_api_api::models::CipherLoginUriModel {
703    fn from(uri: LoginUri) -> Self {
704        bitwarden_api_api::models::CipherLoginUriModel {
705            uri: uri.uri.map(|u| u.to_string()),
706            uri_checksum: uri.uri_checksum.map(|c| c.to_string()),
707            r#match: uri.r#match.map(|m| m.into()),
708        }
709    }
710}
711
712impl From<UriMatchType> for bitwarden_api_api::models::UriMatchType {
713    fn from(match_type: UriMatchType) -> Self {
714        match match_type {
715            UriMatchType::Domain => bitwarden_api_api::models::UriMatchType::Domain,
716            UriMatchType::Host => bitwarden_api_api::models::UriMatchType::Host,
717            UriMatchType::StartsWith => bitwarden_api_api::models::UriMatchType::StartsWith,
718            UriMatchType::Exact => bitwarden_api_api::models::UriMatchType::Exact,
719            UriMatchType::RegularExpression => {
720                bitwarden_api_api::models::UriMatchType::RegularExpression
721            }
722            UriMatchType::Never => bitwarden_api_api::models::UriMatchType::Never,
723        }
724    }
725}
726
727impl From<Fido2Credential> for bitwarden_api_api::models::CipherFido2CredentialModel {
728    fn from(cred: Fido2Credential) -> Self {
729        bitwarden_api_api::models::CipherFido2CredentialModel {
730            credential_id: Some(cred.credential_id.to_string()),
731            key_type: Some(cred.key_type.to_string()),
732            key_algorithm: Some(cred.key_algorithm.to_string()),
733            key_curve: Some(cred.key_curve.to_string()),
734            key_value: Some(cred.key_value.to_string()),
735            rp_id: Some(cred.rp_id.to_string()),
736            user_handle: cred.user_handle.map(|h| h.to_string()),
737            user_name: cred.user_name.map(|n| n.to_string()),
738            counter: Some(cred.counter.to_string()),
739            rp_name: cred.rp_name.map(|n| n.to_string()),
740            user_display_name: cred.user_display_name.map(|n| n.to_string()),
741            discoverable: Some(cred.discoverable.to_string()),
742            creation_date: cred.creation_date.to_rfc3339(),
743        }
744    }
745}
746
747impl From<Login> for bitwarden_api_api::models::CipherLoginModel {
748    fn from(login: Login) -> Self {
749        bitwarden_api_api::models::CipherLoginModel {
750            uri: None,
751            uris: login
752                .uris
753                .map(|u| u.into_iter().map(|u| u.into()).collect()),
754            username: login.username.map(|u| u.to_string()),
755            password: login.password.map(|p| p.to_string()),
756            password_revision_date: login.password_revision_date.map(|d| d.to_rfc3339()),
757            totp: login.totp.map(|t| t.to_string()),
758            autofill_on_page_load: login.autofill_on_page_load,
759            http_authentication_enabled: login.http_authentication_enabled,
760            fido2_credentials: login
761                .fido2_credentials
762                .map(|c| c.into_iter().map(|c| c.into()).collect()),
763        }
764    }
765}
766
767impl CipherKind for Login {
768    fn decrypt_subtitle(
769        &self,
770        ctx: &mut KeyStoreContext<KeySlotIds>,
771        key: SymmetricKeySlotId,
772    ) -> Result<String, CryptoError> {
773        let username: Option<String> = self.username.decrypt(ctx, key)?;
774
775        Ok(username.unwrap_or_default())
776    }
777
778    fn get_copyable_fields(&self, _: Option<&Cipher>) -> Vec<CopyableCipherFields> {
779        [
780            self.username
781                .as_ref()
782                .map(|_| CopyableCipherFields::LoginUsername),
783            self.password
784                .as_ref()
785                .map(|_| CopyableCipherFields::LoginPassword),
786            self.totp.as_ref().map(|_| CopyableCipherFields::LoginTotp),
787        ]
788        .into_iter()
789        .flatten()
790        .collect()
791    }
792}
793
794#[cfg(test)]
795mod tests {
796    use crate::{
797        Login,
798        cipher::cipher::{CipherKind, CopyableCipherFields},
799    };
800
801    #[test]
802    fn test_valid_checksum() {
803        let uri = super::LoginUriView {
804            uri: Some("https://example.com".to_string()),
805            r#match: Some(super::UriMatchType::Domain),
806            uri_checksum: Some("EAaArVRs5qV39C9S3zO0z9ynVoWeZkuNfeMpsVDQnOk=".to_string()),
807        };
808        assert!(uri.is_checksum_valid());
809    }
810
811    #[test]
812    fn test_invalid_checksum() {
813        let uri = super::LoginUriView {
814            uri: Some("https://example.com".to_string()),
815            r#match: Some(super::UriMatchType::Domain),
816            uri_checksum: Some("UtSgIv8LYfEdOu7yqjF7qXWhmouYGYC8RSr7/ryZg5Q=".to_string()),
817        };
818        assert!(!uri.is_checksum_valid());
819    }
820
821    #[test]
822    fn test_missing_checksum() {
823        let uri = super::LoginUriView {
824            uri: Some("https://example.com".to_string()),
825            r#match: Some(super::UriMatchType::Domain),
826            uri_checksum: None,
827        };
828        assert!(!uri.is_checksum_valid());
829    }
830
831    #[test]
832    fn test_generate_checksum() {
833        let mut uri = super::LoginUriView {
834            uri: Some("https://test.com".to_string()),
835            r#match: Some(super::UriMatchType::Domain),
836            uri_checksum: None,
837        };
838
839        uri.generate_checksum();
840
841        assert_eq!(
842            uri.uri_checksum.unwrap().as_str(),
843            "OWk2vQvwYD1nhLZdA+ltrpBWbDa2JmHyjUEWxRZSS8w="
844        );
845    }
846
847    #[test]
848    fn test_get_copyable_fields_login_password() {
849        let login_with_password = Login {
850            username: None,
851            password: Some("2.38t4E88QbQEkBdK+oZNHFg==|B3BiDcG3ZfEkD2BK+FMytQ==|2Dw1/f+LCfkCmCj4gKOxOu6CRnZj93qaBYUqbzy/reU=".parse().unwrap()),
852            password_revision_date: None,
853            uris: None,
854            totp: None,
855            autofill_on_page_load: None,
856            http_authentication_enabled: None,
857            fido2_credentials: None,
858        };
859
860        let copyable_fields = login_with_password.get_copyable_fields(None);
861        assert_eq!(copyable_fields, vec![CopyableCipherFields::LoginPassword]);
862    }
863
864    #[test]
865    fn test_get_copyable_fields_login_username() {
866        let login_with_username = Login {
867            username: Some("2.38t4E88QbQEkBdK+oZNHFg==|B3BiDcG3ZfEkD2BK+FMytQ==|2Dw1/f+LCfkCmCj4gKOxOu6CRnZj93qaBYUqbzy/reU=".parse().unwrap()),
868            password: None,
869            password_revision_date: None,
870            uris: None,
871            totp: None,
872            autofill_on_page_load: None,
873            http_authentication_enabled: None,
874            fido2_credentials: None,
875        };
876
877        let copyable_fields = login_with_username.get_copyable_fields(None);
878        assert_eq!(copyable_fields, vec![CopyableCipherFields::LoginUsername]);
879    }
880
881    #[test]
882    fn test_get_copyable_fields_login_everything() {
883        let login = Login {
884            username: Some("2.38t4E88QbQEkBdK+oZNHFg==|B3BiDcG3ZfEkD2BK+FMytQ==|2Dw1/f+LCfkCmCj4gKOxOu6CRnZj93qaBYUqbzy/reU=".parse().unwrap()),
885            password: Some("2.38t4E88QbQEkBdK+oZNHFg==|B3BiDcG3ZfEkD2BK+FMytQ==|2Dw1/f+LCfkCmCj4gKOxOu6CRnZj93qaBYUqbzy/reU=".parse().unwrap()),
886            password_revision_date: None,
887            uris: None,
888            totp: Some("2.38t4E88QbQEkBdK+oZNHFg==|B3BiDcG3ZfEkD2BK+FMytQ==|2Dw1/f+LCfkCmCj4gKOxOu6CRnZj93qaBYUqbzy/reU=".parse().unwrap()),
889            autofill_on_page_load: None,
890            http_authentication_enabled: None,
891            fido2_credentials: None,
892        };
893
894        let copyable_fields = login.get_copyable_fields(None);
895        assert_eq!(
896            copyable_fields,
897            vec![
898                CopyableCipherFields::LoginUsername,
899                CopyableCipherFields::LoginPassword,
900                CopyableCipherFields::LoginTotp
901            ]
902        );
903    }
904}