Skip to main content

bitwarden_exporters/cxf/
import.rs

1use chrono::{DateTime, Utc};
2use credential_exchange_format::{
3    Account as CxfAccount, AddressCredential, ApiKeyCredential, BasicAuthCredential, Credential,
4    CreditCardCredential, CustomFieldsCredential, DriversLicenseCredential, EditableField,
5    EditableFieldString, EditableFieldValue, GeneratedPasswordCredential,
6    IdentityDocumentCredential, Item, NoteCredential, PasskeyCredential, PassportCredential,
7    PersonNameCredential, SshKeyCredential, TotpCredential, WifiCredential,
8};
9
10use crate::{
11    CipherType, Field, ImportingCipher, SecureNote, SecureNoteType,
12    cxf::{
13        CxfError,
14        api_key::api_key_to_fields,
15        card::to_card,
16        editable_field::create_field,
17        identity::{
18            address_to_identity, drivers_license_to_identity, identity_document_to_identity,
19            passport_to_identity, person_name_to_identity,
20        },
21        login::to_login,
22        note::extract_note_content,
23        ssh::to_ssh,
24        wifi::wifi_to_fields,
25    },
26};
27
28/**
29 * Parse CXF payload in the format compatible with Apple (At the Account-level)
30 */
31pub(crate) fn parse_cxf(payload: String) -> Result<Vec<ImportingCipher>, CxfError> {
32    let sanitized = sanitize_timestamps(&payload);
33    let account: CxfAccount = serde_json::from_str(&sanitized)?;
34
35    let items: Vec<ImportingCipher> = account.items.into_iter().flat_map(parse_item).collect();
36
37    Ok(items)
38}
39
40/// Replace negative `creationAt` and `modifiedAt` values with null, so that `Utc::now()` will be
41/// used downstream
42///
43/// Some credential managers (e.g., Google Password Manager) export timestamps
44/// as the Windows FILETIME epoch (-11644473600) when no real date exists. The
45/// `credential-exchange-format` crate deserializes these fields as `u64` and
46/// cannot handle negative values.
47pub(crate) fn sanitize_timestamps(payload: &str) -> std::borrow::Cow<'_, str> {
48    let Ok(mut value) = serde_json::from_str::<serde_json::Value>(payload) else {
49        return std::borrow::Cow::Borrowed(payload);
50    };
51
52    let mut modified = false;
53
54    if let Some(items) = value.get_mut("items").and_then(|v| v.as_array_mut()) {
55        for item in items {
56            clamp_timestamps(item, &mut modified);
57        }
58    }
59    if let Some(collections) = value.get_mut("collections").and_then(|v| v.as_array_mut()) {
60        for collection in collections {
61            clamp_collection_timestamps(collection, &mut modified);
62        }
63    }
64
65    if !modified {
66        return std::borrow::Cow::Borrowed(payload);
67    }
68    serde_json::to_string(&value)
69        .map(std::borrow::Cow::Owned)
70        .unwrap_or(std::borrow::Cow::Borrowed(payload))
71}
72
73fn clamp_timestamps(item: &mut serde_json::Value, modified: &mut bool) {
74    for key in ["creationAt", "modifiedAt"] {
75        if item
76            .get(key)
77            .and_then(|v| v.as_i64())
78            .is_some_and(|n| n < 0)
79        {
80            item[key] = serde_json::Value::Null;
81            *modified = true;
82        }
83    }
84}
85
86fn clamp_collection_timestamps(collection: &mut serde_json::Value, modified: &mut bool) {
87    clamp_timestamps(collection, modified);
88    if let Some(subs) = collection
89        .get_mut("subCollections")
90        .and_then(|v| v.as_array_mut())
91    {
92        for sub in subs {
93            clamp_collection_timestamps(sub, modified);
94        }
95    }
96}
97
98/// Convert a CXF timestamp to a [`DateTime<Utc>`].
99///
100/// If the timestamp is None, the current time is used.
101fn convert_date(ts: Option<u64>) -> DateTime<Utc> {
102    ts.and_then(|ts| DateTime::from_timestamp(ts as i64, 0))
103        .unwrap_or(Utc::now())
104}
105
106/// Convert CustomFields credentials to Bitwarden Fields
107/// CustomFields contain arbitrary key-value pairs that should be preserved as custom fields
108fn custom_fields_to_fields(custom_fields: &CustomFieldsCredential) -> Vec<Field> {
109    custom_fields
110        .fields
111        .iter()
112        .map(|field_value| match field_value {
113            EditableFieldValue::String(field) => create_field(field, None::<String>),
114            EditableFieldValue::ConcealedString(field) => create_field(field, None::<String>),
115            EditableFieldValue::Boolean(field) => create_field(field, None::<String>),
116            EditableFieldValue::Date(field) => create_field(field, None::<String>),
117            EditableFieldValue::YearMonth(field) => create_field(field, None::<String>),
118            EditableFieldValue::SubdivisionCode(field) => create_field(field, None::<String>),
119            EditableFieldValue::CountryCode(field) => create_field(field, None::<String>),
120            EditableFieldValue::Email(field) => create_field(field, None::<String>),
121            EditableFieldValue::Number(field) => create_field(field, None::<String>),
122            EditableFieldValue::WifiNetworkSecurityType(field) => {
123                create_field(field, None::<String>)
124            }
125            _ => create_field(
126                &EditableField {
127                    id: None,
128                    label: Some("Unknown Field".to_string()),
129                    value: EditableFieldString("".to_string()).into(),
130                    extensions: None,
131                },
132                None::<String>,
133            ),
134        })
135        .collect()
136}
137
138pub(super) fn parse_item(value: Item) -> Vec<ImportingCipher> {
139    let grouped = group_credentials_by_type(value.credentials);
140
141    let creation_date = convert_date(value.creation_at);
142    let revision_date = convert_date(value.modified_at);
143
144    let mut output = vec![];
145
146    let scope = value.scope.as_ref();
147
148    // Extract note content if present (to be added to parent cipher)
149    let note_content = grouped.note.first().map(extract_note_content);
150
151    // Helper to add ciphers with consistent boilerplate
152    let mut add_item = |t: CipherType, fields: Vec<Field>, fallback_name: Option<String>| {
153        let name = match fallback_name {
154            Some(fallback) if value.title.trim().is_empty() => fallback,
155            _ => value.title.clone(),
156        };
157        output.push(ImportingCipher {
158            folder_id: None, // TODO: Handle folders
159            name,
160            notes: note_content.clone(),
161            r#type: t,
162            favorite: false,
163            reprompt: 0,
164            fields,
165            revision_date,
166            creation_date,
167            deleted_date: None,
168        })
169    };
170
171    // Login credentials
172    if !grouped.basic_auth.is_empty()
173        || !grouped.passkey.is_empty()
174        || !grouped.totp.is_empty()
175        || !grouped.generated_password.is_empty()
176    {
177        let basic_auth = grouped.basic_auth.first();
178        let passkey = grouped.passkey.first();
179        let totp = grouped.totp.first();
180        let generated_password = grouped.generated_password.first();
181
182        let (login, fields) = to_login(
183            creation_date,
184            basic_auth,
185            passkey,
186            totp,
187            generated_password,
188            scope,
189        );
190        add_item(CipherType::Login(Box::new(login)), fields, None);
191    }
192
193    // Credit Card credentials
194    if let Some(credit_card) = grouped.credit_card.first() {
195        let (card, fields) = to_card(credit_card);
196
197        // Use cardholder name as fallback if title is empty
198        let fallback_name = card
199            .cardholder_name
200            .clone()
201            .unwrap_or_else(|| "Untitled Card".to_string());
202
203        add_item(
204            CipherType::Card(Box::new(card)),
205            fields,
206            Some(fallback_name),
207        );
208    }
209
210    // Helper for creating SecureNote cipher type
211    let secure_note_type = || {
212        CipherType::SecureNote(Box::new(SecureNote {
213            r#type: SecureNoteType::Generic,
214        }))
215    };
216
217    // API Key credentials -> Secure Note
218    if let Some(api_key) = grouped.api_key.first() {
219        let fields = api_key_to_fields(api_key);
220        add_item(secure_note_type(), fields, None);
221    }
222
223    // WiFi credentials -> Secure Note
224    if let Some(wifi) = grouped.wifi.first() {
225        let fields = wifi_to_fields(wifi);
226        add_item(secure_note_type(), fields, None);
227    }
228
229    // Identity credentials (address, passport, person name, drivers license, identity document)
230    [
231        grouped
232            .address
233            .first()
234            .map(|a| address_to_identity(a.clone())),
235        grouped
236            .passport
237            .first()
238            .map(|p| passport_to_identity(p.clone())),
239        grouped
240            .person_name
241            .first()
242            .map(|p| person_name_to_identity(p.clone())),
243        grouped
244            .drivers_license
245            .first()
246            .map(|d| drivers_license_to_identity(d.clone())),
247        grouped
248            .identity_document
249            .first()
250            .map(|i| identity_document_to_identity(i.clone())),
251    ]
252    .into_iter()
253    .flatten()
254    .for_each(|(identity, custom_fields)| {
255        add_item(
256            CipherType::Identity(Box::new(identity)),
257            custom_fields,
258            None,
259        );
260    });
261
262    // SSH Key credentials
263    if let Some(ssh) = grouped.ssh.first() {
264        match to_ssh(ssh) {
265            Ok((ssh_key, fields)) => add_item(CipherType::SshKey(Box::new(ssh_key)), fields, None),
266            Err(_) => {
267                // Include information about the failed items, or import as note?
268            }
269        }
270    }
271
272    // After creating all primary ciphers, add custom fields to the first cipher if present
273    // If no ciphers were created, create a standalone SecureNote with custom fields
274    if let Some(custom_fields) = grouped.custom_fields.first() {
275        if let Some(first_cipher) = output.first_mut() {
276            // Append custom fields to the first cipher's fields
277            first_cipher
278                .fields
279                .extend(custom_fields_to_fields(custom_fields));
280        } else {
281            // No ciphers created yet, create standalone custom fields secure note
282            let fields = custom_fields_to_fields(custom_fields);
283            output.push(ImportingCipher {
284                folder_id: None,
285                name: value.title.clone(),
286                notes: note_content.clone(),
287                r#type: secure_note_type(),
288                favorite: false,
289                reprompt: 0,
290                fields,
291                revision_date,
292                creation_date,
293                deleted_date: None,
294            });
295        }
296    }
297
298    // Standalone Note credentials -> Secure Note (only if no other credentials exist)
299    if !grouped.note.is_empty() && output.is_empty() {
300        let standalone_note_content = grouped.note.first().map(extract_note_content);
301        output.push(ImportingCipher {
302            folder_id: None, // TODO: Handle folders
303            name: value.title.clone(),
304            notes: standalone_note_content,
305            r#type: secure_note_type(),
306            favorite: false,
307            reprompt: 0,
308            fields: vec![],
309            revision_date,
310            creation_date,
311            deleted_date: None,
312        });
313    }
314
315    output
316}
317
318/// Group credentials by type.
319///
320/// The Credential Exchange protocol allows multiple identical credentials to be stored in a single
321/// item. Currently we only support one of each type and grouping allows an easy way to fetch the
322/// first of each type. Eventually we should add support for handling multiple credentials of the
323/// same type.
324fn group_credentials_by_type(credentials: Vec<Credential>) -> GroupedCredentials {
325    fn filter_credentials<T>(
326        credentials: &[Credential],
327        f: impl Fn(&Credential) -> Option<&T>,
328    ) -> Vec<T>
329    where
330        T: Clone,
331    {
332        credentials.iter().filter_map(f).cloned().collect()
333    }
334
335    macro_rules! extract_credential {
336        ($field:ident, $variant:path, $type:ty) => {
337            filter_credentials(&credentials, |c| match c {
338                &$variant(ref inner) => Some(inner.as_ref()),
339                _ => None,
340            })
341        };
342    }
343
344    GroupedCredentials {
345        api_key: extract_credential!(api_key, Credential::ApiKey, ApiKeyCredential),
346        basic_auth: extract_credential!(basic_auth, Credential::BasicAuth, BasicAuthCredential),
347        credit_card: extract_credential!(credit_card, Credential::CreditCard, CreditCardCredential),
348        custom_fields: extract_credential!(custom_fields, Credential::CustomFields, CustomFields),
349        generated_password: extract_credential!(
350            generated_password,
351            Credential::GeneratedPassword,
352            GeneratedPasswordCredential
353        ),
354        passkey: extract_credential!(passkey, Credential::Passkey, PasskeyCredential),
355        ssh: extract_credential!(ssh, Credential::SshKey, SshKeyCredential),
356        totp: extract_credential!(totp, Credential::Totp, TotpCredential),
357        wifi: extract_credential!(wifi, Credential::Wifi, WifiCredential),
358        address: extract_credential!(address, Credential::Address, AddressCredential),
359        passport: extract_credential!(passport, Credential::Passport, PassportCredential),
360        person_name: extract_credential!(person_name, Credential::PersonName, PersonNameCredential),
361        drivers_license: extract_credential!(
362            drivers_license,
363            Credential::DriversLicense,
364            DriversLicenseCredential
365        ),
366        identity_document: extract_credential!(
367            identity_document,
368            Credential::IdentityDocument,
369            IdentityDocumentCredential
370        ),
371        note: extract_credential!(note, Credential::Note, NoteCredential),
372    }
373}
374
375struct GroupedCredentials {
376    address: Vec<AddressCredential>,
377    api_key: Vec<ApiKeyCredential>,
378    basic_auth: Vec<BasicAuthCredential>,
379    credit_card: Vec<CreditCardCredential>,
380    custom_fields: Vec<CustomFieldsCredential>,
381    drivers_license: Vec<DriversLicenseCredential>,
382    generated_password: Vec<GeneratedPasswordCredential>,
383    identity_document: Vec<IdentityDocumentCredential>,
384    note: Vec<NoteCredential>,
385    passkey: Vec<PasskeyCredential>,
386    passport: Vec<PassportCredential>,
387    person_name: Vec<PersonNameCredential>,
388    ssh: Vec<SshKeyCredential>,
389    totp: Vec<TotpCredential>,
390    wifi: Vec<WifiCredential>,
391}
392
393#[cfg(test)]
394mod tests {
395    use chrono::{Duration, Month};
396    use credential_exchange_format::{B64Url, CreditCardCredential, EditableFieldYearMonth};
397
398    use super::*;
399
400    /// CustomFields payloads containing `email` and `number` field types should round-trip as
401    /// Text fields with their label and value preserved (previously they fell into a wildcard
402    /// arm that fabricated an "Unknown Field" placeholder with an empty value).
403    #[test]
404    fn test_custom_fields_email_and_number_roundtrip() {
405        use bitwarden_vault::FieldType as BwFieldType;
406
407        let custom_fields: CustomFieldsCredential = serde_json::from_value(serde_json::json!({
408            "fields": [
409                {"fieldType": "email", "value": "[email protected]", "label": "Recovery email"},
410                {"fieldType": "number", "value": "42", "label": "Lucky number"},
411            ],
412            "extensions": [],
413        }))
414        .unwrap();
415
416        let fields = custom_fields_to_fields(&custom_fields);
417
418        assert_eq!(
419            fields,
420            vec![
421                Field {
422                    name: Some("Recovery email".to_string()),
423                    value: Some("[email protected]".to_string()),
424                    r#type: BwFieldType::Text as u8,
425                    linked_id: None,
426                },
427                Field {
428                    name: Some("Lucky number".to_string()),
429                    value: Some("42".to_string()),
430                    r#type: BwFieldType::Text as u8,
431                    linked_id: None,
432                },
433            ]
434        );
435    }
436
437    #[test]
438    fn test_convert_date() {
439        let timestamp: u64 = 1706613834;
440        let datetime = convert_date(Some(timestamp));
441        assert_eq!(
442            datetime,
443            "2024-01-30T11:23:54Z".parse::<DateTime<Utc>>().unwrap()
444        );
445    }
446
447    #[test]
448    fn test_convert_date_none() {
449        let datetime = convert_date(None);
450        assert!(datetime > Utc::now() - Duration::seconds(1));
451        assert!(datetime <= Utc::now());
452    }
453
454    #[test]
455    fn test_parse_empty_item() {
456        let item = Item {
457            id: vec![0, 1, 2, 3, 4, 5, 6].into(),
458            creation_at: Some(1706613834),
459            modified_at: Some(1706623773),
460            title: "Bitwarden".to_string(),
461            subtitle: None,
462            favorite: None,
463            credentials: vec![],
464            tags: None,
465            extensions: None,
466            scope: None,
467        };
468
469        let ciphers: Vec<ImportingCipher> = parse_item(item);
470        assert_eq!(ciphers.len(), 0);
471    }
472
473    #[test]
474    fn test_parse_passkey() {
475        let item = Item {
476            id: B64Url::try_from("Njk1RERENTItNkQ0Ny00NERBLTlFN0EtNDM1MjNEQjYzNjVF")
477                .unwrap(),
478            creation_at: Some(1732181986),
479            modified_at: Some(1732182026),
480            title: "example.com".to_string(),
481            subtitle: None,
482            favorite: None,
483            credentials: vec![Credential::Passkey(Box::new(PasskeyCredential {
484                credential_id: B64Url::try_from("6NiHiekW4ZY8vYHa-ucbvA")
485                    .unwrap(),
486                rp_id: "example.com".to_string(),
487                username: "pj-fry".to_string(),
488                user_display_name: "Philip J. Fry".to_string(),
489                user_handle: B64Url::try_from("YWxleCBtdWxsZXI").unwrap(),
490                key: B64Url::try_from("MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgPzvtWYWmIsvqqr3LsZB0K-cbjuhJSGTGziL1LksHAPShRANCAAT-vqHTyEDS9QBNNi2BNLyu6TunubJT_L3G3i7KLpEDhMD15hi24IjGBH0QylJIrvlT4JN2tdRGF436XGc-VoAl")
491                    .unwrap(),
492                fido2_extensions: None,
493            }))],
494            tags: None,
495            extensions: None,
496            scope: None,
497        };
498
499        let ciphers: Vec<ImportingCipher> = parse_item(item);
500        assert_eq!(ciphers.len(), 1);
501        let cipher = ciphers.first().unwrap();
502
503        assert_eq!(cipher.folder_id, None);
504        assert_eq!(cipher.name, "example.com");
505
506        let login = match &cipher.r#type {
507            CipherType::Login(login) => login,
508            _ => panic!("Expected login"),
509        };
510
511        assert_eq!(login.username, Some("pj-fry".to_string()));
512        assert_eq!(login.password, None);
513        assert_eq!(login.login_uris.len(), 1);
514        assert_eq!(
515            login.login_uris[0].uri,
516            Some("https://example.com".to_string())
517        );
518        assert_eq!(login.totp, None);
519
520        let passkey = login.fido2_credentials.as_ref().unwrap().first().unwrap();
521        assert_eq!(passkey.credential_id, "b64.6NiHiekW4ZY8vYHa-ucbvA");
522        assert_eq!(passkey.key_type, "public-key");
523        assert_eq!(passkey.key_algorithm, "ECDSA");
524        assert_eq!(passkey.key_curve, "P-256");
525        assert_eq!(
526            passkey.key_value,
527            "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgPzvtWYWmIsvqqr3LsZB0K-cbjuhJSGTGziL1LksHAPShRANCAAT-vqHTyEDS9QBNNi2BNLyu6TunubJT_L3G3i7KLpEDhMD15hi24IjGBH0QylJIrvlT4JN2tdRGF436XGc-VoAl"
528        );
529        assert_eq!(passkey.rp_id, "example.com");
530        assert_eq!(
531            passkey.user_handle.as_ref().map(|h| h.to_string()).unwrap(),
532            "YWxleCBtdWxsZXI"
533        );
534        assert_eq!(passkey.user_name, Some("pj-fry".to_string()));
535        assert_eq!(passkey.counter, 0);
536        assert_eq!(passkey.rp_name, Some("example.com".to_string()));
537        assert_eq!(passkey.user_display_name, Some("Philip J. Fry".to_string()));
538        assert_eq!(passkey.discoverable, "true");
539        assert_eq!(
540            passkey.creation_date,
541            "2024-11-21T09:39:46Z".parse::<DateTime<Utc>>().unwrap()
542        );
543    }
544
545    #[test]
546    fn test_passkey_with_basic_auth_and_scope() {
547        use credential_exchange_format::{BasicAuthCredential, CredentialScope};
548
549        let item = Item {
550            id: B64Url::try_from("Njk1RERENTItNkQ0Ny00NERBLTlFN0EtNDM1MjNEQjYzNjVF")
551                .unwrap(),
552            creation_at: Some(1732181986),
553            modified_at: Some(1732182026),
554            title: "Combined Login".to_string(),
555            subtitle: None,
556            favorite: None,
557            credentials: vec![
558                Credential::BasicAuth(Box::new(BasicAuthCredential {
559                    username: Some("basic_username".to_string().into()),
560                    password: Some("basic_password".to_string().into()),
561                })),
562                Credential::Passkey(Box::new(PasskeyCredential {
563                    credential_id: B64Url::try_from("6NiHiekW4ZY8vYHa-ucbvA")
564                        .unwrap(),
565                    rp_id: "passkey-domain.com".to_string(),
566                    username: "passkey_username".to_string(),
567                    user_display_name: "Passkey User".to_string(),
568                    user_handle: B64Url::try_from("YWxleCBtdWxsZXI")
569                        .unwrap(),
570                    key: B64Url::try_from("MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgPzvtWYWmIsvqqr3LsZB0K-cbjuhJSGTGziL1LksHAPShRANCAAT-vqHTyEDS9QBNNi2BNLyu6TunubJT_L3G3i7KLpEDhMD15hi24IjGBH0QylJIrvlT4JN2tdRGF436XGc-VoAl")
571                        .unwrap(),
572                    fido2_extensions: None,
573                }))
574            ],
575            tags: None,
576            extensions: None,
577            scope: Some(CredentialScope {
578                urls: vec!["https://example.com".to_string()],
579                android_apps: vec![],
580            }),
581        };
582
583        let ciphers: Vec<ImportingCipher> = parse_item(item);
584        assert_eq!(ciphers.len(), 1);
585        let cipher = ciphers.first().unwrap();
586
587        let login = match &cipher.r#type {
588            CipherType::Login(login) => login,
589            _ => panic!("Expected login"),
590        };
591
592        // Basic auth username should take priority over passkey username
593        assert_eq!(login.username, Some("basic_username".to_string()));
594        assert_eq!(login.password, Some("basic_password".to_string()));
595
596        // Scope URIs should take priority over passkey rp_id
597        assert_eq!(login.login_uris.len(), 1);
598        assert_eq!(
599            login.login_uris[0].uri,
600            Some("https://example.com".to_string())
601        );
602
603        // Passkey should still be present
604        assert!(login.fido2_credentials.is_some());
605    }
606
607    #[test]
608    fn test_passkey_with_empty_username() {
609        let item = Item {
610            id: B64Url::try_from("Njk1RERENTItNkQ0Ny00NERBLTlFN0EtNDM1MjNEQjYzNjVF").unwrap(),
611            creation_at: Some(1732181986),
612            modified_at: Some(1732182026),
613            title: "Empty Username Passkey".to_string(),
614            subtitle: None,
615            favorite: None,
616            credentials: vec![Credential::Passkey(Box::new(PasskeyCredential {
617                credential_id: B64Url::try_from("6NiHiekW4ZY8vYHa-ucbvA")
618                    .unwrap(),
619                rp_id: "example.com".to_string(),
620                username: "".to_string(),  // Empty username
621                user_display_name: "User Display".to_string(),
622                user_handle: B64Url::try_from("YWxleCBtdWxsZXI")
623                    .unwrap(),
624                key: B64Url::try_from("MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgPzvtWYWmIsvqqr3LsZB0K-cbjuhJSGTGziL1LksHAPShRANCAAT-vqHTyEDS9QBNNi2BNLyu6TunubJT_L3G3i7KLpEDhMD15hi24IjGBH0QylJIrvlT4JN2tdRGF436XGc-VoAl")
625                    .unwrap(),
626                fido2_extensions: None,
627            }))],
628            tags: None,
629            extensions: None,
630            scope: None,
631        };
632
633        let ciphers: Vec<ImportingCipher> = parse_item(item);
634        assert_eq!(ciphers.len(), 1);
635        let cipher = ciphers.first().unwrap();
636
637        let login = match &cipher.r#type {
638            CipherType::Login(login) => login,
639            _ => panic!("Expected login"),
640        };
641
642        // Empty username should not be mapped
643        assert_eq!(login.username, None);
644        assert_eq!(login.password, None);
645
646        // Should still map rp_id to URI
647        assert_eq!(login.login_uris.len(), 1);
648        assert_eq!(
649            login.login_uris[0].uri,
650            Some("https://example.com".to_string())
651        );
652    }
653
654    #[test]
655    fn test_credit_card() {
656        let item = Item {
657            id: vec![0, 1, 2, 3, 4, 5, 6].into(),
658            creation_at: Some(1706613834),
659            modified_at: Some(1706623773),
660            title: "My MasterCard".to_string(),
661            subtitle: None,
662            favorite: None,
663            credentials: vec![Credential::CreditCard(Box::new(CreditCardCredential {
664                number: Some("1234 5678 9012 3456".to_string().into()),
665                full_name: Some("John Doe".to_string().into()),
666                card_type: Some("MasterCard".to_string().into()),
667                verification_number: Some("123".to_string().into()),
668                pin: None,
669                expiry_date: Some(
670                    EditableFieldYearMonth {
671                        year: 2026,
672                        month: Month::January,
673                    }
674                    .into(),
675                ),
676                valid_from: None,
677            }))],
678            tags: None,
679            extensions: None,
680            scope: None,
681        };
682
683        let ciphers: Vec<ImportingCipher> = parse_item(item);
684        assert_eq!(ciphers.len(), 1);
685        let cipher = ciphers.first().unwrap();
686
687        assert_eq!(cipher.folder_id, None);
688        assert_eq!(cipher.name, "My MasterCard");
689
690        let card = match &cipher.r#type {
691            CipherType::Card(card) => card,
692            _ => panic!("Expected card"),
693        };
694
695        assert_eq!(card.cardholder_name, Some("John Doe".to_string()));
696        assert_eq!(card.exp_month, Some("1".to_string()));
697        assert_eq!(card.exp_year, Some("2026".to_string()));
698        assert_eq!(card.code, Some("123".to_string()));
699        assert_eq!(card.brand, Some("Mastercard".to_string()));
700        assert_eq!(card.number, Some("1234 5678 9012 3456".to_string()));
701    }
702
703    #[test]
704    fn test_totp() {
705        use credential_exchange_format::{OTPHashAlgorithm, TotpCredential};
706
707        let item = Item {
708            id: vec![0, 1, 2, 3, 4, 5, 6].into(),
709            creation_at: Some(1706613834),
710            modified_at: Some(1706623773),
711            title: "My TOTP".to_string(),
712            subtitle: None,
713            favorite: None,
714            credentials: vec![Credential::Totp(Box::new(TotpCredential {
715                secret: "Hello World!".as_bytes().to_vec().into(),
716                period: 30,
717                digits: 6,
718                username: Some("[email protected]".to_string()),
719                algorithm: OTPHashAlgorithm::Sha1,
720                issuer: Some("Example Service".to_string()),
721            }))],
722            tags: None,
723            extensions: None,
724            scope: None,
725        };
726
727        let ciphers: Vec<ImportingCipher> = parse_item(item);
728        assert_eq!(ciphers.len(), 1);
729        let cipher = ciphers.first().unwrap();
730
731        assert_eq!(cipher.folder_id, None);
732        assert_eq!(cipher.name, "My TOTP");
733        assert_eq!(cipher.notes, None);
734        assert!(!cipher.favorite);
735        assert_eq!(cipher.reprompt, 0);
736        assert_eq!(cipher.fields, vec![]);
737
738        let login = match &cipher.r#type {
739            CipherType::Login(login) => login,
740            _ => panic!("Expected login cipher for TOTP"),
741        };
742
743        // TOTP should be mapped to login.totp as otpauth URI
744        assert!(login.totp.is_some());
745        let otpauth = login.totp.as_ref().unwrap();
746
747        // Verify the otpauth URI format and content
748        assert!(
749            otpauth.starts_with("otpauth://totp/Example%20Service:test%40example%2Ecom?secret=")
750        );
751        assert!(otpauth.contains("&issuer=Example%20Service"));
752
753        // Default values should not be present in URI
754        assert!(!otpauth.contains("&period=30"));
755        assert!(!otpauth.contains("&digits=6"));
756        assert!(!otpauth.contains("&algorithm=SHA1"));
757
758        // Other login fields should be None since only TOTP was provided
759        assert_eq!(login.username, None);
760        assert_eq!(login.password, None);
761        assert_eq!(login.login_uris, vec![]);
762    }
763
764    #[test]
765    fn test_totp_combined_with_basic_auth() {
766        use credential_exchange_format::{BasicAuthCredential, OTPHashAlgorithm, TotpCredential};
767
768        let item = Item {
769            id: vec![0, 1, 2, 3, 4, 5, 6].into(),
770            creation_at: Some(1706613834),
771            modified_at: Some(1706623773),
772            title: "Login with TOTP".to_string(),
773            subtitle: None,
774            favorite: None,
775            credentials: vec![
776                Credential::BasicAuth(Box::new(BasicAuthCredential {
777                    username: Some("myuser".to_string().into()),
778                    password: Some("mypass".to_string().into()),
779                })),
780                Credential::Totp(Box::new(TotpCredential {
781                    secret: "totpkey".as_bytes().to_vec().into(),
782                    period: 30,
783                    digits: 6,
784                    username: Some("totpuser".to_string()),
785                    algorithm: OTPHashAlgorithm::Sha1,
786                    issuer: Some("Service".to_string()),
787                })),
788            ],
789            tags: None,
790            extensions: None,
791            scope: None,
792        };
793
794        let ciphers: Vec<ImportingCipher> = parse_item(item);
795        assert_eq!(ciphers.len(), 1);
796        let cipher = ciphers.first().unwrap();
797
798        let login = match &cipher.r#type {
799            CipherType::Login(login) => login,
800            _ => panic!("Expected login cipher"),
801        };
802
803        // Should have both basic auth and TOTP
804        assert_eq!(login.username, Some("myuser".to_string()));
805        assert_eq!(login.password, Some("mypass".to_string()));
806        assert!(login.totp.is_some());
807
808        let otpauth = login.totp.as_ref().unwrap();
809        assert!(otpauth.starts_with("otpauth://totp/Service:totpuser?secret="));
810        assert!(otpauth.contains("&issuer=Service"));
811    }
812
813    // Generated password tests
814
815    fn generated_password_item(credentials: Vec<Credential>) -> Item {
816        Item {
817            // Fixed fixture values: the importer doesn't read `Item.id`, and fixed timestamps keep
818            // the tests deterministic.
819            id: uuid::Uuid::default().as_bytes().to_vec().into(),
820            creation_at: Some(1706613834),
821            modified_at: Some(1706623773),
822            title: "Generated Password".to_string(),
823            subtitle: None,
824            favorite: None,
825            credentials,
826            tags: None,
827            extensions: None,
828            scope: None,
829        }
830    }
831
832    fn generated_password(password: &str) -> Credential {
833        Credential::GeneratedPassword(Box::new(GeneratedPasswordCredential {
834            password: password.to_string(),
835        }))
836    }
837
838    fn expect_login(cipher: &ImportingCipher) -> &crate::Login {
839        match &cipher.r#type {
840            CipherType::Login(login) => login,
841            _ => panic!("Expected Login cipher for generated password"),
842        }
843    }
844
845    #[test]
846    fn test_generated_password_only() {
847        let item = generated_password_item(vec![generated_password("fake-generated-pw")]);
848
849        let ciphers: Vec<ImportingCipher> = parse_item(item);
850        assert_eq!(ciphers.len(), 1);
851        let cipher = ciphers.first().unwrap();
852
853        assert_eq!(cipher.name, "Generated Password");
854        assert_eq!(cipher.notes, None);
855        assert_eq!(cipher.fields, vec![]);
856
857        let login = expect_login(cipher);
858        assert_eq!(login.password, Some("fake-generated-pw".to_string()));
859        assert_eq!(login.username, None);
860        assert_eq!(login.login_uris, vec![]);
861        assert_eq!(login.totp, None);
862        assert!(login.fido2_credentials.is_none());
863    }
864
865    #[test]
866    fn test_generated_password_with_note() {
867        let item = generated_password_item(vec![
868            generated_password("fake-generated-pw"),
869            Credential::Note(Box::new(NoteCredential {
870                content: "This note should be added to the login cipher."
871                    .to_string()
872                    .into(),
873            })),
874        ]);
875
876        let ciphers: Vec<ImportingCipher> = parse_item(item);
877        assert_eq!(ciphers.len(), 1); // Login with note content, not an extra SecureNote
878        let cipher = ciphers.first().unwrap();
879
880        assert_eq!(
881            cipher.notes,
882            Some("This note should be added to the login cipher.".to_string())
883        );
884
885        let login = expect_login(cipher);
886        assert_eq!(login.password, Some("fake-generated-pw".to_string()));
887    }
888
889    #[test]
890    fn test_generated_password_with_basic_auth_same_password() {
891        let item = generated_password_item(vec![
892            Credential::BasicAuth(Box::new(BasicAuthCredential {
893                username: Some("fake-user".to_string().into()),
894                password: Some("fake-shared-pw".to_string().into()),
895            })),
896            generated_password("fake-shared-pw"),
897        ]);
898
899        let ciphers: Vec<ImportingCipher> = parse_item(item);
900        assert_eq!(ciphers.len(), 1);
901        let cipher = ciphers.first().unwrap();
902
903        // Identical passwords should not produce a duplicate custom field
904        assert_eq!(cipher.fields, vec![]);
905
906        let login = expect_login(cipher);
907        assert_eq!(login.username, Some("fake-user".to_string()));
908        assert_eq!(login.password, Some("fake-shared-pw".to_string()));
909    }
910
911    #[test]
912    fn test_generated_password_with_basic_auth_different_password() {
913        use bitwarden_vault::FieldType;
914
915        let item = generated_password_item(vec![
916            Credential::BasicAuth(Box::new(BasicAuthCredential {
917                username: Some("fake-user".to_string().into()),
918                password: Some("fake-basic-pw".to_string().into()),
919            })),
920            generated_password("fake-generated-pw"),
921        ]);
922
923        let ciphers: Vec<ImportingCipher> = parse_item(item);
924        assert_eq!(ciphers.len(), 1);
925        let cipher = ciphers.first().unwrap();
926
927        // Basic auth password wins, generated password is preserved as a hidden field
928        let login = expect_login(cipher);
929        assert_eq!(login.username, Some("fake-user".to_string()));
930        assert_eq!(login.password, Some("fake-basic-pw".to_string()));
931
932        assert_eq!(
933            cipher.fields,
934            vec![Field {
935                name: Some("Generated Password".to_string()),
936                value: Some("fake-generated-pw".to_string()),
937                r#type: FieldType::Hidden as u8,
938                linked_id: None,
939            }]
940        );
941    }
942
943    #[test]
944    fn test_generated_password_with_custom_fields() {
945        let item = generated_password_item(vec![
946            generated_password("fake-generated-pw"),
947            Credential::CustomFields(Box::new(CustomFieldsCredential {
948                id: None,
949                label: None,
950                fields: vec![EditableFieldValue::String(EditableField {
951                    id: None,
952                    label: Some("Hint".to_string()),
953                    value: EditableFieldString("fake-hint".to_string()).into(),
954                    extensions: None,
955                })],
956                extensions: vec![],
957            })),
958        ]);
959
960        let ciphers: Vec<ImportingCipher> = parse_item(item);
961        assert_eq!(ciphers.len(), 1); // Custom fields merged into the Login cipher
962        let cipher = ciphers.first().unwrap();
963
964        let login = expect_login(cipher);
965        assert_eq!(login.password, Some("fake-generated-pw".to_string()));
966
967        assert_eq!(cipher.fields.len(), 1);
968        assert_eq!(cipher.fields[0].name, Some("Hint".to_string()));
969        assert_eq!(cipher.fields[0].value, Some("fake-hint".to_string()));
970    }
971
972    #[test]
973    fn test_generated_password_with_totp() {
974        use credential_exchange_format::{OTPHashAlgorithm, TotpCredential};
975
976        let item = generated_password_item(vec![
977            generated_password("fake-generated-pw"),
978            Credential::Totp(Box::new(TotpCredential {
979                secret: "totpkey".as_bytes().to_vec().into(),
980                period: 30,
981                digits: 6,
982                username: Some("totpuser".to_string()),
983                algorithm: OTPHashAlgorithm::Sha1,
984                issuer: Some("Service".to_string()),
985            })),
986        ]);
987
988        let ciphers: Vec<ImportingCipher> = parse_item(item);
989        assert_eq!(ciphers.len(), 1);
990        let cipher = ciphers.first().unwrap();
991
992        assert_eq!(cipher.fields, vec![]);
993
994        let login = expect_login(cipher);
995        assert_eq!(login.password, Some("fake-generated-pw".to_string()));
996        assert!(
997            login
998                .totp
999                .as_ref()
1000                .unwrap()
1001                .starts_with("otpauth://totp/Service:totpuser?secret=")
1002        );
1003    }
1004
1005    #[test]
1006    fn test_generated_password_empty() {
1007        let item = generated_password_item(vec![generated_password("")]);
1008
1009        let ciphers: Vec<ImportingCipher> = parse_item(item);
1010        assert_eq!(ciphers.len(), 1); // The item is kept, titled, as a Login without a password
1011        let cipher = ciphers.first().unwrap();
1012
1013        assert_eq!(cipher.name, "Generated Password");
1014        assert_eq!(cipher.fields, vec![]);
1015
1016        let login = expect_login(cipher);
1017        assert_eq!(login.password, None);
1018        assert_eq!(login.username, None);
1019        assert_eq!(login.login_uris, vec![]);
1020        assert_eq!(login.totp, None);
1021        assert!(login.fido2_credentials.is_none());
1022    }
1023
1024    #[test]
1025    fn test_generated_password_with_passkey() {
1026        let item = generated_password_item(vec![
1027            generated_password("fake-generated-pw"),
1028            Credential::Passkey(Box::new(PasskeyCredential {
1029                credential_id: B64Url::try_from("6NiHiekW4ZY8vYHa-ucbvA").unwrap(),
1030                rp_id: "example.com".to_string(),
1031                username: "fake-user".to_string(),
1032                user_display_name: "Fake User".to_string(),
1033                user_handle: B64Url::try_from("YWxleCBtdWxsZXI").unwrap(),
1034                key: B64Url::try_from("MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgPzvtWYWmIsvqqr3LsZB0K-cbjuhJSGTGziL1LksHAPShRANCAAT-vqHTyEDS9QBNNi2BNLyu6TunubJT_L3G3i7KLpEDhMD15hi24IjGBH0QylJIrvlT4JN2tdRGF436XGc-VoAl")
1035                    .unwrap(),
1036                fido2_extensions: None,
1037            })),
1038        ]);
1039
1040        let ciphers: Vec<ImportingCipher> = parse_item(item);
1041        assert_eq!(ciphers.len(), 1);
1042        let cipher = ciphers.first().unwrap();
1043
1044        assert_eq!(cipher.fields, vec![]);
1045
1046        // The password comes from the generated password; username and URI fall back to the
1047        // passkey.
1048        let login = expect_login(cipher);
1049        assert_eq!(login.password, Some("fake-generated-pw".to_string()));
1050        assert_eq!(login.username, Some("fake-user".to_string()));
1051        assert_eq!(login.login_uris.len(), 1);
1052        assert_eq!(
1053            login.login_uris[0].uri,
1054            Some("https://example.com".to_string())
1055        );
1056
1057        let passkey = login.fido2_credentials.as_ref().unwrap().first().unwrap();
1058        assert_eq!(passkey.credential_id, "b64.6NiHiekW4ZY8vYHa-ucbvA");
1059        assert_eq!(passkey.rp_id, "example.com");
1060    }
1061
1062    // Note integration tests
1063
1064    #[test]
1065    fn test_note_as_part_of_login() {
1066        use credential_exchange_format::{BasicAuthCredential, Credential, Item, NoteCredential};
1067
1068        let item = Item {
1069            id: vec![0, 1, 2, 3, 4, 5, 6].into(),
1070            creation_at: Some(1706613834),
1071            modified_at: Some(1706623773),
1072            title: "Login with Note".to_string(),
1073            subtitle: None,
1074            favorite: None,
1075            credentials: vec![
1076                Credential::BasicAuth(Box::new(BasicAuthCredential {
1077                    username: Some("testuser".to_string().into()),
1078                    password: Some("testpass".to_string().into()),
1079                })),
1080                Credential::Note(Box::new(NoteCredential {
1081                    content: "This note should be added to the login cipher."
1082                        .to_string()
1083                        .into(),
1084                })),
1085            ],
1086            tags: None,
1087            extensions: None,
1088            scope: None,
1089        };
1090
1091        let ciphers: Vec<ImportingCipher> = parse_item(item);
1092        assert_eq!(ciphers.len(), 1); // Should create only one cipher (Login with note content)
1093        let cipher = ciphers.first().unwrap();
1094
1095        assert_eq!(cipher.name, "Login with Note");
1096        assert_eq!(
1097            cipher.notes,
1098            Some("This note should be added to the login cipher.".to_string())
1099        );
1100
1101        match &cipher.r#type {
1102            CipherType::Login(_) => (), // Should be a Login cipher
1103            _ => panic!("Expected Login cipher with note content"),
1104        };
1105    }
1106
1107    #[test]
1108    fn test_note_as_part_of_api_key() {
1109        use credential_exchange_format::{ApiKeyCredential, Credential, Item, NoteCredential};
1110
1111        let item = Item {
1112            id: vec![0, 1, 2, 3, 4, 5, 6].into(),
1113            creation_at: Some(1706613834),
1114            modified_at: Some(1706623773),
1115            title: "API Key with Note".to_string(),
1116            subtitle: None,
1117            favorite: None,
1118            credentials: vec![
1119                Credential::ApiKey(Box::new(ApiKeyCredential {
1120                    key: Some("api-key-12345".to_string().into()),
1121                    username: Some("api-user".to_string().into()),
1122                    key_type: Some("Bearer".to_string().into()),
1123                    url: None,
1124                    valid_from: None,
1125                    expiry_date: None,
1126                })),
1127                Credential::Note(Box::new(NoteCredential {
1128                    content: "This note should be added to the API key cipher."
1129                        .to_string()
1130                        .into(),
1131                })),
1132            ],
1133            tags: None,
1134            extensions: None,
1135            scope: None,
1136        };
1137
1138        let ciphers: Vec<ImportingCipher> = parse_item(item);
1139        assert_eq!(ciphers.len(), 1); // Should create only one cipher (SecureNote with note content)
1140        let cipher = ciphers.first().unwrap();
1141
1142        assert_eq!(cipher.name, "API Key with Note");
1143        assert_eq!(
1144            cipher.notes,
1145            Some("This note should be added to the API key cipher.".to_string())
1146        );
1147
1148        match &cipher.r#type {
1149            CipherType::SecureNote(_) => (), // Should be a SecureNote cipher
1150            _ => panic!("Expected SecureNote cipher with note content"),
1151        };
1152
1153        // Should have API key fields
1154        assert!(!cipher.fields.is_empty());
1155    }
1156
1157    #[test]
1158    fn test_note_as_part_of_credit_card() {
1159        use chrono::Month;
1160        use credential_exchange_format::{Credential, CreditCardCredential, Item, NoteCredential};
1161
1162        let item = Item {
1163            id: vec![0, 1, 2, 3, 4, 5, 6].into(),
1164            creation_at: Some(1706613834),
1165            modified_at: Some(1706623773),
1166            title: "Credit Card with Note".to_string(),
1167            subtitle: None,
1168            favorite: None,
1169            credentials: vec![
1170                Credential::CreditCard(Box::new(CreditCardCredential {
1171                    number: Some("1234 5678 9012 3456".to_string().into()),
1172                    full_name: Some("John Doe".to_string().into()),
1173                    card_type: Some("Visa".to_string().into()),
1174                    verification_number: Some("123".to_string().into()),
1175                    pin: None,
1176                    expiry_date: Some(
1177                        credential_exchange_format::EditableFieldYearMonth {
1178                            year: 2026,
1179                            month: Month::December,
1180                        }
1181                        .into(),
1182                    ),
1183                    valid_from: None,
1184                })),
1185                Credential::Note(Box::new(NoteCredential {
1186                    content: "This note should be added to the credit card cipher."
1187                        .to_string()
1188                        .into(),
1189                })),
1190            ],
1191            tags: None,
1192            extensions: None,
1193            scope: None,
1194        };
1195
1196        let ciphers: Vec<ImportingCipher> = parse_item(item);
1197        assert_eq!(ciphers.len(), 1); // Should create only one cipher (Card with note content)
1198        let cipher = ciphers.first().unwrap();
1199
1200        assert_eq!(cipher.name, "Credit Card with Note");
1201        assert_eq!(
1202            cipher.notes,
1203            Some("This note should be added to the credit card cipher.".to_string())
1204        );
1205
1206        match &cipher.r#type {
1207            CipherType::Card(_) => (), // Should be a Card cipher
1208            _ => panic!("Expected Card cipher with note content"),
1209        };
1210    }
1211
1212    #[test]
1213    fn test_note_as_part_of_wifi() {
1214        use credential_exchange_format::{
1215            Credential, EditableFieldWifiNetworkSecurityType, Item, NoteCredential, WifiCredential,
1216        };
1217
1218        let item = Item {
1219            id: vec![0, 1, 2, 3, 4, 5, 6].into(),
1220            creation_at: Some(1706613834),
1221            modified_at: Some(1706623773),
1222            title: "WiFi with Note".to_string(),
1223            subtitle: None,
1224            favorite: None,
1225            credentials: vec![
1226                Credential::Wifi(Box::new(WifiCredential {
1227                    ssid: Some("MyNetwork".to_string().into()),
1228                    passphrase: Some("password123".to_string().into()),
1229                    network_security_type: Some(
1230                        EditableFieldWifiNetworkSecurityType::Wpa3Personal.into(),
1231                    ),
1232                    hidden: Some(false.into()),
1233                })),
1234                Credential::Note(Box::new(NoteCredential {
1235                    content: "This note should be added to the WiFi cipher."
1236                        .to_string()
1237                        .into(),
1238                })),
1239            ],
1240            tags: None,
1241            extensions: None,
1242            scope: None,
1243        };
1244
1245        let ciphers: Vec<ImportingCipher> = parse_item(item);
1246        assert_eq!(ciphers.len(), 1); // Should create only one cipher (SecureNote with note content)
1247        let cipher = ciphers.first().unwrap();
1248
1249        assert_eq!(cipher.name, "WiFi with Note");
1250        assert_eq!(
1251            cipher.notes,
1252            Some("This note should be added to the WiFi cipher.".to_string())
1253        );
1254
1255        match &cipher.r#type {
1256            CipherType::SecureNote(_) => (), // Should be a SecureNote cipher
1257            _ => panic!("Expected SecureNote cipher with note content"),
1258        };
1259
1260        // Should have WiFi fields
1261        assert!(!cipher.fields.is_empty());
1262    }
1263
1264    #[test]
1265    fn test_credit_card_empty_title_uses_cardholder_name() {
1266        let item = Item {
1267            id: vec![0, 1, 2, 3, 4, 5, 6].into(),
1268            creation_at: Some(1706613834),
1269            modified_at: Some(1706623773),
1270            title: "".to_string(), // Empty title
1271            subtitle: None,
1272            favorite: None,
1273            credentials: vec![Credential::CreditCard(Box::new(CreditCardCredential {
1274                number: Some("1234 5678 9012 3456".to_string().into()),
1275                full_name: Some("Jane Smith".to_string().into()), // Cardholder name
1276                card_type: Some("Visa".to_string().into()),
1277                verification_number: Some("456".to_string().into()),
1278                pin: None,
1279                expiry_date: Some(
1280                    EditableFieldYearMonth {
1281                        year: 2027,
1282                        month: Month::March,
1283                    }
1284                    .into(),
1285                ),
1286                valid_from: None,
1287            }))],
1288            tags: None,
1289            extensions: None,
1290            scope: None,
1291        };
1292
1293        let ciphers: Vec<ImportingCipher> = parse_item(item);
1294        assert_eq!(ciphers.len(), 1);
1295        let cipher = ciphers.first().unwrap();
1296
1297        // Should use cardholder name since title is empty
1298        assert_eq!(cipher.name, "Jane Smith");
1299
1300        let card = match &cipher.r#type {
1301            CipherType::Card(card) => card,
1302            _ => panic!("Expected card"),
1303        };
1304
1305        assert_eq!(card.cardholder_name, Some("Jane Smith".to_string()));
1306    }
1307
1308    #[test]
1309    fn test_credit_card_blank_title_uses_cardholder_name() {
1310        let item = Item {
1311            id: vec![0, 1, 2, 3, 4, 5, 6].into(),
1312            creation_at: Some(1706613834),
1313            modified_at: Some(1706623773),
1314            title: "   ".to_string(), // Blank/whitespace title
1315            subtitle: None,
1316            favorite: None,
1317            credentials: vec![Credential::CreditCard(Box::new(CreditCardCredential {
1318                number: Some("1234 5678 9012 3456".to_string().into()),
1319                full_name: Some("John Doe".to_string().into()),
1320                card_type: Some("Mastercard".to_string().into()),
1321                verification_number: Some("789".to_string().into()),
1322                pin: None,
1323                expiry_date: None,
1324                valid_from: None,
1325            }))],
1326            tags: None,
1327            extensions: None,
1328            scope: None,
1329        };
1330
1331        let ciphers: Vec<ImportingCipher> = parse_item(item);
1332        assert_eq!(ciphers.len(), 1);
1333        let cipher = ciphers.first().unwrap();
1334
1335        // Should use cardholder name since title is just whitespace
1336        assert_eq!(cipher.name, "John Doe");
1337    }
1338
1339    #[test]
1340    fn test_credit_card_empty_title_no_cardholder_uses_fallback() {
1341        let item = Item {
1342            id: vec![0, 1, 2, 3, 4, 5, 6].into(),
1343            creation_at: Some(1706613834),
1344            modified_at: Some(1706623773),
1345            title: "".to_string(), // Empty title
1346            subtitle: None,
1347            favorite: None,
1348            credentials: vec![Credential::CreditCard(Box::new(CreditCardCredential {
1349                number: Some("1234 5678 9012 3456".to_string().into()),
1350                full_name: None, // No cardholder name
1351                card_type: Some("Visa".to_string().into()),
1352                verification_number: Some("123".to_string().into()),
1353                pin: None,
1354                expiry_date: None,
1355                valid_from: None,
1356            }))],
1357            tags: None,
1358            extensions: None,
1359            scope: None,
1360        };
1361
1362        let ciphers: Vec<ImportingCipher> = parse_item(item);
1363        assert_eq!(ciphers.len(), 1);
1364        let cipher = ciphers.first().unwrap();
1365
1366        // Should use fallback since both title and cardholder name are missing
1367        assert_eq!(cipher.name, "Untitled Card");
1368    }
1369
1370    #[test]
1371    fn test_credit_card_with_title_ignores_cardholder_name() {
1372        let item = Item {
1373            id: vec![0, 1, 2, 3, 4, 5, 6].into(),
1374            creation_at: Some(1706613834),
1375            modified_at: Some(1706623773),
1376            title: "My Business Card".to_string(), // Has title
1377            subtitle: None,
1378            favorite: None,
1379            credentials: vec![Credential::CreditCard(Box::new(CreditCardCredential {
1380                number: Some("1234 5678 9012 3456".to_string().into()),
1381                full_name: Some("Jane Smith".to_string().into()),
1382                card_type: Some("Visa".to_string().into()),
1383                verification_number: Some("456".to_string().into()),
1384                pin: None,
1385                expiry_date: None,
1386                valid_from: None,
1387            }))],
1388            tags: None,
1389            extensions: None,
1390            scope: None,
1391        };
1392
1393        let ciphers: Vec<ImportingCipher> = parse_item(item);
1394        assert_eq!(ciphers.len(), 1);
1395        let cipher = ciphers.first().unwrap();
1396
1397        // Should use title since it exists, not cardholder name
1398        assert_eq!(cipher.name, "My Business Card");
1399    }
1400
1401    #[test]
1402    fn test_note_as_part_of_identity() {
1403        use credential_exchange_format::{AddressCredential, Credential, Item, NoteCredential};
1404
1405        let item = Item {
1406            id: vec![0, 1, 2, 3, 4, 5, 6].into(),
1407            creation_at: Some(1706613834),
1408            modified_at: Some(1706623773),
1409            title: "Address with Note".to_string(),
1410            subtitle: None,
1411            favorite: None,
1412            credentials: vec![
1413                Credential::Address(Box::new(AddressCredential {
1414                    street_address: Some("123 Main St".to_string().into()),
1415                    city: Some("Springfield".to_string().into()),
1416                    territory: Some("CA".to_string().into()),
1417                    postal_code: Some("12345".to_string().into()),
1418                    country: Some("US".to_string().into()),
1419                    tel: Some("+1-555-123-4567".to_string().into()),
1420                })),
1421                Credential::Note(Box::new(NoteCredential {
1422                    content: "This note should be added to the address identity cipher."
1423                        .to_string()
1424                        .into(),
1425                })),
1426            ],
1427            tags: None,
1428            extensions: None,
1429            scope: None,
1430        };
1431
1432        let ciphers: Vec<ImportingCipher> = parse_item(item);
1433        assert_eq!(ciphers.len(), 1); // Should create only one cipher (Identity with note content)
1434        let cipher = ciphers.first().unwrap();
1435
1436        assert_eq!(cipher.name, "Address with Note");
1437        assert_eq!(
1438            cipher.notes,
1439            Some("This note should be added to the address identity cipher.".to_string())
1440        );
1441
1442        match &cipher.r#type {
1443            CipherType::Identity(_) => (), // Should be an Identity cipher
1444            _ => panic!("Expected Identity cipher"),
1445        };
1446    }
1447
1448    #[test]
1449    fn test_wifi_with_note_and_custom_fields() {
1450        use bitwarden_vault::FieldType;
1451        use credential_exchange_format::{
1452            Credential, CustomFieldsCredential, EditableFieldValue,
1453            EditableFieldWifiNetworkSecurityType, Item, NoteCredential, WifiCredential,
1454        };
1455
1456        let item = Item {
1457            id: vec![0, 1, 2, 3, 4, 5, 6].into(),
1458            creation_at: Some(1706613834),
1459            modified_at: Some(1706623773),
1460            title: "Wireless Router".to_string(),
1461            subtitle: None,
1462            favorite: None,
1463            credentials: vec![
1464                Credential::Wifi(Box::new(WifiCredential {
1465                    ssid: Some("networker".to_string().into()),
1466                    passphrase: Some("zhc6KLx9CD7Kj2RV9vPF".to_string().into()),
1467                    network_security_type: Some(
1468                        EditableFieldWifiNetworkSecurityType::Wpa3Personal.into(),
1469                    ),
1470                    hidden: None,
1471                })),
1472                Credential::Note(Box::new(NoteCredential {
1473                    content: "My notes heigfkfdkkcmdwkkfkckekfkjf".to_string().into(),
1474                })),
1475                Credential::CustomFields(Box::new(CustomFieldsCredential {
1476                    id: None,
1477                    label: None,
1478                    fields: vec![
1479                        EditableFieldValue::String("My Station".to_string().into()),
1480                        EditableFieldValue::ConcealedString(
1481                            "hf6LW9UMmaxDg4sy6YCv".to_string().into(),
1482                        ),
1483                        EditableFieldValue::String("1.1.1.3".to_string().into()),
1484                        EditableFieldValue::String("".to_string().into()),
1485                        EditableFieldValue::ConcealedString(
1486                            "kJaFcs7KwETkrmnpiQER".to_string().into(),
1487                        ),
1488                    ],
1489                    extensions: vec![],
1490                })),
1491            ],
1492            tags: None,
1493            extensions: None,
1494            scope: None,
1495        };
1496
1497        let ciphers: Vec<ImportingCipher> = parse_item(item);
1498        assert_eq!(ciphers.len(), 1); // Should create only ONE secure note, not two
1499
1500        let cipher = ciphers.first().unwrap();
1501        assert_eq!(cipher.name, "Wireless Router");
1502        assert_eq!(
1503            cipher.notes,
1504            Some("My notes heigfkfdkkcmdwkkfkckekfkjf".to_string())
1505        );
1506
1507        match &cipher.r#type {
1508            CipherType::SecureNote(_) => (), // Should be a SecureNote cipher
1509            _ => panic!("Expected SecureNote cipher"),
1510        };
1511
1512        // Should have both WiFi fields AND custom fields merged together
1513        assert_eq!(cipher.fields.len(), 8); // 3 WiFi fields + 5 custom fields
1514
1515        // Verify WiFi fields are present
1516        assert!(
1517            cipher
1518                .fields
1519                .iter()
1520                .any(|f| f.name.as_deref() == Some("SSID")
1521                    && f.value.as_deref() == Some("networker"))
1522        );
1523        assert!(
1524            cipher
1525                .fields
1526                .iter()
1527                .any(|f| f.name.as_deref() == Some("Passphrase")
1528                    && f.value.as_deref() == Some("zhc6KLx9CD7Kj2RV9vPF")
1529                    && f.r#type == FieldType::Hidden as u8)
1530        );
1531        assert!(
1532            cipher
1533                .fields
1534                .iter()
1535                .any(|f| f.name.as_deref() == Some("Network Security Type")
1536                    && f.value.as_deref() == Some("WPA3 Personal"))
1537        );
1538
1539        // Verify custom fields are present
1540        assert!(
1541            cipher
1542                .fields
1543                .iter()
1544                .any(|f| f.value.as_deref() == Some("My Station"))
1545        );
1546        assert!(
1547            cipher
1548                .fields
1549                .iter()
1550                .any(|f| f.value.as_deref() == Some("hf6LW9UMmaxDg4sy6YCv")
1551                    && f.r#type == FieldType::Hidden as u8)
1552        );
1553        assert!(
1554            cipher
1555                .fields
1556                .iter()
1557                .any(|f| f.value.as_deref() == Some("1.1.1.3"))
1558        );
1559    }
1560}