Skip to main content

bitwarden_exporters/cxf/
login.rs

1//! Login credential conversion
2//!
3//! Handles conversion between internal [Login] and credential exchange [BasicAuthCredential] and
4//! [PasskeyCredential].
5
6use bitwarden_core::MissingFieldError;
7use bitwarden_fido::{InvalidGuidError, string_to_guid_bytes};
8use bitwarden_vault::{FieldType, Totp, TotpAlgorithm};
9use chrono::{DateTime, Utc};
10use credential_exchange_format::{
11    AndroidAppIdCredential, B64Url, BasicAuthCredential, CredentialScope,
12    GeneratedPasswordCredential, NotB64UrlEncoded, OTPHashAlgorithm, PasskeyCredential,
13    TotpCredential,
14};
15use thiserror::Error;
16
17use crate::{Fido2Credential, Field, Login, LoginUri};
18
19/// Prefix that indicates the URL is an Android app scheme.
20const ANDROID_APP_SCHEME: &str = "androidapp://";
21
22/// Name of the hidden custom field used to preserve a [GeneratedPasswordCredential] that conflicts
23/// with the [BasicAuthCredential] password.
24const GENERATED_PASSWORD_FIELD_NAME: &str = "Generated Password";
25
26/// Convert CXF OTPHashAlgorithm to Bitwarden's TotpAlgorithm
27/// Handles standard algorithms and special cases like Steam
28fn convert_otp_algorithm(algorithm: &OTPHashAlgorithm) -> TotpAlgorithm {
29    match algorithm {
30        OTPHashAlgorithm::Sha1 => TotpAlgorithm::Sha1,
31        OTPHashAlgorithm::Sha256 => TotpAlgorithm::Sha256,
32        OTPHashAlgorithm::Sha512 => TotpAlgorithm::Sha512,
33        OTPHashAlgorithm::Unknown(algo) if algo == "steam" => TotpAlgorithm::Steam,
34        OTPHashAlgorithm::Unknown(_) | _ => TotpAlgorithm::Sha1, /* Default to SHA1 for unknown
35                                                                  * algorithms */
36    }
37}
38
39/// Convert CXF TotpCredential to Bitwarden's Totp struct
40/// This ensures we use the exact same encoding and formatting as Bitwarden's core implementation
41fn totp_credential_to_totp(cxf_totp: &TotpCredential) -> Totp {
42    let algorithm = convert_otp_algorithm(&cxf_totp.algorithm);
43
44    let secret_bytes: Vec<u8> = cxf_totp.secret.clone().into();
45
46    Totp {
47        account: cxf_totp.username.clone(),
48        algorithm,
49        digits: cxf_totp.digits as u32,
50        issuer: cxf_totp.issuer.clone(),
51        period: cxf_totp.period as u32,
52        secret: secret_bytes,
53    }
54}
55
56/// Convert CXF login related credentials to a Bitwarden [Login].
57///
58/// Returns the login together with any additional custom fields that should be added to the
59/// cipher, e.g. a generated password that conflicts with the basic auth password.
60pub(super) fn to_login(
61    creation_date: DateTime<Utc>,
62    basic_auth: Option<&BasicAuthCredential>,
63    passkey: Option<&PasskeyCredential>,
64    totp: Option<&TotpCredential>,
65    generated_password: Option<&GeneratedPasswordCredential>,
66    scope: Option<&CredentialScope>,
67) -> (Login, Vec<Field>) {
68    // Use basic_auth username first, fallback to non-empty passkey username
69    let username = basic_auth
70        .and_then(|v| v.username.clone().map(Into::into))
71        .or_else(|| {
72            passkey
73                .filter(|p| !p.username.is_empty())
74                .map(|p| p.username.clone())
75        });
76
77    // Use scope URIs first, fallback to passkey rp_id
78    let login_uris = scope
79        .map(to_uris)
80        .or_else(|| passkey.map(|p| vec![passkey_rp_id_to_uri(&p.rp_id)]))
81        .unwrap_or_default();
82
83    let basic_auth_password = basic_auth.and_then(|v| v.password.clone().map(String::from));
84    let generated_password = generated_password
85        .map(|g| g.password.clone())
86        .filter(|p| !p.is_empty());
87
88    // Use non-empty basic_auth password first, fallback to the generated password. If both exist
89    // and differ, preserve the generated password as a hidden custom field so it isn't lost.
90    let (password, fields) = match (basic_auth_password, generated_password) {
91        (Some(password), Some(generated)) if password.is_empty() => (Some(generated), vec![]),
92        (Some(password), Some(generated)) if password != generated => (
93            Some(password),
94            vec![Field {
95                name: Some(GENERATED_PASSWORD_FIELD_NAME.to_string()),
96                value: Some(generated),
97                r#type: FieldType::Hidden as u8,
98                linked_id: None,
99            }],
100        ),
101        (password, generated) => (password.or(generated), vec![]),
102    };
103
104    let login = Login {
105        username,
106        password,
107        login_uris,
108        totp: totp.map(|t| totp_credential_to_totp(t).to_string()),
109        fido2_credentials: passkey.map(|p| {
110            vec![Fido2Credential {
111                credential_id: format!("b64.{}", p.credential_id),
112                key_type: "public-key".to_string(),
113                key_algorithm: "ECDSA".to_string(),
114                key_curve: "P-256".to_string(),
115                key_value: p.key.to_string(),
116                rp_id: p.rp_id.clone(),
117                user_handle: Some(p.user_handle.to_string()),
118                user_name: Some(p.username.clone()),
119                counter: 0,
120                rp_name: Some(p.rp_id.clone()),
121                user_display_name: Some(p.user_display_name.clone()),
122                discoverable: "true".to_string(),
123                creation_date,
124            }]
125        }),
126    };
127
128    (login, fields)
129}
130
131/// Creates a LoginUri from a URL string
132fn create_login_uri(uri: String) -> LoginUri {
133    LoginUri {
134        uri: Some(uri),
135        r#match: None,
136    }
137}
138
139/// Creates URIs from a passkey's rp_id, adding https:// prefix for domain-like strings
140fn passkey_rp_id_to_uri(rp_id: &str) -> LoginUri {
141    let uri = if rp_id.contains('.') && !rp_id.starts_with("http") {
142        format!("https://{rp_id}")
143    } else {
144        rp_id.to_string()
145    };
146    create_login_uri(uri)
147}
148
149/// Converts a `CredentialScope` to a vector of `LoginUri` objects.
150///
151/// This is used for login credentials.
152fn to_uris(scope: &CredentialScope) -> Vec<LoginUri> {
153    let urls = scope.urls.iter().map(|u| create_login_uri(u.clone()));
154
155    let android_apps = scope
156        .android_apps
157        .iter()
158        .map(|a| create_login_uri(format!("{ANDROID_APP_SCHEME}{}", a.bundle_id)));
159
160    urls.chain(android_apps).collect()
161}
162
163/// Converts a `CredentialScope` to a vector of `Field` objects.
164///
165/// This is used for non-login credentials.
166#[allow(unused)]
167pub(super) fn to_fields(scope: &CredentialScope) -> Vec<Field> {
168    let urls = scope.urls.iter().enumerate().map(|(i, u)| Field {
169        name: Some(format!("Url {}", i + 1)),
170        value: Some(u.clone()),
171        r#type: FieldType::Text as u8,
172        linked_id: None,
173    });
174
175    let android_apps = scope.android_apps.iter().enumerate().map(|(i, a)| Field {
176        name: Some(format!("Android App {}", i + 1)),
177        value: Some(a.bundle_id.clone()),
178        r#type: FieldType::Text as u8,
179        linked_id: None,
180    });
181
182    urls.chain(android_apps).collect()
183}
184
185impl From<Login> for BasicAuthCredential {
186    fn from(login: Login) -> Self {
187        BasicAuthCredential {
188            username: login.username.map(|v| v.into()),
189            password: login.password.map(|v| v.into()),
190        }
191    }
192}
193
194impl From<Login> for CredentialScope {
195    fn from(login: Login) -> Self {
196        let (android_uris, urls): (Vec<_>, Vec<_>) = login
197            .login_uris
198            .into_iter()
199            .filter_map(|u| u.uri)
200            .partition(|uri| uri.starts_with(ANDROID_APP_SCHEME));
201
202        let android_apps = android_uris
203            .into_iter()
204            .map(|uri| {
205                let rest = uri.trim_start_matches(ANDROID_APP_SCHEME);
206                AndroidAppIdCredential {
207                    bundle_id: rest.to_string(),
208                    certificate: None,
209                    name: None,
210                }
211            })
212            .collect();
213
214        CredentialScope { urls, android_apps }
215    }
216}
217
218#[derive(Error, Debug)]
219pub enum PasskeyError {
220    #[error("Counter is not zero")]
221    CounterNotZero,
222    #[error(transparent)]
223    InvalidGuid(InvalidGuidError),
224    #[error(transparent)]
225    MissingField(MissingFieldError),
226    #[error("Data isn't base64url encoded")]
227    InvalidBase64(NotB64UrlEncoded),
228}
229
230impl TryFrom<Fido2Credential> for PasskeyCredential {
231    type Error = PasskeyError;
232
233    fn try_from(value: Fido2Credential) -> Result<Self, Self::Error> {
234        if value.counter > 0 {
235            return Err(PasskeyError::CounterNotZero);
236        }
237
238        Ok(PasskeyCredential {
239            credential_id: string_to_guid_bytes(&value.credential_id)
240                .map_err(PasskeyError::InvalidGuid)?
241                .into(),
242            rp_id: value.rp_id,
243            username: value.user_name.unwrap_or_default(),
244            user_display_name: value.user_display_name.unwrap_or_default(),
245            user_handle: value
246                .user_handle
247                .map(|v| B64Url::try_from(v.as_str()))
248                .transpose()
249                .map_err(PasskeyError::InvalidBase64)?
250                .ok_or(PasskeyError::MissingField(MissingFieldError("user_handle")))?,
251            key: B64Url::try_from(value.key_value.as_str()).map_err(PasskeyError::InvalidBase64)?,
252            fido2_extensions: None,
253        })
254    }
255}
256
257#[cfg(test)]
258mod tests {
259    use super::*;
260    use crate::LoginUri;
261
262    #[test]
263    fn test_basic_auth() {
264        let login = Login {
265            username: Some("[email protected]".to_string()),
266            password: Some("asdfasdfasdf".to_string()),
267            login_uris: vec![LoginUri {
268                uri: Some("https://vault.bitwarden.com".to_string()),
269                r#match: None,
270            }],
271            totp: None,
272            fido2_credentials: None,
273        };
274
275        let basic_auth: BasicAuthCredential = login.into();
276
277        let username = basic_auth.username.as_ref().unwrap();
278        assert_eq!(
279            username.value.as_expected().unwrap().0,
280            "[email protected]"
281        );
282        assert!(username.label.is_none());
283
284        let password = basic_auth.password.as_ref().unwrap();
285        assert_eq!(password.value.as_expected().unwrap().0, "asdfasdfasdf");
286        assert!(password.label.is_none());
287    }
288
289    #[test]
290    fn test_credential_scope() {
291        let login = Login {
292            username: None,
293            password: None,
294            login_uris: vec![LoginUri {
295                uri: Some("https://vault.bitwarden.com".to_string()),
296                r#match: None,
297            }],
298            totp: None,
299            fido2_credentials: None,
300        };
301
302        let scope: CredentialScope = login.into();
303
304        assert_eq!(scope.urls, vec!["https://vault.bitwarden.com".to_string()]);
305    }
306
307    #[test]
308    fn test_passkey() {
309        let credential = Fido2Credential {
310            credential_id: "e8d88789-e916-e196-3cbd-81dafae71bbc".to_string(),
311            key_type: "public-key".to_string(),
312            key_algorithm: "ECDSA".to_string(),
313            key_curve: "P-256".to_string(),
314            key_value: "AAECAwQFBg".to_string(),
315            rp_id: "123".to_string(),
316            user_handle: Some("AAECAwQFBg".to_string()),
317            user_name: None,
318            counter: 0,
319            rp_name: None,
320            user_display_name: None,
321            discoverable: "true".to_string(),
322            creation_date: "2024-06-07T14:12:36.150Z".parse().unwrap(),
323        };
324
325        let passkey: PasskeyCredential = credential.try_into().unwrap();
326
327        assert_eq!(passkey.credential_id.to_string(), "6NiHiekW4ZY8vYHa-ucbvA");
328        assert_eq!(passkey.rp_id, "123");
329        assert_eq!(passkey.username, "");
330        assert_eq!(passkey.user_display_name, "");
331        assert_eq!(String::from(passkey.user_handle.clone()), "AAECAwQFBg");
332        assert_eq!(String::from(passkey.key.clone()), "AAECAwQFBg");
333        assert!(passkey.fido2_extensions.is_none());
334    }
335
336    #[test]
337    fn test_to_uris_with_urls_only() {
338        let scope = CredentialScope {
339            urls: vec![
340                "https://vault.bitwarden.com".to_string(),
341                "https://bitwarden.com".to_string(),
342            ],
343            android_apps: vec![],
344        };
345
346        let uris = to_uris(&scope);
347
348        assert_eq!(
349            uris,
350            vec![
351                LoginUri {
352                    uri: Some("https://vault.bitwarden.com".to_string()),
353                    r#match: None
354                },
355                LoginUri {
356                    uri: Some("https://bitwarden.com".to_string()),
357                    r#match: None
358                },
359            ]
360        );
361    }
362
363    #[test]
364    fn test_to_uris_with_android_apps_only() {
365        let scope = CredentialScope {
366            urls: vec![],
367            android_apps: vec![
368                credential_exchange_format::AndroidAppIdCredential {
369                    bundle_id: "com.bitwarden.app".to_string(),
370                    certificate: None,
371                    name: None,
372                },
373                credential_exchange_format::AndroidAppIdCredential {
374                    bundle_id: "com.example.app".to_string(),
375                    certificate: None,
376                    name: None,
377                },
378            ],
379        };
380
381        let uris = to_uris(&scope);
382
383        assert_eq!(
384            uris,
385            vec![
386                LoginUri {
387                    uri: Some("androidapp://com.bitwarden.app".to_string()),
388                    r#match: None
389                },
390                LoginUri {
391                    uri: Some("androidapp://com.example.app".to_string()),
392                    r#match: None
393                },
394            ]
395        );
396    }
397
398    #[test]
399    fn test_to_uris_with_mixed_urls_and_android_apps() {
400        let scope = CredentialScope {
401            urls: vec![
402                "https://vault.bitwarden.com".to_string(),
403                "https://bitwarden.com".to_string(),
404            ],
405            android_apps: vec![
406                credential_exchange_format::AndroidAppIdCredential {
407                    bundle_id: "com.bitwarden.app".to_string(),
408                    certificate: None,
409                    name: None,
410                },
411                credential_exchange_format::AndroidAppIdCredential {
412                    bundle_id: "com.example.app".to_string(),
413                    certificate: None,
414                    name: None,
415                },
416            ],
417        };
418
419        let uris = to_uris(&scope);
420
421        assert_eq!(
422            uris,
423            vec![
424                LoginUri {
425                    uri: Some("https://vault.bitwarden.com".to_string()),
426                    r#match: None
427                },
428                LoginUri {
429                    uri: Some("https://bitwarden.com".to_string()),
430                    r#match: None
431                },
432                LoginUri {
433                    uri: Some("androidapp://com.bitwarden.app".to_string()),
434                    r#match: None
435                },
436                LoginUri {
437                    uri: Some("androidapp://com.example.app".to_string()),
438                    r#match: None
439                },
440            ]
441        );
442    }
443
444    #[test]
445    fn test_to_uris_with_empty_scope() {
446        let scope = CredentialScope {
447            urls: vec![],
448            android_apps: vec![],
449        };
450
451        let uris = to_uris(&scope);
452
453        assert!(uris.is_empty());
454    }
455
456    #[test]
457    fn test_credential_scope_with_android_apps_only() {
458        let login = Login {
459            username: None,
460            password: None,
461            login_uris: vec![
462                LoginUri {
463                    uri: Some("androidapp://com.bitwarden.app".to_string()),
464                    r#match: None,
465                },
466                LoginUri {
467                    uri: Some("androidapp://com.example.app".to_string()),
468                    r#match: None,
469                },
470            ],
471            totp: None,
472            fido2_credentials: None,
473        };
474
475        let scope: CredentialScope = login.into();
476        assert!(scope.urls.is_empty());
477        assert_eq!(scope.android_apps.len(), 2);
478        assert_eq!(scope.android_apps[0].bundle_id, "com.bitwarden.app");
479        assert_eq!(scope.android_apps[1].bundle_id, "com.example.app");
480    }
481
482    #[test]
483    fn test_credential_scope_with_mixed_urls_and_android_apps() {
484        let login = Login {
485            username: None,
486            password: None,
487            login_uris: vec![
488                LoginUri {
489                    uri: Some("https://vault.bitwarden.com".to_string()),
490                    r#match: None,
491                },
492                LoginUri {
493                    uri: Some("androidapp://com.bitwarden.app".to_string()),
494                    r#match: None,
495                },
496                LoginUri {
497                    uri: Some("https://bitwarden.com".to_string()),
498                    r#match: None,
499                },
500                LoginUri {
501                    uri: Some("androidapp://com.example.app".to_string()),
502                    r#match: None,
503                },
504            ],
505            totp: None,
506            fido2_credentials: None,
507        };
508
509        let scope: CredentialScope = login.into();
510        assert_eq!(
511            scope.urls,
512            vec![
513                "https://vault.bitwarden.com".to_string(),
514                "https://bitwarden.com".to_string(),
515            ]
516        );
517        assert_eq!(scope.android_apps.len(), 2);
518        assert_eq!(scope.android_apps[0].bundle_id, "com.bitwarden.app");
519        assert_eq!(scope.android_apps[1].bundle_id, "com.example.app");
520    }
521
522    #[test]
523    fn test_to_fields() {
524        let scope = CredentialScope {
525            urls: vec![
526                "https://vault.bitwarden.com".to_string(),
527                "https://bitwarden.com".to_string(),
528            ],
529            android_apps: vec![
530                credential_exchange_format::AndroidAppIdCredential {
531                    bundle_id: "com.bitwarden.app".to_string(),
532                    certificate: None,
533                    name: None,
534                },
535                credential_exchange_format::AndroidAppIdCredential {
536                    bundle_id: "com.example.app".to_string(),
537                    certificate: None,
538                    name: None,
539                },
540            ],
541        };
542
543        let fields = to_fields(&scope);
544        assert_eq!(
545            fields,
546            vec![
547                Field {
548                    name: Some("Url 1".to_string()),
549                    value: Some("https://vault.bitwarden.com".to_string()),
550                    r#type: FieldType::Text as u8,
551                    linked_id: None,
552                },
553                Field {
554                    name: Some("Url 2".to_string()),
555                    value: Some("https://bitwarden.com".to_string()),
556                    r#type: FieldType::Text as u8,
557                    linked_id: None,
558                },
559                Field {
560                    name: Some("Android App 1".to_string()),
561                    value: Some("com.bitwarden.app".to_string()),
562                    r#type: FieldType::Text as u8,
563                    linked_id: None,
564                },
565                Field {
566                    name: Some("Android App 2".to_string()),
567                    value: Some("com.example.app".to_string()),
568                    r#type: FieldType::Text as u8,
569                    linked_id: None,
570                },
571            ]
572        );
573    }
574
575    // TOTP tests
576    #[test]
577    fn test_totp_credential_to_totp_basic() {
578        let totp = TotpCredential {
579            secret: "Hello World!".as_bytes().to_vec().into(),
580            period: 30,
581            digits: 6,
582            username: Some("[email protected]".to_string()),
583            algorithm: OTPHashAlgorithm::Sha1,
584            issuer: Some("Example".to_string()),
585        };
586
587        let bitwarden_totp = totp_credential_to_totp(&totp);
588        let otpauth = bitwarden_totp.to_string();
589
590        assert!(otpauth.starts_with("otpauth://totp/Example:test%40example%2Ecom?secret="));
591        assert!(otpauth.contains("&issuer=Example"));
592        // Default period (30) and digits (6) and algorithm (SHA1) should not be included
593        assert!(!otpauth.contains("&period=30"));
594        assert!(!otpauth.contains("&digits=6"));
595        assert!(!otpauth.contains("&algorithm=SHA1"));
596    }
597
598    #[test]
599    fn test_totp_credential_to_totp_custom_parameters() {
600        let totp = TotpCredential {
601            secret: "Hello World!".as_bytes().to_vec().into(),
602            period: 60,
603            digits: 8,
604            username: Some("user".to_string()),
605            algorithm: OTPHashAlgorithm::Sha256,
606            issuer: Some("Custom Issuer".to_string()),
607        };
608
609        let bitwarden_totp = totp_credential_to_totp(&totp);
610        let otpauth = bitwarden_totp.to_string();
611
612        assert!(otpauth.contains("Custom%20Issuer:user"));
613        assert!(otpauth.contains("&issuer=Custom%20Issuer"));
614        assert!(otpauth.contains("&period=60"));
615        assert!(otpauth.contains("&digits=8"));
616        assert!(otpauth.contains("&algorithm=SHA256"));
617    }
618
619    // Algorithm conversion tests
620    #[test]
621    fn test_convert_otp_algorithm_sha1() {
622        let result = convert_otp_algorithm(&OTPHashAlgorithm::Sha1);
623        assert_eq!(result, TotpAlgorithm::Sha1);
624    }
625
626    #[test]
627    fn test_convert_otp_algorithm_sha256() {
628        let result = convert_otp_algorithm(&OTPHashAlgorithm::Sha256);
629        assert_eq!(result, TotpAlgorithm::Sha256);
630    }
631
632    #[test]
633    fn test_convert_otp_algorithm_sha512() {
634        let result = convert_otp_algorithm(&OTPHashAlgorithm::Sha512);
635        assert_eq!(result, TotpAlgorithm::Sha512);
636    }
637
638    #[test]
639    fn test_convert_otp_algorithm_steam() {
640        let result = convert_otp_algorithm(&OTPHashAlgorithm::Unknown("steam".to_string()));
641        assert_eq!(result, TotpAlgorithm::Steam);
642    }
643
644    #[test]
645    fn test_convert_otp_algorithm_steam_case_sensitive() {
646        // Test that "steam" is case-sensitive
647        let result = convert_otp_algorithm(&OTPHashAlgorithm::Unknown("Steam".to_string()));
648        assert_eq!(result, TotpAlgorithm::Sha1); // will default to SHA1
649    }
650
651    #[test]
652    fn test_convert_otp_algorithm_unknown_empty() {
653        let result = convert_otp_algorithm(&OTPHashAlgorithm::Unknown("".to_string()));
654        assert_eq!(result, TotpAlgorithm::Sha1); // will default to SHA1
655    }
656
657    #[test]
658    fn test_convert_otp_algorithm_unknown_md5() {
659        // Test an algorithm that might exist in other systems but isn't supported
660        let result = convert_otp_algorithm(&OTPHashAlgorithm::Unknown("md5".to_string()));
661        assert_eq!(result, TotpAlgorithm::Sha1); // will default to SHA1
662    }
663
664    #[test]
665    fn test_convert_otp_algorithm_unknown_whitespace() {
666        // Test steam with whitespace (will not match)
667        let result = convert_otp_algorithm(&OTPHashAlgorithm::Unknown(" steam ".to_string()));
668        assert_eq!(result, TotpAlgorithm::Sha1); // will default to SHA1
669    }
670
671    // Tests for the new helper functions
672    #[test]
673    fn test_passkey_rp_id_to_uri_with_domain() {
674        let uri = passkey_rp_id_to_uri("example.com");
675        assert_eq!(uri.uri, Some("https://example.com".to_string()));
676        assert_eq!(uri.r#match, None);
677    }
678
679    #[test]
680    fn test_passkey_rp_id_to_uri_with_https() {
681        let uri = passkey_rp_id_to_uri("https://example.com");
682        assert_eq!(uri.uri, Some("https://example.com".to_string()));
683        assert_eq!(uri.r#match, None);
684    }
685
686    #[test]
687    fn test_passkey_rp_id_to_uri_without_domain() {
688        let uri = passkey_rp_id_to_uri("localhost");
689        assert_eq!(uri.uri, Some("localhost".to_string()));
690        assert_eq!(uri.r#match, None);
691    }
692
693    #[test]
694    fn test_create_login_uri() {
695        let uri = create_login_uri("https://test.example".to_string());
696        assert_eq!(uri.uri, Some("https://test.example".to_string()));
697        assert_eq!(uri.r#match, None);
698    }
699}