//! What these hold is the one promise the secrets surface makes: a value goes //! IN and never comes back out. Every other assertion here is in service of //! that — the refusal when there is no vault, the hint's four characters, the //! replace-rather-than-duplicate rule, and the absence of `value_enc` from //! every answer any tool can produce. use std::sync::Arc; use chrono::{DateTime, Utc}; use cotton_core::vault::seal::Vmk; use serde_json::{json, Map, Value}; use crate::mcp::dispatch::{call_tool, ToolServices}; use crate::rails::{SealedSecret, VaultRail}; const WORKSPACE: &str = "00000000-0000-4000-8000-00000000ffee"; const OWNER: &str = "00000000-0000-4000-8000-0000000000dd"; const DEVICE: &str = "device:iphone-secrets"; const NOW: &str = "2026-09-09T10:00:00.000Z"; /// The REAL seal, under a key this test minted. /// /// Not a double: the thing being asserted is that a value is sealed and never /// answered, and a double that returned `enc(x)` would prove the second half /// while quietly excusing the first. Minting a key costs 32 bytes. #[derive(Debug)] struct TestVault { vmk: Vmk, version: u32, } impl TestVault { fn at(version: u32) -> TestVault { TestVault { vmk: Vmk::mint(), version, } } } impl VaultRail for TestVault { fn seal(&self, secret_id: &str, payload: &[u8]) -> Option { Some(SealedSecret { value_enc: cotton_core::vault::seal(&self.vmk, secret_id, self.version, payload)?, vmk_version: self.version, }) } fn open(&self, secret_id: &str, vmk_version: u32, sealed: &str) -> Option> { cotton_core::vault::open(&self.vmk, secret_id, vmk_version, sealed) } } /// A vault that refuses. A build can hold one and still fail on the day; the /// answer is a refusal, never the plaintext. #[derive(Debug)] struct BrokenVault; impl VaultRail for BrokenVault { fn seal(&self, _secret_id: &str, _payload: &[u8]) -> Option { None } fn open(&self, _secret_id: &str, _vmk_version: u32, _sealed: &str) -> Option> { None } } pub(crate) fn fixture() -> cotton_store::driver::Driver { let db = cotton_store::test_template::create_workspace_in_memory_for_test(&cotton_store::meta::Meta { workspace_id: WORKSPACE.to_string(), owner_id: OWNER.to_string(), device_id: "device:secrets-fixture".to_string(), last_server_seq: 0, last_hlc: None, }) .expect("a fresh file"); db.run( "INSERT INTO cotton_workspaces (id, name, owner_user_id, created_at, _hlc) VALUES (?, ?, \ ?, ?, '')", &[ rusqlite::types::Value::Text(WORKSPACE.to_string()), rusqlite::types::Value::Text("Secrets fixture".to_string()), rusqlite::types::Value::Text(OWNER.to_string()), rusqlite::types::Value::Text(NOW.to_string()), ], ) .expect("the workspace row every domain table keys back to"); db } pub(crate) fn services(vault: Option>) -> ToolServices { ToolServices { vault, ..ToolServices::none() } } /// The file every context here is in, as `read_file_identity` would read it. static FILE: std::sync::LazyLock = std::sync::LazyLock::new(|| cotton_store::file_identity::FileIdentity::for_tests(WORKSPACE)); pub(crate) fn ctx<'a>( db: &'a cotton_store::driver::Driver, services: &'a ToolServices, ) -> crate::mcp::dispatch::Ctx<'a> { let now = NOW.parse::>().expect("a fixed instant"); // The owner at the test device: its row is seeded once, and the actor // names it (a write is asked by an actor the file knows). let row_id = format!("row-{DEVICE}"); db.run( "INSERT OR IGNORE INTO cotton_devices (id, workspace_id, device_id, name, approved_at, \ approved_by_device, created_at, updated_at) VALUES (?, ?, ?, 'Test phone', ?, 'self', ?, ?)", &[ rusqlite::types::Value::Text(row_id.clone()), rusqlite::types::Value::Text(WORKSPACE.to_string()), rusqlite::types::Value::Text(DEVICE.to_string()), rusqlite::types::Value::Text(NOW.to_string()), rusqlite::types::Value::Text(NOW.to_string()), rusqlite::types::Value::Text(NOW.to_string()), ], ) .expect("the device's row"); let actor = cotton_store::actor::Actor::Owner( cotton_store::actor::DeviceId::in_file(db, &row_id).expect("the row names the device"), ); crate::mcp::dispatch::Ctx::phone( db, &FILE, OWNER, DEVICE, actor, cotton_store::mint::Held::Replica, now, Arc::new(crate::random::SystemRandom), services, ) } fn args(pairs: &[(&str, &str)]) -> Map { let mut map = Map::new(); for (key, value) in pairs { map.insert((*key).to_string(), Value::from(*value)); } map } fn stored_count(db: &cotton_store::driver::Driver) -> i64 { db.get("SELECT count(*) AS n FROM cotton_secrets", &[]) .expect("the table is readable") .expect("a count") .int("n") .unwrap_or(-1) } #[test] fn a_stored_secret_answers_with_a_hint_and_never_with_the_value() { let db = fixture(); let services = services(Some(Arc::new(TestVault::at(1)))); let mut ctx = ctx(&db, &services); let stored = call_tool( &mut ctx, "create_secret", &args(&[ ("name", "My key"), ("service", "anthropic"), ("value", "sk-ant-secret-value-4f2a"), ]), ) .expect("the key is stored"); assert_eq!(stored["hint"], Value::from("4f2a")); assert_eq!(stored["service"], Value::from("anthropic")); assert_eq!(stored["kind"], Value::from("api_key")); // The tool it was HANDED to does not hand it back. let text = stored.to_string(); assert!(!text.contains("sk-ant-secret-value-4f2a"), "{text}"); assert!(!text.contains("value_enc"), "{text}"); let listed = call_tool(&mut ctx, "list_secrets", &Map::new()).expect("the list answers"); let text = listed.to_string(); assert!(!text.contains("sk-ant-secret-value-4f2a"), "{text}"); assert!(!text.contains("value_enc"), "{text}"); assert!(!text.contains("v2:"), "not even the ciphertext: {text}"); assert_eq!(listed["secrets"][0]["hint"], Value::from("4f2a")); assert_eq!(listed["secrets"][0]["isSet"], Value::Bool(true)); } #[test] fn the_sealed_payload_is_what_lands_on_disk_and_the_plaintext_is_not() { let db = fixture(); let services = services(Some(Arc::new(TestVault::at(3)))); let mut ctx = ctx(&db, &services); call_tool( &mut ctx, "create_secret", &args(&[ ("name", "My key"), ("service", "anthropic"), ("value", "plaintext-key"), ]), ) .expect("the key is stored"); let row = db .get("SELECT value_enc, hint, vmk_version, kind FROM cotton_secrets", &[]) .expect("the table is readable") .expect("one row"); let sealed = row.text("value_enc").expect("a sealed value").to_string(); assert!(sealed.starts_with("v2:"), "{sealed}"); assert!(!sealed.contains("plaintext-key"), "{sealed}"); assert_eq!(row.text("hint"), Some("-key")); assert_eq!(row.int("vmk_version"), Some(3), "the row names the key that sealed it"); assert_eq!(row.text("kind"), Some("api_key")); } #[test] fn a_build_with_no_vault_refuses_by_name_rather_than_storing_the_plaintext() { let db = fixture(); // The phone's shape: `ToolServices::none()` carries no vault. let services = services(None); let mut ctx = ctx(&db, &services); let refusal = call_tool( &mut ctx, "create_secret", &args(&[ ("name", "My key"), ("service", "anthropic"), ("value", "plaintext-key"), ]), ) .expect_err("a build with no vault cannot store a secret"); assert!(refusal.message().contains("vault_unavailable"), "{refusal}"); assert_eq!(stored_count(&db), 0, "a refused write must write nothing"); } #[test] fn a_vault_that_refuses_is_a_refusal_and_never_a_fallback() { let db = fixture(); let services = services(Some(Arc::new(BrokenVault))); let mut ctx = ctx(&db, &services); let refusal = call_tool( &mut ctx, "create_secret", &args(&[ ("name", "My key"), ("service", "anthropic"), ("value", "plaintext-key"), ]), ) .expect_err("a vault that refuses stops the write"); assert!(refusal.message().contains("Nothing was written"), "{refusal}"); assert_eq!(stored_count(&db), 0); } #[test] fn re_pasting_a_key_replaces_the_value_rather_than_minting_a_second_row() { let db = fixture(); let services = services(Some(Arc::new(TestVault::at(1)))); let mut ctx = ctx(&db, &services); let first = call_tool( &mut ctx, "create_secret", &args(&[ ("name", "My key"), ("service", "anthropic"), ("value", "old-aaaa"), ]), ) .expect("stored"); let second = call_tool( &mut ctx, "create_secret", &args(&[ ("name", "My key"), ("service", "anthropic"), ("value", "new-bbbb"), ]), ) .expect("re-stored"); // The same row, the new value: two live keys under one name is a question // nothing in this system can answer. assert_eq!(first["id"], second["id"]); assert_eq!(second["hint"], Value::from("bbbb")); assert_eq!(stored_count(&db), 1); } #[test] fn two_logins_of_one_name_are_two_rows_because_a_login_has_no_service() { let db = fixture(); let services = services(Some(Arc::new(TestVault::at(1)))); let mut ctx = ctx(&db, &services); for (username, password) in [("one@example.invalid", "aaaa"), ("two@example.invalid", "bbbb")] { call_tool( &mut ctx, "create_secret", &args(&[ ("kind", "login"), ("name", "Gmail"), ("username", username), ("site", "https://mail.example.invalid"), ("value", password), ]), ) .expect("stored"); } assert_eq!(stored_count(&db), 2, "a person has two Gmail logins"); } #[test] fn a_typed_payload_seals_every_field_and_hints_from_the_primary_one() { let db = fixture(); let vault = Arc::new(TestVault::at(1)); let services = services(Some(vault.clone())); let mut ctx = ctx(&db, &services); let stored = call_tool( &mut ctx, "create_secret", &{ let mut map = Map::new(); map.insert("kind".to_string(), json!("card")); map.insert("name".to_string(), json!("Everyday card")); map.insert( "fields".to_string(), json!({"number": "4000000000009999", "holder": "Wren Ashgrove", "expiry": "07/31", "cvv": "123"}), ); map }, ) .expect("the card is stored"); assert_eq!(stored["hint"], Value::from("9999")); let row = db .get("SELECT id, value_enc, vmk_version FROM cotton_secrets", &[]) .expect("readable") .expect("one row"); let id = row.text("id").expect("an id").to_string(); let sealed = row.text("value_enc").expect("sealed").to_string(); // Every field is inside, and NONE of them is on the row. let opened = vault .open(&id, row.int("vmk_version").unwrap_or_default() as u32, &sealed) .expect("the vault opens what it sealed"); let payload: cotton_core::vault::SecretPayload = serde_json::from_slice(&opened).expect("a typed payload"); assert_eq!( payload, cotton_core::vault::SecretPayload::Card { number: "4000000000009999".to_string(), holder: Some("Wren Ashgrove".to_string()), expiry: Some("07/31".to_string()), cvv: Some("123".to_string()), notes: None, } ); } #[test] fn a_payload_sealed_for_one_row_cannot_be_opened_as_another_s() { let db = fixture(); let vault = Arc::new(TestVault::at(1)); let services = services(Some(vault.clone())); let mut ctx = ctx(&db, &services); let stored = call_tool( &mut ctx, "create_secret", &args(&[("name", "k"), ("service", "anthropic"), ("value", "aaaa")]), ) .expect("stored"); let id = stored["id"].as_str().expect("an id").to_string(); let sealed = db .get("SELECT value_enc FROM cotton_secrets", &[]) .expect("readable") .expect("one row") .text("value_enc") .expect("sealed") .to_string(); assert!(vault.open(&id, 1, &sealed).is_some()); assert!( vault.open("00000000-0000-4000-8000-000000000001", 1, &sealed).is_none(), "the row id is the seal's associated data" ); assert!(vault.open(&id, 2, &sealed).is_none(), "so is the key version"); } #[test] fn passing_both_a_value_and_fields_is_refused_rather_than_having_one_win() { let db = fixture(); let services = services(Some(Arc::new(TestVault::at(1)))); let mut ctx = ctx(&db, &services); let mut asked = Map::new(); asked.insert("kind".to_string(), json!("login")); asked.insert("name".to_string(), json!("Gmail")); asked.insert("value".to_string(), json!("aaaa")); asked.insert("fields".to_string(), json!({"password": "bbbb"})); let refusal = call_tool(&mut ctx, "create_secret", &asked).expect_err("ambiguous"); assert!(refusal.message().contains("not both"), "{refusal}"); assert_eq!(stored_count(&db), 0); } #[test] fn fields_that_are_not_the_kind_s_payload_are_refused_with_the_fields_named() { let db = fixture(); let services = services(Some(Arc::new(TestVault::at(1)))); let mut ctx = ctx(&db, &services); let mut asked = Map::new(); asked.insert("kind".to_string(), json!("card")); asked.insert("name".to_string(), json!("Everyday card")); // No `number`, which is a card's primary field. asked.insert("fields".to_string(), json!({"holder": "Wren Ashgrove"})); let refusal = call_tool(&mut ctx, "create_secret", &asked).expect_err("not a card"); assert!(refusal.message().contains("number"), "{refusal}"); } #[test] fn a_kind_that_does_not_exist_is_refused_with_every_kind_named() { let db = fixture(); let services = services(Some(Arc::new(TestVault::at(1)))); let mut ctx = ctx(&db, &services); let refusal = call_tool( &mut ctx, "create_secret", &args(&[("kind", "passport"), ("name", "k"), ("value", "v")]), ) .expect_err("there is no such kind"); assert!(refusal.message().contains("identity"), "{refusal}"); } #[test] fn a_service_the_column_would_refuse_is_refused_with_a_sentence_instead() { let db = fixture(); let services = services(Some(Arc::new(TestVault::at(1)))); let mut ctx = ctx(&db, &services); for bad in ["Anthropic", "my service", "-leading"] { let refusal = call_tool( &mut ctx, "create_secret", &args(&[("name", "k"), ("service", bad), ("value", "v")]), ) .expect_err("the service is refused"); // A CHECK's own message says nothing a model could correct itself from. assert!( refusal.message().contains("service") || refusal.message().contains("required"), "{bad}: {refusal}" ); } } #[test] fn an_api_key_with_no_service_is_refused_because_nothing_could_find_it_again() { let db = fixture(); let services = services(Some(Arc::new(TestVault::at(1)))); let mut ctx = ctx(&db, &services); let refusal = call_tool( &mut ctx, "create_secret", &args(&[("name", "My key"), ("value", "aaaa")]), ) .expect_err("an api key is found by service"); assert!(refusal.message().contains("service"), "{refusal}"); } #[test] fn an_empty_value_is_a_refusal_and_not_a_stored_blank() { let db = fixture(); let services = services(Some(Arc::new(TestVault::at(1)))); let mut ctx = ctx(&db, &services); let refusal = call_tool( &mut ctx, "create_secret", &args(&[("name", "k"), ("service", "anthropic"), ("value", "")]), ) .expect_err("an empty credential is not a credential"); assert!(refusal.message().contains("empty"), "{refusal}"); } // ── update ────────────────────────────────────────────────────────────────── #[test] fn update_secret_changes_the_metadata_and_leaves_the_payload_alone() { let db = fixture(); let services = services(Some(Arc::new(TestVault::at(1)))); let mut ctx = ctx(&db, &services); let stored = call_tool( &mut ctx, "create_secret", &args(&[ ("kind", "login"), ("name", "Gmial"), ("value", "secret-aaaa"), ]), ) .expect("stored"); let id = stored["id"].as_str().expect("an id").to_string(); let before = db .get("SELECT value_enc FROM cotton_secrets", &[]) .expect("readable") .expect("one row") .text("value_enc") .expect("sealed") .to_string(); let changed = call_tool( &mut ctx, "update_secret", &args(&[ ("id", &id), ("name", "Gmail"), ("site", "https://mail.example.invalid"), ("username", "wren@example.invalid"), ]), ) .expect("renamed"); assert_eq!(changed["name"], Value::from("Gmail")); assert_eq!(changed["site"], Value::from("https://mail.example.invalid")); // The hint is the row's own, unchanged — and still not the value. assert_eq!(changed["hint"], Value::from("aaaa")); let after = db .get("SELECT value_enc FROM cotton_secrets", &[]) .expect("readable") .expect("one row") .text("value_enc") .expect("sealed") .to_string(); assert_eq!(before, after, "a rename must not re-seal"); } #[test] fn update_secret_re_seals_when_a_payload_is_passed_and_never_answers_it() { let db = fixture(); let services = services(Some(Arc::new(TestVault::at(1)))); let mut ctx = ctx(&db, &services); let stored = call_tool( &mut ctx, "create_secret", &args(&[("kind", "login"), ("name", "Gmail"), ("value", "old-aaaa")]), ) .expect("stored"); let id = stored["id"].as_str().expect("an id").to_string(); let mut asked = Map::new(); asked.insert("id".to_string(), json!(id)); asked.insert( "fields".to_string(), json!({"password": "new-bbbb", "notes": "changed today"}), ); let changed = call_tool(&mut ctx, "update_secret", &asked).expect("re-sealed"); assert_eq!(changed["hint"], Value::from("bbbb")); let text = changed.to_string(); assert!(!text.contains("new-bbbb"), "{text}"); assert!(!text.contains("changed today"), "{text}"); } #[test] fn update_secret_with_a_payload_and_no_vault_refuses_by_name() { let db = fixture(); let sealed_services = services(Some(Arc::new(TestVault::at(1)))); let mut sealing = ctx(&db, &sealed_services); let stored = call_tool( &mut sealing, "create_secret", &args(&[("kind", "note"), ("name", "Studio wifi"), ("value", "aaaa")]), ) .expect("stored"); let id = stored["id"].as_str().expect("an id").to_string(); drop(sealing); let no_vault = services(None); let mut ctx = ctx(&db, &no_vault); let mut asked = Map::new(); asked.insert("id".to_string(), json!(id)); asked.insert("fields".to_string(), json!({"body": "bbbb"})); let refusal = call_tool(&mut ctx, "update_secret", &asked).expect_err("no vault"); assert!(refusal.message().contains("vault_unavailable"), "{refusal}"); // A RENAME still works without one: naming what you hold is not a secret. assert!(call_tool( &mut ctx, "update_secret", &args(&[("id", &id), ("name", "Studio wi-fi")]) ) .is_ok()); } #[test] fn update_secret_on_a_row_that_is_not_there_refuses_by_id() { let db = fixture(); let services = services(Some(Arc::new(TestVault::at(1)))); let mut ctx = ctx(&db, &services); let refusal = call_tool( &mut ctx, "update_secret", &args(&[ ("id", "00000000-0000-4000-8000-0000000000aa"), ("name", "anything"), ]), ) .expect_err("no such secret"); assert!(refusal.message().contains("no secret with id"), "{refusal}"); } #[test] fn update_secret_with_nothing_to_change_says_so_rather_than_answering_ok() { let db = fixture(); let services = services(Some(Arc::new(TestVault::at(1)))); let mut ctx = ctx(&db, &services); let stored = call_tool( &mut ctx, "create_secret", &args(&[("name", "k"), ("service", "anthropic"), ("value", "aaaa")]), ) .expect("stored"); let id = stored["id"].as_str().expect("an id").to_string(); let refusal = call_tool(&mut ctx, "update_secret", &args(&[("id", &id)])) .expect_err("a no-op is not an update"); assert!(refusal.message().contains("nothing to change"), "{refusal}"); } // ── the bin ───────────────────────────────────────────────────────────────── #[test] fn deleting_a_secret_moves_it_to_the_bin_rather_than_erasing_it() { let db = fixture(); let services = services(Some(Arc::new(TestVault::at(1)))); let mut ctx = ctx(&db, &services); let stored = call_tool( &mut ctx, "create_secret", &args(&[ ("name", "My key"), ("service", "anthropic"), ("value", "aaaa"), ]), ) .expect("stored"); let id = stored["id"].as_str().expect("an id").to_string(); let gone = call_tool(&mut ctx, "delete_secret", &args(&[("id", &id)])).expect("binned"); assert_eq!(gone["binned"], Value::Bool(true)); assert_eq!(gone["name"], Value::from("My key")); // The row is STILL THERE — being wrong must cost a tap, not a credential. assert_eq!(stored_count(&db), 1); let listed = call_tool(&mut ctx, "list_secrets", &Map::new()).expect("the list answers"); assert_eq!( listed["secrets"].as_array().map(Vec::len), Some(0), "a binned password must not read as one the person still has" ); } #[test] fn the_kind_generic_bin_lists_a_binned_secret_and_restores_it() { let db = fixture(); let services = services(Some(Arc::new(TestVault::at(1)))); let mut ctx = ctx(&db, &services); let stored = call_tool( &mut ctx, "create_secret", &args(&[("kind", "login"), ("name", "Gmail"), ("value", "aaaa")]), ) .expect("stored"); let id = stored["id"].as_str().expect("an id").to_string(); call_tool(&mut ctx, "delete_secret", &args(&[("id", &id)])).expect("binned"); let bin = call_tool(&mut ctx, "list_bin", &args(&[("kind", "secret")])).expect("the bin lists"); let text = bin.to_string(); assert!(text.contains("Gmail"), "{text}"); assert!(!text.contains("aaaa"), "the bin shows a NAME, never a value: {text}"); call_tool( &mut ctx, "restore_from_bin", &args(&[("kind", "secret"), ("id", &id)]), ) .expect("restored"); let listed = call_tool(&mut ctx, "list_secrets", &Map::new()).expect("the list answers"); assert_eq!(listed["secrets"].as_array().map(Vec::len), Some(1)); } #[test] fn emptying_the_bin_erases_a_binned_secret_for_good() { let db = fixture(); let services = services(Some(Arc::new(TestVault::at(1)))); let mut ctx = ctx(&db, &services); let stored = call_tool( &mut ctx, "create_secret", &args(&[("kind", "note"), ("name", "Old note"), ("value", "aaaa")]), ) .expect("stored"); let id = stored["id"].as_str().expect("an id").to_string(); call_tool(&mut ctx, "delete_secret", &args(&[("id", &id)])).expect("binned"); call_tool(&mut ctx, "empty_bin", &args(&[("kind", "secret")])).expect("emptied"); assert_eq!(stored_count(&db), 0, "empty_bin alone erases"); } #[test] fn re_pasting_a_binned_key_brings_it_back() { let db = fixture(); let services = services(Some(Arc::new(TestVault::at(1)))); let mut ctx = ctx(&db, &services); let first = call_tool( &mut ctx, "create_secret", &args(&[("name", "k"), ("service", "anthropic"), ("value", "aaaa")]), ) .expect("stored"); let id = first["id"].as_str().expect("an id").to_string(); call_tool(&mut ctx, "delete_secret", &args(&[("id", &id)])).expect("binned"); let again = call_tool( &mut ctx, "create_secret", &args(&[("name", "k"), ("service", "anthropic"), ("value", "bbbb")]), ) .expect("re-pasted"); assert_eq!(again["id"], Value::from(id)); let listed = call_tool(&mut ctx, "list_secrets", &Map::new()).expect("listed"); assert_eq!(listed["secrets"].as_array().map(Vec::len), Some(1)); } // ── the list's filters ────────────────────────────────────────────────────── #[test] fn the_list_filters_by_kind_and_by_a_word_over_the_plain_columns_only() { let db = fixture(); let services = services(Some(Arc::new(TestVault::at(1)))); let mut ctx = ctx(&db, &services); call_tool( &mut ctx, "create_secret", &args(&[ ("kind", "login"), ("name", "Glasshouse Mail"), ("site", "https://mail.glasshouse.example.invalid"), ("value", "needle-in-the-payload"), ]), ) .expect("stored"); call_tool( &mut ctx, "create_secret", &args(&[("name", "A key"), ("service", "anthropic"), ("value", "aaaa")]), ) .expect("stored"); let logins = call_tool(&mut ctx, "list_secrets", &args(&[("kind", "login")])).expect("listed"); assert_eq!(logins["secrets"].as_array().map(Vec::len), Some(1)); assert_eq!(logins["secrets"][0]["name"], Value::from("Glasshouse Mail")); let found = call_tool(&mut ctx, "list_secrets", &args(&[("q", "glasshouse")])).expect("listed"); assert_eq!(found["secrets"].as_array().map(Vec::len), Some(1)); // The PAYLOAD is not searchable, and that is the point of sealing it. let nothing = call_tool(&mut ctx, "list_secrets", &args(&[("q", "needle")])).expect("listed"); assert_eq!(nothing["secrets"].as_array().map(Vec::len), Some(0)); }