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