bitwarden_vault/cipher/
login.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
use base64::{engine::general_purpose::STANDARD, Engine};
use bitwarden_api_api::models::{CipherLoginModel, CipherLoginUriModel};
use bitwarden_core::require;
use bitwarden_crypto::{
    CryptoError, EncString, KeyDecryptable, KeyEncryptable, SymmetricCryptoKey,
};
use chrono::{DateTime, Utc};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_repr::{Deserialize_repr, Serialize_repr};

use crate::VaultParseError;

#[derive(Clone, Copy, Serialize_repr, Deserialize_repr, Debug, JsonSchema)]
#[repr(u8)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
pub enum UriMatchType {
    Domain = 0,
    Host = 1,
    StartsWith = 2,
    Exact = 3,
    RegularExpression = 4,
    Never = 5,
}

#[derive(Serialize, Deserialize, Debug, JsonSchema, Clone)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
pub struct LoginUri {
    pub uri: Option<EncString>,
    pub r#match: Option<UriMatchType>,
    pub uri_checksum: Option<EncString>,
}

#[derive(Serialize, Deserialize, Debug, JsonSchema, Clone)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
pub struct LoginUriView {
    pub uri: Option<String>,
    pub r#match: Option<UriMatchType>,
    pub uri_checksum: Option<String>,
}

impl LoginUriView {
    pub(crate) fn is_checksum_valid(&self) -> bool {
        let Some(uri) = &self.uri else {
            return false;
        };
        let Some(cs) = &self.uri_checksum else {
            return false;
        };
        let Ok(cs) = STANDARD.decode(cs) else {
            return false;
        };

        use sha2::Digest;
        let uri_hash = sha2::Sha256::new().chain_update(uri.as_bytes()).finalize();

        uri_hash.as_slice() == cs
    }

    pub(crate) fn generate_checksum(&mut self) {
        if let Some(uri) = &self.uri {
            use sha2::Digest;
            let uri_hash = sha2::Sha256::new().chain_update(uri.as_bytes()).finalize();
            let uri_hash = STANDARD.encode(uri_hash.as_slice());
            self.uri_checksum = Some(uri_hash);
        }
    }
}

#[derive(Serialize, Deserialize, Debug, JsonSchema, Clone)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
pub struct Fido2Credential {
    pub credential_id: EncString,
    pub key_type: EncString,
    pub key_algorithm: EncString,
    pub key_curve: EncString,
    pub key_value: EncString,
    pub rp_id: EncString,
    pub user_handle: Option<EncString>,
    pub user_name: Option<EncString>,
    pub counter: EncString,
    pub rp_name: Option<EncString>,
    pub user_display_name: Option<EncString>,
    pub discoverable: EncString,
    pub creation_date: DateTime<Utc>,
}

#[derive(Serialize, Deserialize, Debug, JsonSchema, Clone)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
pub struct Fido2CredentialView {
    pub credential_id: String,
    pub key_type: String,
    pub key_algorithm: String,
    pub key_curve: String,
    // This value doesn't need to be returned to the client
    // so we keep it encrypted until we need it
    pub key_value: EncString,
    pub rp_id: String,
    pub user_handle: Option<String>,
    pub user_name: Option<String>,
    pub counter: String,
    pub rp_name: Option<String>,
    pub user_display_name: Option<String>,
    pub discoverable: String,
    pub creation_date: DateTime<Utc>,
}

// This is mostly a copy of the Fido2CredentialView, but with the key exposed
// Only meant to be used internally and not exposed to the outside world
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Fido2CredentialFullView {
    pub credential_id: String,
    pub key_type: String,
    pub key_algorithm: String,
    pub key_curve: String,
    pub key_value: String,
    pub rp_id: String,
    pub user_handle: Option<String>,
    pub user_name: Option<String>,
    pub counter: String,
    pub rp_name: Option<String>,
    pub user_display_name: Option<String>,
    pub discoverable: String,
    pub creation_date: DateTime<Utc>,
}

// This is mostly a copy of the Fido2CredentialView, meant to be exposed to the clients
// to let them select where to store the new credential. Note that it doesn't contain
// the encrypted key as that is only filled when the cipher is selected
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
pub struct Fido2CredentialNewView {
    pub credential_id: String,
    pub key_type: String,
    pub key_algorithm: String,
    pub key_curve: String,
    pub rp_id: String,
    pub user_handle: Option<String>,
    pub user_name: Option<String>,
    pub counter: String,
    pub rp_name: Option<String>,
    pub user_display_name: Option<String>,
    pub creation_date: DateTime<Utc>,
}

impl From<Fido2CredentialFullView> for Fido2CredentialNewView {
    fn from(value: Fido2CredentialFullView) -> Self {
        Fido2CredentialNewView {
            credential_id: value.credential_id,
            key_type: value.key_type,
            key_algorithm: value.key_algorithm,
            key_curve: value.key_curve,
            rp_id: value.rp_id,
            user_handle: value.user_handle,
            user_name: value.user_name,
            counter: value.counter,
            rp_name: value.rp_name,
            user_display_name: value.user_display_name,
            creation_date: value.creation_date,
        }
    }
}

impl KeyEncryptable<SymmetricCryptoKey, Fido2Credential> for Fido2CredentialFullView {
    fn encrypt_with_key(self, key: &SymmetricCryptoKey) -> Result<Fido2Credential, CryptoError> {
        Ok(Fido2Credential {
            credential_id: self.credential_id.encrypt_with_key(key)?,
            key_type: self.key_type.encrypt_with_key(key)?,
            key_algorithm: self.key_algorithm.encrypt_with_key(key)?,
            key_curve: self.key_curve.encrypt_with_key(key)?,
            key_value: self.key_value.encrypt_with_key(key)?,
            rp_id: self.rp_id.encrypt_with_key(key)?,
            user_handle: self
                .user_handle
                .map(|h| h.encrypt_with_key(key))
                .transpose()?,
            user_name: self.user_name.encrypt_with_key(key)?,
            counter: self.counter.encrypt_with_key(key)?,
            rp_name: self.rp_name.encrypt_with_key(key)?,
            user_display_name: self.user_display_name.encrypt_with_key(key)?,
            discoverable: self.discoverable.encrypt_with_key(key)?,
            creation_date: self.creation_date,
        })
    }
}

impl KeyDecryptable<SymmetricCryptoKey, Fido2CredentialFullView> for Fido2Credential {
    fn decrypt_with_key(
        &self,
        key: &SymmetricCryptoKey,
    ) -> Result<Fido2CredentialFullView, CryptoError> {
        Ok(Fido2CredentialFullView {
            credential_id: self.credential_id.decrypt_with_key(key)?,
            key_type: self.key_type.decrypt_with_key(key)?,
            key_algorithm: self.key_algorithm.decrypt_with_key(key)?,
            key_curve: self.key_curve.decrypt_with_key(key)?,
            key_value: self.key_value.decrypt_with_key(key)?,
            rp_id: self.rp_id.decrypt_with_key(key)?,
            user_handle: self.user_handle.decrypt_with_key(key)?,
            user_name: self.user_name.decrypt_with_key(key)?,
            counter: self.counter.decrypt_with_key(key)?,
            rp_name: self.rp_name.decrypt_with_key(key)?,
            user_display_name: self.user_display_name.decrypt_with_key(key)?,
            discoverable: self.discoverable.decrypt_with_key(key)?,
            creation_date: self.creation_date,
        })
    }
}

impl KeyDecryptable<SymmetricCryptoKey, Fido2CredentialFullView> for Fido2CredentialView {
    fn decrypt_with_key(
        &self,
        key: &SymmetricCryptoKey,
    ) -> Result<Fido2CredentialFullView, CryptoError> {
        Ok(Fido2CredentialFullView {
            credential_id: self.credential_id.clone(),
            key_type: self.key_type.clone(),
            key_algorithm: self.key_algorithm.clone(),
            key_curve: self.key_curve.clone(),
            key_value: self.key_value.decrypt_with_key(key)?,
            rp_id: self.rp_id.clone(),
            user_handle: self.user_handle.clone(),
            user_name: self.user_name.clone(),
            counter: self.counter.clone(),
            rp_name: self.rp_name.clone(),
            user_display_name: self.user_display_name.clone(),
            discoverable: self.discoverable.clone(),
            creation_date: self.creation_date,
        })
    }
}

#[derive(Serialize, Deserialize, Debug, JsonSchema, Clone)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
pub struct Login {
    pub username: Option<EncString>,
    pub password: Option<EncString>,
    pub password_revision_date: Option<DateTime<Utc>>,

    pub uris: Option<Vec<LoginUri>>,
    pub totp: Option<EncString>,
    pub autofill_on_page_load: Option<bool>,

    pub fido2_credentials: Option<Vec<Fido2Credential>>,
}

#[derive(Serialize, Deserialize, Debug, JsonSchema, Clone)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
pub struct LoginView {
    pub username: Option<String>,
    pub password: Option<String>,
    pub password_revision_date: Option<DateTime<Utc>>,

    pub uris: Option<Vec<LoginUriView>>,
    pub totp: Option<String>,
    pub autofill_on_page_load: Option<bool>,

    // TODO: Remove this once the SDK supports state
    pub fido2_credentials: Option<Vec<Fido2Credential>>,
}

impl KeyEncryptable<SymmetricCryptoKey, LoginUri> for LoginUriView {
    fn encrypt_with_key(self, key: &SymmetricCryptoKey) -> Result<LoginUri, CryptoError> {
        Ok(LoginUri {
            uri: self.uri.encrypt_with_key(key)?,
            r#match: self.r#match,
            uri_checksum: self.uri_checksum.encrypt_with_key(key)?,
        })
    }
}

impl KeyEncryptable<SymmetricCryptoKey, Login> for LoginView {
    fn encrypt_with_key(self, key: &SymmetricCryptoKey) -> Result<Login, CryptoError> {
        Ok(Login {
            username: self.username.encrypt_with_key(key)?,
            password: self.password.encrypt_with_key(key)?,
            password_revision_date: self.password_revision_date,
            uris: self.uris.encrypt_with_key(key)?,
            totp: self.totp.encrypt_with_key(key)?,
            autofill_on_page_load: self.autofill_on_page_load,
            fido2_credentials: self.fido2_credentials,
        })
    }
}

impl KeyDecryptable<SymmetricCryptoKey, LoginUriView> for LoginUri {
    fn decrypt_with_key(&self, key: &SymmetricCryptoKey) -> Result<LoginUriView, CryptoError> {
        Ok(LoginUriView {
            uri: self.uri.decrypt_with_key(key)?,
            r#match: self.r#match,
            uri_checksum: self.uri_checksum.decrypt_with_key(key)?,
        })
    }
}

impl KeyDecryptable<SymmetricCryptoKey, LoginView> for Login {
    fn decrypt_with_key(&self, key: &SymmetricCryptoKey) -> Result<LoginView, CryptoError> {
        Ok(LoginView {
            username: self.username.decrypt_with_key(key).ok().flatten(),
            password: self.password.decrypt_with_key(key).ok().flatten(),
            password_revision_date: self.password_revision_date,
            uris: self.uris.decrypt_with_key(key).ok().flatten(),
            totp: self.totp.decrypt_with_key(key).ok().flatten(),
            autofill_on_page_load: self.autofill_on_page_load,
            fido2_credentials: self.fido2_credentials.clone(),
        })
    }
}

impl KeyEncryptable<SymmetricCryptoKey, Fido2Credential> for Fido2CredentialView {
    fn encrypt_with_key(self, key: &SymmetricCryptoKey) -> Result<Fido2Credential, CryptoError> {
        Ok(Fido2Credential {
            credential_id: self.credential_id.encrypt_with_key(key)?,
            key_type: self.key_type.encrypt_with_key(key)?,
            key_algorithm: self.key_algorithm.encrypt_with_key(key)?,
            key_curve: self.key_curve.encrypt_with_key(key)?,
            key_value: self.key_value,
            rp_id: self.rp_id.encrypt_with_key(key)?,
            user_handle: self
                .user_handle
                .map(|h| h.encrypt_with_key(key))
                .transpose()?,
            user_name: self
                .user_name
                .map(|n| n.encrypt_with_key(key))
                .transpose()?,
            counter: self.counter.encrypt_with_key(key)?,
            rp_name: self.rp_name.encrypt_with_key(key)?,
            user_display_name: self.user_display_name.encrypt_with_key(key)?,
            discoverable: self.discoverable.encrypt_with_key(key)?,
            creation_date: self.creation_date,
        })
    }
}

impl KeyDecryptable<SymmetricCryptoKey, Fido2CredentialView> for Fido2Credential {
    fn decrypt_with_key(
        &self,
        key: &SymmetricCryptoKey,
    ) -> Result<Fido2CredentialView, CryptoError> {
        Ok(Fido2CredentialView {
            credential_id: self.credential_id.decrypt_with_key(key)?,
            key_type: self.key_type.decrypt_with_key(key)?,
            key_algorithm: self.key_algorithm.decrypt_with_key(key)?,
            key_curve: self.key_curve.decrypt_with_key(key)?,
            key_value: self.key_value.clone(),
            rp_id: self.rp_id.decrypt_with_key(key)?,
            user_handle: self.user_handle.decrypt_with_key(key)?,
            user_name: self.user_name.decrypt_with_key(key)?,
            counter: self.counter.decrypt_with_key(key)?,
            rp_name: self.rp_name.decrypt_with_key(key)?,
            user_display_name: self.user_display_name.decrypt_with_key(key)?,
            discoverable: self.discoverable.decrypt_with_key(key)?,
            creation_date: self.creation_date,
        })
    }
}

impl TryFrom<CipherLoginModel> for Login {
    type Error = VaultParseError;

    fn try_from(login: CipherLoginModel) -> Result<Self, Self::Error> {
        Ok(Self {
            username: EncString::try_from_optional(login.username)?,
            password: EncString::try_from_optional(login.password)?,
            password_revision_date: login
                .password_revision_date
                .map(|d| d.parse())
                .transpose()?,
            uris: login
                .uris
                .map(|v| v.into_iter().map(|u| u.try_into()).collect())
                .transpose()?,
            totp: EncString::try_from_optional(login.totp)?,
            autofill_on_page_load: login.autofill_on_page_load,
            fido2_credentials: login
                .fido2_credentials
                .map(|v| v.into_iter().map(|c| c.try_into()).collect())
                .transpose()?,
        })
    }
}

impl TryFrom<CipherLoginUriModel> for LoginUri {
    type Error = VaultParseError;

    fn try_from(uri: CipherLoginUriModel) -> Result<Self, Self::Error> {
        Ok(Self {
            uri: EncString::try_from_optional(uri.uri)?,
            r#match: uri.r#match.map(|m| m.into()),
            uri_checksum: EncString::try_from_optional(uri.uri_checksum)?,
        })
    }
}

impl From<bitwarden_api_api::models::UriMatchType> for UriMatchType {
    fn from(value: bitwarden_api_api::models::UriMatchType) -> Self {
        match value {
            bitwarden_api_api::models::UriMatchType::Domain => Self::Domain,
            bitwarden_api_api::models::UriMatchType::Host => Self::Host,
            bitwarden_api_api::models::UriMatchType::StartsWith => Self::StartsWith,
            bitwarden_api_api::models::UriMatchType::Exact => Self::Exact,
            bitwarden_api_api::models::UriMatchType::RegularExpression => Self::RegularExpression,
            bitwarden_api_api::models::UriMatchType::Never => Self::Never,
        }
    }
}

impl TryFrom<bitwarden_api_api::models::CipherFido2CredentialModel> for Fido2Credential {
    type Error = VaultParseError;

    fn try_from(
        value: bitwarden_api_api::models::CipherFido2CredentialModel,
    ) -> Result<Self, Self::Error> {
        Ok(Self {
            credential_id: require!(value.credential_id).parse()?,
            key_type: require!(value.key_type).parse()?,
            key_algorithm: require!(value.key_algorithm).parse()?,
            key_curve: require!(value.key_curve).parse()?,
            key_value: require!(value.key_value).parse()?,
            rp_id: require!(value.rp_id).parse()?,
            user_handle: EncString::try_from_optional(value.user_handle)
                .ok()
                .flatten(),
            user_name: EncString::try_from_optional(value.user_name).ok().flatten(),
            counter: require!(value.counter).parse()?,
            rp_name: EncString::try_from_optional(value.rp_name).ok().flatten(),
            user_display_name: EncString::try_from_optional(value.user_display_name)
                .ok()
                .flatten(),
            discoverable: require!(value.discoverable).parse()?,
            creation_date: value.creation_date.parse()?,
        })
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn test_valid_checksum() {
        let uri = super::LoginUriView {
            uri: Some("https://example.com".to_string()),
            r#match: Some(super::UriMatchType::Domain),
            uri_checksum: Some("EAaArVRs5qV39C9S3zO0z9ynVoWeZkuNfeMpsVDQnOk=".to_string()),
        };
        assert!(uri.is_checksum_valid());
    }

    #[test]
    fn test_invalid_checksum() {
        let uri = super::LoginUriView {
            uri: Some("https://example.com".to_string()),
            r#match: Some(super::UriMatchType::Domain),
            uri_checksum: Some("UtSgIv8LYfEdOu7yqjF7qXWhmouYGYC8RSr7/ryZg5Q=".to_string()),
        };
        assert!(!uri.is_checksum_valid());
    }

    #[test]
    fn test_missing_checksum() {
        let uri = super::LoginUriView {
            uri: Some("https://example.com".to_string()),
            r#match: Some(super::UriMatchType::Domain),
            uri_checksum: None,
        };
        assert!(!uri.is_checksum_valid());
    }

    #[test]
    fn test_generate_checksum() {
        let mut uri = super::LoginUriView {
            uri: Some("https://test.com".to_string()),
            r#match: Some(super::UriMatchType::Domain),
            uri_checksum: None,
        };

        uri.generate_checksum();

        assert_eq!(
            uri.uri_checksum.unwrap().as_str(),
            "OWk2vQvwYD1nhLZdA+ltrpBWbDa2JmHyjUEWxRZSS8w="
        );
    }
}