Skip to main content

vault_core/
cxf.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright the UnENVerse contributors.
3//! FIDO Credential Exchange (CXF) import and export — Phase 24.5.
4//!
5//! CXF (FIDO Alliance) is the JSON format password managers are converging on
6//! for moving credentials between products. This is the one place it is read
7//! or written: `unv-cli` calls it directly, and the desktop app reaches it
8//! over IPC, the same split TOTP import/export already uses and for the same
9//! reason — six formats parsed twice is six chances for the app and the CLI
10//! to disagree about what a file meant.
11//!
12//! # What this is modelled from, and what that means
13//!
14//! Built from the public CXF field tables (`Item`, `Collection`, the
15//! `basic-auth` / `api-key` / `totp` / `note` / `wifi` / `ssh-key` /
16//! `custom-fields` credential shapes) rather than against a corpus of real
17//! exports from other managers — the design's own note said to check which
18//! managers emit a CXF **file** today before building this, and that check is
19//! still outstanding. Treat the shape here as a reasonable-effort reading of
20//! the spec, not a verified interop guarantee, until it has been run against
21//! a real export from at least one other product.
22//!
23//! # The mapping
24//!
25//! An `Item` with **one** credential becomes a plain entry. An `Item` with
26//! **several** becomes a Phase 24.1 bundle: one `secretType: "bundle"` parent
27//! plus one member per non-`custom-fields` credential. CXF custom fields become
28//! the bundle's local variables, so they can participate in scoped templates
29//! rather than appearing as a fake member.
30//!
31//! A `totp` credential never becomes its own entry: it is Phase 22's stored
32//! seed, a field *on* whichever entry the rest of the item produced, matching
33//! how this project already refuses to give TOTP its own `SecretType`.
34//!
35//! Every UnENVerse type without a native CXF shape — the majority of the 26 in
36//! `secret_types` — exports as `custom-fields` carrying an
37//! `_unenverse_type` field, so another manager sees labelled fields and
38//! UnENVerse-to-UnENVerse round-trips losslessly. Import of `custom-fields`
39//! reads `_unenverse_type` back when present and falls back to `extra_vars`
40//! otherwise, so a CXF file honestly written by some other tool still imports
41//! as something rather than being refused.
42
43use serde::{Deserialize, Serialize};
44use serde_json::{json, Value};
45
46// ── The CXF document shape ─────────────────────────────────────────────────
47
48#[derive(Serialize, Deserialize, Default)]
49pub struct CxfDocument {
50    #[serde(default)]
51    pub items: Vec<CxfItem>,
52}
53
54#[derive(Serialize, Deserialize, Default)]
55pub struct CxfItem {
56    pub id: String,
57    pub title: String,
58    #[serde(default, skip_serializing_if = "Option::is_none")]
59    pub subtitle: Option<String>,
60    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
61    pub favorite: bool,
62    #[serde(default, skip_serializing_if = "Vec::is_empty")]
63    pub tags: Vec<String>,
64    #[serde(default, skip_serializing_if = "Option::is_none")]
65    pub scope: Option<CxfScope>,
66    #[serde(default)]
67    pub credentials: Vec<CxfCredential>,
68}
69
70#[derive(Serialize, Deserialize, Default)]
71pub struct CxfScope {
72    #[serde(default, skip_serializing_if = "Vec::is_empty")]
73    pub urls: Vec<String>,
74}
75
76#[derive(Serialize, Deserialize)]
77#[serde(tag = "type", rename_all = "kebab-case")]
78pub enum CxfCredential {
79    BasicAuth {
80        #[serde(default, skip_serializing_if = "Option::is_none")]
81        username: Option<String>,
82        password: String,
83    },
84    ApiKey {
85        key: String,
86        #[serde(default, skip_serializing_if = "Option::is_none")]
87        username: Option<String>,
88        #[serde(default, skip_serializing_if = "Option::is_none")]
89        key_type: Option<String>,
90        #[serde(default, skip_serializing_if = "Option::is_none")]
91        url: Option<String>,
92        #[serde(default, skip_serializing_if = "Option::is_none")]
93        expiry_date: Option<String>,
94    },
95    Totp {
96        secret: String,
97        #[serde(default, skip_serializing_if = "Option::is_none")]
98        issuer: Option<String>,
99        #[serde(default, skip_serializing_if = "Option::is_none")]
100        username: Option<String>,
101        #[serde(default, skip_serializing_if = "Option::is_none")]
102        period: Option<u64>,
103        #[serde(default, skip_serializing_if = "Option::is_none")]
104        digits: Option<u32>,
105        #[serde(default, skip_serializing_if = "Option::is_none")]
106        algorithm: Option<String>,
107    },
108    Note {
109        content: String,
110    },
111    Wifi {
112        ssid: String,
113        #[serde(default, skip_serializing_if = "Option::is_none")]
114        network_security_type: Option<String>,
115        #[serde(default, skip_serializing_if = "Option::is_none")]
116        passphrase: Option<String>,
117        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
118        hidden: bool,
119    },
120    SshKey {
121        private_key: String,
122        #[serde(default, skip_serializing_if = "Option::is_none")]
123        public_key: Option<String>,
124    },
125    #[serde(rename = "custom-fields")]
126    CustomFields {
127        fields: Vec<CxfField>,
128    },
129}
130
131#[derive(Serialize, Deserialize)]
132pub struct CxfField {
133    pub name: String,
134    pub value: String,
135    #[serde(default, skip_serializing_if = "Option::is_none")]
136    pub field_type: Option<String>,
137}
138
139// ── Export: our entries → a CXF document ───────────────────────────────────
140
141fn s(entry: &Value, key: &str) -> Option<String> {
142    entry
143        .get(key)
144        .and_then(|v| v.as_str())
145        .filter(|v| !v.is_empty())
146        .map(str::to_string)
147}
148
149fn has_totp(entry: &Value) -> bool {
150    s(entry, "totp_secret").is_some()
151}
152
153fn totp_credential(entry: &Value) -> CxfCredential {
154    CxfCredential::Totp {
155        secret: s(entry, "totp_secret").unwrap_or_default(),
156        issuer: s(entry, "provider"),
157        username: s(entry, "account_name"),
158        period: entry.get("totp_period").and_then(|v| v.as_u64()),
159        digits: entry
160            .get("totp_digits")
161            .and_then(|v| v.as_u64())
162            .map(|d| d as u32),
163        algorithm: s(entry, "totp_algorithm"),
164    }
165}
166
167/// Every field CXF has no native slot for, as `custom-fields`, tagged with the
168/// UnENVerse type so a re-import (from this program or another UnENVerse
169/// instance) recovers it exactly. This is the fallback every type without a
170/// native mapping below uses, and it is what keeps the export lossless.
171fn custom_fields_credential(entry: &Value) -> CxfCredential {
172    let mut fields = Vec::new();
173    let secret_type = s(entry, "secretType").unwrap_or_else(|| "api_key".to_string());
174    fields.push(CxfField {
175        name: "_unenverse_type".to_string(),
176        value: secret_type,
177        field_type: None,
178    });
179    for key in [
180        "api_key",
181        "api_secret",
182        "api_url",
183        "key_id",
184        "user_agent",
185        "mount_path",
186        "composite_template",
187        "connection_string_note",
188        "description",
189    ] {
190        if let Some(v) = s(entry, key) {
191            fields.push(CxfField {
192                name: key.to_string(),
193                value: v,
194                field_type: None,
195            });
196        }
197    }
198    if let Some(vars) = entry.get("extra_vars").and_then(|v| v.as_array()) {
199        for var in vars {
200            let (Some(key), Some(value)) = (
201                var.get("key").and_then(|v| v.as_str()),
202                var.get("value").and_then(|v| v.as_str()),
203            ) else {
204                continue;
205            };
206            fields.push(CxfField {
207                name: key.to_string(),
208                value: value.to_string(),
209                field_type: None,
210            });
211        }
212    }
213    CxfCredential::CustomFields { fields }
214}
215
216/// CXF has no bundle-level fields; this extension preserves parent locals.
217const BUNDLE_LOCAL_ESCAPE: &str = "__unenverse_local__";
218
219fn encode_bundle_local_name(name: &str) -> String {
220    if name == "_unenverse_type"
221        || name == "_unenverse_bundle"
222        || name.starts_with(BUNDLE_LOCAL_ESCAPE)
223    {
224        format!("{BUNDLE_LOCAL_ESCAPE}{name}")
225    } else {
226        name.to_string()
227    }
228}
229
230fn decode_bundle_local_name(name: &str) -> &str {
231    name.strip_prefix(BUNDLE_LOCAL_ESCAPE).unwrap_or(name)
232}
233
234fn bundle_locals_credential(entry: Option<&Value>) -> CxfCredential {
235    let mut fields = vec![CxfField {
236        name: "_unenverse_bundle".into(),
237        value: "true".into(),
238        field_type: None,
239    }];
240    if let Some(vars) = entry
241        .and_then(|value| value.get("extra_vars"))
242        .and_then(Value::as_array)
243    {
244        fields.extend(vars.iter().filter_map(|var| {
245            Some(CxfField {
246                name: encode_bundle_local_name(var.get("key")?.as_str()?),
247                value: var.get("value")?.as_str()?.to_string(),
248                field_type: None,
249            })
250        }));
251    }
252    CxfCredential::CustomFields { fields }
253}
254
255/// One entry's non-TOTP credential, native where a mapping exists in
256/// `secret_types.json`, `custom-fields` otherwise.
257fn native_credential(entry: &Value) -> CxfCredential {
258    match s(entry, "secretType").as_deref() {
259        Some("password") => CxfCredential::BasicAuth {
260            username: s(entry, "account_name"),
261            password: s(entry, "api_key").unwrap_or_default(),
262        },
263        Some("api_key") | Some("registry_token") | Some("local_service") => CxfCredential::ApiKey {
264            key: s(entry, "api_key").unwrap_or_default(),
265            username: s(entry, "account_name"),
266            key_type: s(entry, "secretType"),
267            url: s(entry, "api_url"),
268            expiry_date: s(entry, "expires_at"),
269        },
270        // A note that carries variables would lose them in a native note, which has only text.
271        Some("secure_note") if has_extra_vars(entry) => custom_fields_credential(entry),
272        Some("secure_note") => CxfCredential::Note {
273            content: s(entry, "description")
274                .or_else(|| s(entry, "api_key"))
275                .unwrap_or_default(),
276        },
277        Some("ssh_key") => CxfCredential::SshKey {
278            private_key: s(entry, "api_key").unwrap_or_default(),
279            public_key: s(entry, "api_secret"),
280        },
281        Some("wifi") => CxfCredential::Wifi {
282            ssid: s(entry, "account_name")
283                .or_else(|| s(entry, "provider"))
284                .unwrap_or_default(),
285            network_security_type: extra_var(entry, "security"),
286            passphrase: s(entry, "api_key"),
287            hidden: extra_var(entry, "hidden").as_deref() == Some("true"),
288        },
289        _ => custom_fields_credential(entry),
290    }
291}
292
293fn has_extra_vars(entry: &Value) -> bool {
294    entry
295        .get("extra_vars")
296        .and_then(|v| v.as_array())
297        .is_some_and(|a| !a.is_empty())
298}
299
300fn extra_var(entry: &Value, key: &str) -> Option<String> {
301    entry
302        .get("extra_vars")
303        .and_then(|v| v.as_array())
304        .and_then(|a| {
305            a.iter()
306                .find(|var| var.get("key").and_then(|v| v.as_str()) == Some(key))
307        })
308        .and_then(|var| var.get("value").and_then(|v| v.as_str()))
309        .map(str::to_string)
310}
311
312fn item_from_entry(entry: &Value) -> CxfItem {
313    let mut credentials = vec![native_credential(entry)];
314    if has_totp(entry) {
315        credentials.push(totp_credential(entry));
316    }
317    let urls = s(entry, "api_url").into_iter().collect::<Vec<_>>();
318    CxfItem {
319        id: s(entry, "id").unwrap_or_default(),
320        title: s(entry, "provider").unwrap_or_default(),
321        subtitle: s(entry, "account_name"),
322        favorite: entry
323            .get("pinned")
324            .and_then(|v| v.as_bool())
325            .unwrap_or(false),
326        tags: entry
327            .get("tags")
328            .and_then(|v| v.as_array())
329            .map(|a| {
330                a.iter()
331                    .filter_map(|t| t.as_str().map(str::to_string))
332                    .collect()
333            })
334            .unwrap_or_default(),
335        scope: if urls.is_empty() {
336            None
337        } else {
338            Some(CxfScope { urls })
339        },
340        credentials,
341    }
342}
343
344/// Builds a CXF document from a slice of entries (`VaultData.api_keys`).
345///
346/// Bundle members (`bundle_id` set) are grouped into one multi-credential
347/// `Item` per bundle; the bundle's own parent entry contributes the item's
348/// title but no credential of its own — a `bundle` entry's payload is its
349/// members, not a value in `api_key`.
350pub fn export(entries: &[Value]) -> CxfDocument {
351    let mut bundles: std::collections::BTreeMap<String, Vec<&Value>> = Default::default();
352    let mut bundle_parents: std::collections::HashMap<String, &Value> = Default::default();
353    let mut standalone = Vec::new();
354
355    for e in entries {
356        if s(e, "secretType").as_deref() == Some("bundle") {
357            if let Some(id) = s(e, "id") {
358                bundle_parents.insert(id.clone(), e);
359                bundles.entry(id).or_default();
360            }
361            continue;
362        }
363        match s(e, "bundle_id") {
364            Some(bid) => bundles.entry(bid).or_default().push(e),
365            None => standalone.push(e),
366        }
367    }
368
369    let mut items: Vec<CxfItem> = standalone.iter().map(|e| item_from_entry(e)).collect();
370    for (bundle_id, members) in bundles {
371        let mut credentials = vec![bundle_locals_credential(
372            bundle_parents.get(&bundle_id).copied(),
373        )];
374        for m in &members {
375            credentials.push(native_credential(m));
376            if has_totp(m) {
377                credentials.push(totp_credential(m));
378            }
379        }
380        items.push(CxfItem {
381            id: bundle_id.clone(),
382            title: bundle_parents
383                .get(&bundle_id)
384                .and_then(|parent| s(parent, "provider"))
385                .unwrap_or_else(|| "Bundle".to_string()),
386            subtitle: None,
387            favorite: false,
388            tags: Vec::new(),
389            scope: None,
390            credentials,
391        });
392    }
393
394    CxfDocument { items }
395}
396
397// ── Import: a CXF document → our entries ───────────────────────────────────
398
399/// One imported entry, or two when an `Item` held several non-TOTP
400/// credentials (a bundle parent plus its members).
401fn entries_from_item(item: &CxfItem, mut new_id: impl FnMut() -> String, now: &str) -> Vec<Value> {
402    let non_totp: Vec<&CxfCredential> = item
403        .credentials
404        .iter()
405        .filter(|c| !matches!(c, CxfCredential::Totp { .. }))
406        .collect();
407    let totp: Option<&CxfCredential> = item
408        .credentials
409        .iter()
410        .find(|c| matches!(c, CxfCredential::Totp { .. }));
411    let is_bundle = non_totp.iter().any(|credential| match credential {
412        CxfCredential::CustomFields { fields } => fields
413            .iter()
414            .any(|field| field.name == "_unenverse_bundle" && field.value == "true"),
415        _ => false,
416    });
417
418    let apply_totp = |entry: &mut Value| {
419        if let Some(CxfCredential::Totp {
420            secret,
421            period,
422            digits,
423            algorithm,
424            ..
425        }) = totp
426        {
427            entry["totp_secret"] = json!(secret);
428            if let Some(p) = period {
429                entry["totp_period"] = json!(p);
430            }
431            if let Some(d) = digits {
432                entry["totp_digits"] = json!(d);
433            }
434            if let Some(a) = algorithm {
435                entry["totp_algorithm"] = json!(a);
436            }
437        }
438    };
439
440    if non_totp.is_empty() {
441        // A TOTP-only item (rare, but the format allows it): a seed with
442        // nowhere else to live, exactly what Phase 22's import produces for
443        // the same case — an entry with an empty primary.
444        let mut entry = base_entry(&new_id(), &item.title, "password", now);
445        apply_totp(&mut entry);
446        return vec![entry];
447    }
448
449    if non_totp.len() == 1 && !is_bundle {
450        let mut entry = entry_from_credential(&new_id(), &item.title, non_totp[0], now);
451        apply_totp(&mut entry);
452        return vec![entry];
453    }
454
455    // Several non-TOTP credentials: a bundle. The TOTP credential (if any)
456    // attaches to the first member — CXF gives no stronger signal for which
457    // login it belongs to, and the alternative is dropping it.
458    let bundle_id = new_id();
459    let mut members = Vec::new();
460    let mut local_vars = Vec::new();
461    for credential in non_totp {
462        match credential {
463            CxfCredential::CustomFields { fields } => local_vars.extend(
464                fields
465                    .iter()
466                    .filter(|field| {
467                        field.name != "_unenverse_type" && field.name != "_unenverse_bundle"
468                    })
469                    .map(|field| {
470                        json!({ "key": decode_bundle_local_name(&field.name), "value": field.value })
471                    }),
472            ),
473            _ => members.push(credential),
474        }
475    }
476    let mut out = vec![json!({
477        "id": bundle_id,
478        "provider": item.title,
479        "api_key": "",
480        "price_type": "free",
481        "secretType": "bundle",
482        "categories": [],
483        "scopes": [],
484        "projectIds": ["Universal"],
485        "extra_vars": local_vars,
486        "created_at": now,
487    })];
488    for (i, cred) in members.iter().enumerate() {
489        let mut member = entry_from_credential(&new_id(), &item.title, cred, now);
490        member["bundle_id"] = json!(bundle_id);
491        member["bundle_slot"] = json!(cxf_credential_kind(cred));
492        member["bundle_order"] = json!((i as i64) * 10);
493        if i == 0 {
494            apply_totp(&mut member);
495        }
496        out.push(member);
497    }
498    out
499}
500
501fn cxf_credential_kind(c: &CxfCredential) -> &'static str {
502    match c {
503        CxfCredential::BasicAuth { .. } => "basic-auth",
504        CxfCredential::ApiKey { .. } => "api-key",
505        CxfCredential::Totp { .. } => "totp",
506        CxfCredential::Note { .. } => "note",
507        CxfCredential::Wifi { .. } => "wifi",
508        CxfCredential::SshKey { .. } => "ssh-key",
509        CxfCredential::CustomFields { .. } => "custom-fields",
510    }
511}
512
513fn base_entry(id: &str, title: &str, secret_type: &str, now: &str) -> Value {
514    json!({
515        "id": id,
516        "provider": title,
517        "api_key": "",
518        "price_type": "free",
519        "secretType": secret_type,
520        "categories": [],
521        "scopes": [],
522        "projectIds": ["Universal"],
523        "extra_vars": [],
524        "created_at": now,
525    })
526}
527
528fn entry_from_credential(id: &str, title: &str, cred: &CxfCredential, now: &str) -> Value {
529    match cred {
530        CxfCredential::BasicAuth { username, password } => {
531            let mut e = base_entry(id, title, "password", now);
532            e["api_key"] = json!(password);
533            if let Some(u) = username {
534                e["account_name"] = json!(u);
535            }
536            e
537        }
538        CxfCredential::ApiKey {
539            key,
540            username,
541            key_type,
542            url,
543            expiry_date,
544        } => {
545            let secret_type = key_type
546                .as_deref()
547                .filter(|t| crate::secret_types::find(t).is_some())
548                .unwrap_or("api_key");
549            let mut e = base_entry(id, title, secret_type, now);
550            e["api_key"] = json!(key);
551            if let Some(u) = username {
552                e["account_name"] = json!(u);
553            }
554            if let Some(u) = url {
555                e["api_url"] = json!(u);
556            }
557            if let Some(x) = expiry_date {
558                e["expires_at"] = json!(x);
559            }
560            e
561        }
562        CxfCredential::Note { content } => {
563            let mut e = base_entry(id, title, "secure_note", now);
564            e["description"] = json!(content);
565            e
566        }
567        CxfCredential::SshKey {
568            private_key,
569            public_key,
570        } => {
571            let mut e = base_entry(id, title, "ssh_key", now);
572            e["api_key"] = json!(private_key);
573            if let Some(p) = public_key {
574                e["api_secret"] = json!(p);
575            }
576            e
577        }
578        CxfCredential::Wifi {
579            ssid,
580            network_security_type,
581            passphrase,
582            hidden,
583        } => {
584            let mut e = base_entry(id, ssid, "wifi", now);
585            e["account_name"] = json!(ssid);
586            if let Some(p) = passphrase {
587                e["api_key"] = json!(p);
588            }
589            let mut vars = vec![];
590            if let Some(sec) = network_security_type {
591                vars.push(json!({ "key": "security", "value": sec }));
592            }
593            if *hidden {
594                vars.push(json!({ "key": "hidden", "value": "true" }));
595            }
596            e["extra_vars"] = json!(vars);
597            e
598        }
599        CxfCredential::CustomFields { fields } => {
600            let unenverse_type = fields
601                .iter()
602                .find(|f| f.name == "_unenverse_type")
603                .map(|f| f.value.as_str())
604                .filter(|t| crate::secret_types::find(t).is_some())
605                .unwrap_or("api_key");
606            let mut e = base_entry(id, title, unenverse_type, now);
607            let mut vars = vec![];
608            for f in fields {
609                if f.name == "_unenverse_type" {
610                    continue;
611                }
612                match f.name.as_str() {
613                    "api_key" | "api_secret" | "api_url" | "key_id" | "user_agent"
614                    | "mount_path" | "composite_template" | "description" => {
615                        e[&f.name] = json!(f.value);
616                    }
617                    _ => vars.push(json!({ "key": f.name, "value": f.value })),
618                }
619            }
620            e["extra_vars"] = json!(vars);
621            e
622        }
623        CxfCredential::Totp { .. } => unreachable!("filtered out before this point"),
624    }
625}
626
627/// Parses and converts a whole document. `new_id`/`now` are injected the way
628/// every other importer in this project injects them — determinism for
629/// tests, and one clock rather than each entry stamping its own.
630pub fn import(doc: &CxfDocument, mut new_id: impl FnMut() -> String, now: &str) -> Vec<Value> {
631    doc.items
632        .iter()
633        .flat_map(|item| entries_from_item(item, &mut new_id, now))
634        .collect()
635}
636
637/// Parses a CXF JSON document from bytes.
638pub fn parse(bytes: &[u8]) -> Result<CxfDocument, String> {
639    serde_json::from_slice(bytes).map_err(|e| format!("Not a readable CXF file: {e}"))
640}
641
642#[cfg(test)]
643mod tests {
644    use super::*;
645
646    fn ids() -> impl FnMut() -> String {
647        let mut n = 0;
648        move || {
649            n += 1;
650            format!("id-{n}")
651        }
652    }
653
654    #[test]
655    fn a_password_entry_round_trips_through_basic_auth() {
656        let entry = json!({
657            "id": "e1", "provider": "GitHub", "account_name": "octocat",
658            "api_key": "hunter2", "secretType": "password",
659        });
660        let doc = export(std::slice::from_ref(&entry));
661        assert_eq!(doc.items.len(), 1);
662        let imported = import(&doc, ids(), "2026-01-01T00:00:00Z");
663        assert_eq!(imported.len(), 1);
664        assert_eq!(imported[0]["provider"], "GitHub");
665        assert_eq!(imported[0]["account_name"], "octocat");
666        assert_eq!(imported[0]["api_key"], "hunter2");
667        assert_eq!(imported[0]["secretType"], "password");
668    }
669
670    #[test]
671    fn a_totp_seed_attaches_to_its_entry_rather_than_becoming_one() {
672        let entry = json!({
673            "id": "e1", "provider": "GitHub", "api_key": "hunter2",
674            "secretType": "password", "totp_secret": "JBSWY3DPEHPK3PXP",
675        });
676        let doc = export(std::slice::from_ref(&entry));
677        assert_eq!(doc.items[0].credentials.len(), 2);
678        let imported = import(&doc, ids(), "2026-01-01T00:00:00Z");
679        assert_eq!(imported.len(), 1, "the seed must not become its own entry");
680        assert_eq!(imported[0]["totp_secret"], "JBSWY3DPEHPK3PXP");
681    }
682
683    #[test]
684    fn a_type_with_no_native_mapping_round_trips_through_custom_fields() {
685        let entry = json!({
686            "id": "e1", "provider": "Postgres", "secretType": "database",
687            "api_key": "postgres://…", "extra_vars": [
688                { "key": "host", "value": "db.internal" },
689            ],
690        });
691        let doc = export(std::slice::from_ref(&entry));
692        match &doc.items[0].credentials[0] {
693            CxfCredential::CustomFields { fields } => {
694                assert!(fields
695                    .iter()
696                    .any(|f| f.name == "_unenverse_type" && f.value == "database"));
697            }
698            _ => panic!("expected custom-fields"),
699        }
700        let imported = import(&doc, ids(), "2026-01-01T00:00:00Z");
701        assert_eq!(imported[0]["secretType"], "database");
702        assert_eq!(imported[0]["api_key"], "postgres://…");
703        let vars = imported[0]["extra_vars"].as_array().unwrap();
704        assert!(vars
705            .iter()
706            .any(|v| v["key"] == "host" && v["value"] == "db.internal"));
707    }
708
709    #[test]
710    fn several_credentials_on_one_item_import_as_a_bundle() {
711        let doc = CxfDocument {
712            items: vec![CxfItem {
713                id: "item-1".into(),
714                title: "Spotify".into(),
715                subtitle: None,
716                favorite: false,
717                tags: vec![],
718                scope: None,
719                credentials: vec![
720                    CxfCredential::BasicAuth {
721                        username: Some("me".into()),
722                        password: "pw".into(),
723                    },
724                    CxfCredential::ApiKey {
725                        key: "client-secret".into(),
726                        username: None,
727                        key_type: Some("api_key".into()),
728                        url: None,
729                        expiry_date: None,
730                    },
731                ],
732            }],
733        };
734        let imported = import(&doc, ids(), "2026-01-01T00:00:00Z");
735        assert_eq!(imported.len(), 3, "one bundle parent + two members");
736        assert_eq!(imported[0]["secretType"], "bundle");
737        assert_eq!(imported[1]["bundle_id"], imported[0]["id"]);
738        assert_eq!(imported[2]["bundle_id"], imported[0]["id"]);
739    }
740
741    #[test]
742    fn cxf_custom_fields_become_bundle_locals_not_a_member() {
743        let doc = CxfDocument {
744            items: vec![CxfItem {
745                id: "item-1".into(),
746                title: "Discord bot".into(),
747                subtitle: None,
748                favorite: false,
749                tags: vec![],
750                scope: None,
751                credentials: vec![
752                    CxfCredential::ApiKey {
753                        key: "bot-token".into(),
754                        username: None,
755                        key_type: Some("api_key".into()),
756                        url: None,
757                        expiry_date: None,
758                    },
759                    CxfCredential::CustomFields {
760                        fields: vec![
761                            CxfField {
762                                name: "application_id".into(),
763                                value: "9007199254740993".into(),
764                                field_type: Some("text".into()),
765                            },
766                            CxfField {
767                                name: "_unenverse_type".into(),
768                                value: "api_key".into(),
769                                field_type: None,
770                            },
771                        ],
772                    },
773                ],
774            }],
775        };
776        let imported = import(&doc, ids(), "2026-01-01T00:00:00Z");
777        assert_eq!(imported.len(), 2, "bundle parent plus actual credential");
778        assert_eq!(imported[0]["secretType"], "bundle");
779        assert_eq!(imported[0]["extra_vars"][0]["key"], "application_id");
780        assert_eq!(imported[0]["extra_vars"][0]["value"], "9007199254740993");
781        assert_eq!(imported[1]["bundle_id"], imported[0]["id"]);
782    }
783
784    #[test]
785    fn parsing_junk_bytes_refuses_rather_than_panics() {
786        assert!(parse(b"{not json").is_err());
787    }
788
789    #[test]
790    fn exporting_a_bundle_and_reimporting_keeps_membership() {
791        let bundle = json!({
792            "id": "b1", "provider": "Spotify", "secretType": "bundle",
793            "extra_vars": [{ "key": "region", "value": "eu-west" }],
794        });
795        let m1 = json!({
796            "id": "m1", "provider": "Spotify", "secretType": "password",
797            "api_key": "pw", "bundle_id": "b1",
798        });
799        let m2 = json!({
800            "id": "m2", "provider": "Spotify", "secretType": "api_key",
801            "api_key": "sk", "bundle_id": "b1",
802        });
803        let doc = export(&[bundle, m1, m2]);
804        assert_eq!(doc.items.len(), 1);
805        assert_eq!(doc.items[0].credentials.len(), 3);
806        let imported = import(&doc, ids(), "2026-01-01T00:00:00Z");
807        assert_eq!(imported.len(), 3);
808        assert_eq!(imported[0]["extra_vars"][0]["key"], "region");
809        assert_eq!(imported[0]["extra_vars"][0]["value"], "eu-west");
810    }
811
812    #[test]
813    fn empty_bundle_with_locals_round_trips_as_a_bundle() {
814        let bundle = json!({
815            "id": "b1", "provider": "Discord", "secretType": "bundle",
816            "extra_vars": [
817                { "key": "guild_id", "value": "123" },
818                { "key": "_unenverse_bundle", "value": "true" },
819            ],
820        });
821        let doc = export(&[bundle]);
822        assert_eq!(doc.items[0].credentials.len(), 1);
823        let imported = import(&doc, ids(), "2026-01-01T00:00:00Z");
824        assert_eq!(imported.len(), 1);
825        assert_eq!(imported[0]["secretType"], "bundle");
826        assert_eq!(imported[0]["extra_vars"][0]["key"], "guild_id");
827        assert_eq!(imported[0]["extra_vars"][1]["key"], "_unenverse_bundle");
828        assert_eq!(imported[0]["extra_vars"][1]["value"], "true");
829    }
830}