//! The mandatory vault tests (CLAUDE.md): round-trip, wrong password, tamper, atomic save, //! password change, no secret in Debug/Display. use custos_vault::{ CrashPoint, Error, Field, Item, ItemType, KdfParams, SecretString, Vault, save_atomic, save_atomic_crashing, }; use std::path::Path; /// Cheap parameters so the tamper test can run Argon2 once per byte. Real vaults use `KdfParams::DEFAULT`. const FAST: KdfParams = KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 }; fn pw(s: &str) -> SecretString { SecretString::from(s) } fn sample_vault(password: &str) -> Vault { let mut v = Vault::create(&pw(password), FAST).unwrap(); let mut login = Item::new(ItemType::WebLogin, "GitHub", 1_000); login.set("username", "GitHub.Lantern.47", 1_000); login.set("password", "Orbit7-Fable3-Quartz9-Lumen2", 1_000); login.set("url", "https://github.com", 1_000); login.add_field(Field::text("url", "https://gist.github.com")); login.tags.push("dev".into()); login.set("password", "Second4-Value8-Here1-Now0", 2_000); // one history entry v.add(login); let mut note = Item::new(ItemType::SecureNote, "Česká spořitelna PIN letter", 1_500); note.notes = pw("PIN 1234, keep the envelope"); v.add(note); for kind in ItemType::ALL { v.add(Item::new(kind, &format!("empty {kind:?}"), 3_000)); } v } #[test] fn round_trip_gives_identical_items() { let v = sample_vault("correct horse"); let bytes = v.to_bytes().unwrap(); let back = Vault::open(&bytes, &pw("correct horse")).unwrap(); assert_eq!(back.items(), v.items()); assert_eq!(back.items().len(), 2 + ItemType::ALL.len()); let gh = back.items().iter().find(|i| i.title == "GitHub").unwrap(); assert_eq!(gh.history.len(), 1); assert_eq!(gh.history[0].value.expose(), "Orbit7-Fable3-Quartz9-Lumen2"); assert_eq!(gh.fields.iter().filter(|f| f.name == "url").count(), 2); // Through a file too, and a second save keeps working. let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("a.custos"); v.save(&path).unwrap(); v.save(&path).unwrap(); assert_eq!(Vault::open_file(&path, &pw("correct horse")).unwrap().items(), v.items()); } #[test] fn every_save_uses_a_fresh_nonce() { let v = sample_vault("pw"); assert_ne!(v.to_bytes().unwrap(), v.to_bytes().unwrap()); } #[test] fn wrong_password_fails_clearly_with_no_data() { let bytes = sample_vault("right one").to_bytes().unwrap(); let e = Vault::open(&bytes, &pw("wrong one")).unwrap_err(); assert!(matches!(e, Error::WrongPassword), "{e:?}"); let msg = e.to_string(); assert!(msg.to_lowercase().contains("wrong password"), "{msg}"); assert!(!msg.contains("wrong one") && !msg.contains("right one")); assert!(Vault::open(&bytes, &pw("")).is_err()); } #[test] fn flipping_any_byte_fails_authentication() { let bytes = sample_vault("pw").to_bytes().unwrap(); for i in 0..bytes.len() { for flip in [0x01u8, 0x80] { let mut t = bytes.clone(); t[i] ^= flip; assert!(Vault::open(&t, &pw("pw")).is_err(), "byte {i} ^ {flip:#x} was accepted"); } } // Truncated or extended files fail too. for cut in [0, 5, 9, 100, bytes.len() - 1] { assert!(Vault::open(&bytes[..cut], &pw("pw")).is_err(), "truncated to {cut}"); } let mut longer = bytes.clone(); longer.push(0); assert!(Vault::open(&longer, &pw("pw")).is_err()); } #[test] fn tampered_kdf_params_are_refused_before_argon2_runs() { let bytes = sample_vault("pw").to_bytes().unwrap(); // m_cost sits right after magic(6) version(2) count(1) kind(1) len(2) kdf(1) = offset 13. let mut t = bytes.clone(); t[13..17].copy_from_slice(&u32::MAX.to_le_bytes()); assert!(matches!(Vault::open(&t, &pw("pw")), Err(Error::UnsupportedKdf))); let mut t = bytes; t[17..21].copy_from_slice(&1000u32.to_le_bytes()); // t_cost assert!(matches!(Vault::open(&t, &pw("pw")), Err(Error::UnsupportedKdf))); } #[test] fn not_a_vault_and_future_versions_are_refused() { assert!(matches!(Vault::open(b"hello world, not a vault at all", &pw("x")), Err(Error::NotAVault))); let mut bytes = sample_vault("pw").to_bytes().unwrap(); bytes[6] = 2; assert!(matches!(Vault::open(&bytes, &pw("pw")), Err(Error::UnsupportedVersion(2)))); } fn opens_with(path: &Path, password: &str, title: &str) -> bool { Vault::open_file(path, &pw(password)).map(|v| v.items().iter().any(|i| i.title == title)).unwrap_or(false) } #[test] fn crash_during_save_leaves_original_or_backup_openable() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("home.custos"); let bak = dir.path().join("home.custos.bak"); let mut v = sample_vault("pw"); v.save(&path).unwrap(); v.add(Item::new(ItemType::Wifi, "Second save", 5_000)); v.save(&path).unwrap(); // A normal save keeps the previous version as .bak. assert!(opens_with(&path, "pw", "Second save")); assert!(!opens_with(&bak, "pw", "Second save") && opens_with(&bak, "pw", "GitHub")); v.add(Item::new(ItemType::Card, "Third save", 6_000)); let new_bytes = v.to_bytes().unwrap(); for crash in [CrashPoint::MidTempWrite, CrashPoint::AfterTempWrite, CrashPoint::MidBackup, CrashPoint::AfterBackup] { let e = save_atomic_crashing(&path, &new_bytes, crash).unwrap_err(); assert!(e.to_string().contains("simulated crash"), "{crash:?}: {e}"); // The vault on disk is the last complete save, untouched. assert!(opens_with(&path, "pw", "Second save"), "{crash:?}: original"); assert!(!opens_with(&path, "pw", "Third save"), "{crash:?}: original changed"); // And a backup that opens is always there. assert!(opens_with(&bak, "pw", "GitHub"), "{crash:?}: backup"); } // Leftover temp files do not stop the next save. save_atomic(&path, &new_bytes).unwrap(); assert!(opens_with(&path, "pw", "Third save")); assert!(opens_with(&bak, "pw", "Second save")); } #[test] fn crash_on_first_save_leaves_no_vault_but_no_garbage_either() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("new.custos"); let bytes = sample_vault("pw").to_bytes().unwrap(); save_atomic_crashing(&path, &bytes, CrashPoint::MidTempWrite).unwrap_err(); assert!(!path.exists()); save_atomic(&path, &bytes).unwrap(); assert!(opens_with(&path, "pw", "GitHub")); } #[test] fn password_change_rewraps_the_key_and_keeps_items() { let mut v = sample_vault("old password"); let items_before = v.items().to_vec(); v.change_password(&pw("new password"), FAST).unwrap(); let bytes = v.to_bytes().unwrap(); assert!(matches!(Vault::open(&bytes, &pw("old password")), Err(Error::WrongPassword))); let back = Vault::open(&bytes, &pw("new password")).unwrap(); assert_eq!(back.items(), &items_before[..]); // The vault key itself did not change: only its wrapping did. assert!(back.same_key_as(&v)); } #[test] fn no_secret_in_debug_or_display() { let secret = "Hunter2-Secret9-Value"; let s = pw(secret); for out in [format!("{s:?}"), format!("{s}"), format!("{s:#?}")] { assert!(!out.contains(secret) && out.contains("[redacted]"), "{out}"); } let field = Field::secret("password", secret); let mut item = Item::new(ItemType::WebLogin, "Example", 1); item.set("password", secret, 1); item.set("password", "Another-Secret-Two", 2); item.notes = pw("note Secret-In-Notes"); let vault = { let mut v = Vault::create(&pw("Master-Pass-Word"), FAST).unwrap(); v.add(item.clone()); v }; let outs = [ format!("{field:?}"), format!("{item:?}"), format!("{item:#?}"), format!("{:?}", item.history), format!("{vault:?}"), format!("{:?}", Error::WrongPassword), ]; for out in outs { for leaked in [secret, "Another-Secret-Two", "Secret-In-Notes", "Master-Pass-Word"] { assert!(!out.contains(leaked), "{leaked} leaked in {out}"); } } // Non-secret fields stay readable in Debug, which is what makes it useful. assert!(format!("{item:?}").contains("Example")); } #[test] fn device_wrap_opens_the_same_vault_and_nothing_else() { // Windows Hello gives the desktop app a signature; the core turns it into a key wrap. let v = sample_vault("pw"); let bytes = v.to_bytes().unwrap(); let material = b"signature bytes from the device key"; let blob = v.wrap_for_device(material).unwrap(); assert_ne!(v.wrap_for_device(material).unwrap(), blob, "fresh salt and nonce each time"); let back = Vault::open_with_device(&bytes, &blob, material).unwrap(); assert_eq!(back.items(), v.items()); assert!(matches!(Vault::open_with_device(&bytes, &blob, b"other signature"), Err(Error::DeviceKeyRejected))); for i in 0..blob.len() { let mut t = blob.clone(); t[i] ^= 1; assert!(Vault::open_with_device(&bytes, &t, material).is_err(), "blob byte {i}"); } // A blob made for another vault does not open this one. let other = sample_vault("pw").wrap_for_device(material).unwrap(); assert!(Vault::open_with_device(&bytes, &other, material).is_err()); assert!(!format!("{:?}", Error::DeviceKeyRejected).contains("signature")); }