//! Custos items ↔ KeePass entries (docs/KDBX.md, "Mapping"). use custos_kdbx::{ AutoType, Cipher, Database, Entry, Group, Kdf, Key, SecretBytes, SecretString, StringField, Times, WriteOptions, from_items, read, to_items, write, }; use custos_vault::{Attachment, Field, Item, ItemType}; const FAST: WriteOptions = WriteOptions { cipher: Cipher::ChaCha20, kdf: Kdf::Argon2id { m_kib: 64, t: 1, p: 1 } }; const T: i64 = 1_790_000_000_000; // whole seconds: KeePass keeps seconds fn through_a_file(items: &[Item]) -> Vec { let p = SecretString::from("pw"); let key = Key { password: Some(&p), key_file: None }; let bytes = write(&from_items(items, "Custos"), &key, FAST).unwrap(); to_items(&read(&bytes, &key).unwrap()) } fn every_type() -> Vec { let mut login = Item::new(ItemType::WebLogin, "GitHub", T); login.set("username", "alice", T); login.set("password", "First-Pass-1", T); login.set("password", "Second-Pass-2", T + 1000); login.set("password", "Current-Pass-3", T + 2000); login.set("url", "https://github.com", T); login.set("totp", "JBSWY3DPEHPK3PXP", T); login.set("autotype-match", "*GitHub*", T); login.set("autotype-sequence", "{USERNAME}{TAB}{PASSWORD}{ENTER}", T); login.add_field(Field::text("url", "https://gist.github.com")); login.add_field(Field::text("url", "https://api.github.com")); login.add_field(Field::secret("Recovery code", "Recovery-1234")); login.add_field(Field::text("Account", "")); login.add_field(Field::text("expires", "2031-06-30T12:00:00Z")); login.add_field(Field::text("autotype-match", "Firefox - GitHub")); login.tags = vec!["dev".into(), "work".into()]; login.notes = "line one\r\nline & \"three\"".into(); login.folder = vec!["Internet".into(), "Code".into()]; login.modified = T + 2000; let mut api = Item::new(ItemType::ApiCredential, "Stripe", T); for (k, v) in [("service", "Stripe"), ("key-id", "pk_live_1"), ("secret", "sk-Old"), ("endpoint", "https://api.stripe.com")] { api.set(k, v, T); } api.set("secret", "sk-New", T + 5000); api.set("expires", "2027-01-31", T); let mut app = Item::new(ItemType::LocalApp, "Backup tool", T); for (k, v) in [("target", "restic"), ("username", "backup"), ("password", "Restic-Pass")] { app.set(k, v, T); } let mut wifi = Item::new(ItemType::Wifi, "Home", T); for (k, v) in [("ssid", "Domi"), ("password", "Wifi-Pass"), ("security", "WPA"), ("hidden", "false")] { wifi.set(k, v, T); } let mut note = Item::new(ItemType::SecureNote, "Keys", T); note.notes = "the spare key is with the neighbours".into(); note.attachments = vec![Attachment { name: "id_ed25519".into(), data: SecretBytes::from(&b"\x00\xffkey bytes"[..]) }]; note.folder = vec!["Home".into()]; let mut card = Item::new(ItemType::Card, "Visa", T); for (k, v) in [ ("cardholder", "A N Other"), ("number", "4111111111111111"), ("expiry", "12/29"), ("cvv", "123"), ("pin", "0000"), ] { card.set(k, v, T); } // Two secret fields changed at the same moment: one KeePass snapshot. card.set("number", "4000000000000002", T + 9000); card.set("cvv", "456", T + 9000); let mut pair = Item::new(ItemType::KeyPair, "Signing key", T); for (k, v) in [ ("algorithm", "ed25519"), ("public-key", "ssh-ed25519 AAAA… me"), ("private-key", "-----BEGIN PRIVATE KEY-----\nMC4…\n-----END PRIVATE KEY-----\n"), ] { pair.set(k, v, T); } let empty: Vec = ItemType::ALL.into_iter().map(|k| Item::new(k, &format!("empty {k:?}"), T)).collect(); [vec![login, api, app, wifi, note, card, pair], empty].concat() } #[test] fn every_item_type_survives_export_and_import() { let items = every_type(); let back = through_a_file(&items); assert_eq!(back.len(), items.len()); // Items come back folder by folder (root first), so match them by id. for a in &items { let b = back.iter().find(|b| b.id == a.id).unwrap_or_else(|| panic!("{} is missing", a.title)); assert_eq!(a, b, "{}", a.title); for (fa, fb) in a.fields.iter().zip(&b.fields) { assert_eq!(fa.value, fb.value, "{} / {}", a.title, fa.name); } assert_eq!(a.notes, b.notes, "{}", a.title); } } #[test] fn the_export_looks_like_keepass_to_keepassxc() { let db = from_items(&every_type(), "Custos"); let internet = db.root.groups.iter().find(|g| g.name == "Internet").unwrap(); let gh = &internet.groups[0].entries[0]; assert_eq!(internet.groups[0].name, "Code"); let get = |e: &Entry, k: &str| e.get(k).map(|v| v.expose().to_owned()); assert_eq!(get(gh, "UserName").as_deref(), Some("alice")); assert_eq!(get(gh, "URL").as_deref(), Some("https://github.com")); assert_eq!(get(gh, "KP2A_URL").as_deref(), Some("https://gist.github.com")); assert_eq!(get(gh, "KP2A_URL_1").as_deref(), Some("https://api.github.com")); assert_eq!(get(gh, "otp").as_deref(), Some("JBSWY3DPEHPK3PXP")); assert!(gh.strings.iter().find(|s| s.key == "Password").unwrap().protected); assert!(gh.strings.iter().find(|s| s.key == "Recovery code").unwrap().protected); assert!(gh.get("custos-type").is_none(), "a login looks like a login without help"); assert_eq!(gh.times.expires, custos_kdbx::parse_iso("2031-06-30T12:00:00Z")); assert_eq!(gh.autotype.windows, ["*GitHub*", "Firefox - GitHub"]); // Two password changes: two snapshots, oldest first, each with the password it had then. let old: Vec = gh.history.iter().map(|h| h.get("Password").unwrap().expose().to_owned()).collect(); assert_eq!(old, ["First-Pass-1", "Second-Pass-2"]); let entry = |title: &str| { fn find<'a>(g: &'a Group, t: &str) -> Option<&'a Entry> { g.entries .iter() .find(|e| e.get("Title").unwrap().expose() == t) .or_else(|| g.groups.iter().find_map(|s| find(s, t))) } find(&db.root, title).unwrap() }; let api = entry("Stripe"); assert_eq!(api.get("custos-type").unwrap().expose(), "api-credential"); assert_eq!(api.get("Password").unwrap().expose(), "sk-New"); assert_eq!(api.times.expires, custos_kdbx::parse_iso("2027-01-31")); let card = entry("Visa"); assert_eq!(card.get("UserName").unwrap().expose(), "A N Other"); assert_eq!(card.get("Password").unwrap().expose(), "4000000000000002"); assert!(card.strings.iter().find(|s| s.key == "cvv").unwrap().protected); assert_eq!(card.history.len(), 1, "both changes in one snapshot"); assert_eq!(card.history[0].get("cvv").unwrap().expose(), "123"); assert_eq!(card.history[0].get("Password").unwrap().expose(), "4111111111111111"); assert_eq!(entry("Home").get("UserName").unwrap().expose(), "Domi", "Wi-Fi: SSID as the user name"); assert!(entry("Keys").get("custos-type").is_none(), "a note looks like a note"); // Empty template fields stay out; Custos's own type and template names come back as custom strings. assert!(entry("empty ApiCredential").get("key-id").is_none()); } fn s(key: &str, value: &str, protected: bool) -> StringField { StringField { key: key.into(), value: value.into(), protected } } #[test] fn a_keepass_database_maps_as_the_table_says() { let entry = |n: u8, strings: Vec| Entry { uuid: [n; 16], strings, times: Times { created: 1_700_000_000, modified: 1_700_000_500, expires: None }, ..Default::default() }; let mut login = entry( 1, vec![ s("Notes", "n", false), s("KP2A_URL_2", "https://three.example", false), s("KP2A_URL", "https://two.example", false), s("Password", "Now-1", true), s("PIN", "9999", true), s("Title", "Bank", false), s("TOTP Seed", "JBSW Y3DP EHPK 3PXP", true), s("URL", "https://one.example", false), s("UserName", "me", false), ], ); login.tags = vec!["money".into(), "important".into()]; login.autotype = AutoType { default_sequence: "{PASSWORD}{ENTER}".into(), windows: vec![] }; // Snapshots: the PIN changed first, then the password; the last one changed nothing secret. login.history = vec![ entry(1, vec![s("Title", "Bank", false), s("Password", "Old-1", true), s("PIN", "1111", true)]), entry(1, vec![s("Title", "Bank", false), s("Password", "Old-1", true), s("PIN", "9999", true)]), entry(1, vec![s("Title", "Bank renamed", false), s("Password", "Now-1", true), s("PIN", "9999", true)]), ]; for (i, h) in login.history.iter_mut().enumerate() { h.times.modified = 1_700_000_100 + i as i64 * 100; } let only_custom = entry(2, vec![s("Title", "Licence", false), s("Licence key", "ABCD-EFGH", true)]); let binned = entry(3, vec![s("Title", "Deleted", false), s("Password", "x", true)]); let db = Database { name: "KeePass".into(), root: Group { uuid: [9; 16], name: "Root".into(), entries: vec![only_custom], groups: vec![ Group { uuid: [8; 16], name: "Banking".into(), entries: vec![login], groups: vec![] }, Group { uuid: [7; 16], name: "Recycle Bin".into(), entries: vec![binned], groups: vec![] }, ], }, recycle_bin: Some([7; 16]), }; let items = to_items(&db); assert_eq!(items.len(), 2, "nothing from the recycle bin"); let licence = &items[0]; assert_eq!(licence.kind, ItemType::SecureNote); assert_eq!(licence.fields, [Field::secret("Licence key", "ABCD-EFGH")]); let bank = &items[1]; assert_eq!(bank.kind, ItemType::WebLogin); assert_eq!(bank.id, "01".repeat(16)); assert_eq!(bank.folder, ["Banking"]); assert_eq!(bank.tags, ["money", "important"]); let f = |name: &str| bank.fields.iter().filter(|f| f.name == name).map(|f| f.value.expose()).collect::>(); assert_eq!(f("url"), ["https://one.example", "https://two.example", "https://three.example"]); assert_eq!(f("totp"), ["JBSWY3DPEHPK3PXP"], "default settings: the bare seed, spaces removed"); assert_eq!(f("PIN"), ["9999"]); assert_eq!(f("autotype-sequence"), ["{PASSWORD}{ENTER}"]); let h: Vec<(&str, &str, i64)> = bank.history.iter().map(|h| (h.field.as_str(), h.value.expose(), h.changed)).collect(); assert_eq!(h, [("PIN", "1111", 1_700_000_100_000), ("password", "Old-1", 1_700_000_200_000)]); assert_eq!(bank.created, 1_700_000_000_000); assert_eq!(bank.modified, 1_700_000_500_000); } #[test] fn field_names_keepass_reserves_are_renamed_not_lost() { let mut item = Item::new(ItemType::WebLogin, "Odd", T); item.add_field(Field::text("Title", "a field called Title")); item.add_field(Field::secret("custos-type", "not a type")); item.add_field(Field::text("KP2A_URL", "not a URL")); let db = from_items(&[item], "x"); let e = &db.root.entries[0]; assert_eq!(e.get("Title").unwrap().expose(), "Odd"); assert_eq!(e.get("Title (2)").unwrap().expose(), "a field called Title"); assert_eq!(e.get("custos-type (2)").unwrap().expose(), "not a type"); assert_eq!(e.get("KP2A_URL (2)").unwrap().expose(), "not a URL"); let keys: Vec<&str> = e.strings.iter().map(|s| s.key.as_str()).collect(); let mut unique = keys.clone(); unique.sort(); unique.dedup(); assert_eq!(keys.len(), unique.len(), "keys are unique: {keys:?}"); } #[test] fn ids_survive_and_bad_ids_get_a_fresh_uuid() { let mut a = Item::new(ItemType::SecureNote, "a", T); a.id = "00112233445566778899aabbccddeeff".into(); let mut b = Item::new(ItemType::SecureNote, "b", T); b.id = "not hex".into(); let db = from_items(&[a, b], "x"); assert_eq!( db.root.entries[0].uuid, [0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff] ); assert_ne!(db.root.entries[1].uuid, [0; 16]); }