//! The secrets tools, end to end over `dispatch::call_tool` against a real//! store and a fake `ToolServices` — the four verbs an assistant has//! (`create_secret`, `update_secret`, `list_secrets`, `delete_secret`) and the//! one promise they make: a value goes IN and never comes back out.//!//! There is no TypeScript to port from — the secrets surface was born in Rust//! (schema v46, rebuilt as the vault at v6 of the Rust ladder,//! Cotton note "The vault — the honest sentence"), and its only coverage was the in-crate module//! beside the handler. This is the BEHAVIOURAL half: a tool called the way the//! transport calls one, on a provisioned file, so the group is exercised by the//! same harness every other group is and `handler_group_coverage.rs` can find//! it.mod support;use rusqlite::types::ValueasSqlValue;use serde_json::{json, Value};use support::fakes::FakeVault;use support::harness::Harness;use support::mcp::{call_tool, call_tool_raw, mint_token};fn writer_harness() -> (Harness, String) {letmut h = Harness::new();let secret = mint_token(&mut h, &["read", "write"], "Claude"); (h, secret)}/// Every column of the stored row, so an assertion can say what the file holds/// rather than what a tool answered.fn stored(h: &Harness, id: &str) -> serde_json::Map<String, Value> { h.one("SELECT id, kind, name, site, username, service, value_enc, vmk_version, hint, trashed_at \ FROM cotton_secrets WHERE id = ?", &[SqlValue::Text(id.to_string())], ) .expect("the secret is in the file")}fn column<'row>(row: &'row serde_json::Map<String, Value>, name: &str) -> Option<&'row str> { row.get(name).and_then(Value::as_str)}#[test]fn seals_the_payload_and_answers_with_a_hint_never_with_the_value() {let (h, secret) = writer_harness();let created = call_tool( &h, &secret,"create_secret", json!({"name": "Anthropic API key","service": "anthropic","value": "sk-test-000000000wxyz", }), ); assert_eq!(created["name"], json!("Anthropic API key")); assert_eq!(created["service"], json!("anthropic")); assert_eq!(created["kind"], json!("api_key")); assert_eq!(created["hint"], json!("wxyz"));// The tool that was just handed the value does not hand it back. assert_eq!(created["value"], Value::Null); assert_eq!(created["valueEnc"], Value::Null);// The column holds what the VAULT produced — the typed payload, sealed —// and the plaintext is nowhere in the file outside it.let id = created["id"].as_str().expect("an id").to_string();let row = stored(&h, &id); assert_eq!( column(&row, "value_enc"),Some(FakeVault::sealed( &id,r#"{"kind":"api_key","key":"sk-test-000000000wxyz"}"# ) .as_str() ) ); assert_eq!( row.get("vmk_version").and_then(Value::as_i64),Some(i64::from(FakeVault::VERSION)),"the row names the key that sealed it" ); assert_eq!(column(&row, "hint"), Some("wxyz"));// And the list answers names, services and four characters — never the// column the named readers read.let listed = call_tool(&h, &secret, "list_secrets", json!({}));let secrets = listed["secrets"].as_array().expect("secrets"); assert_eq!(secrets.len(), 1); assert_eq!(secrets[0]["hint"], json!("wxyz")); assert_eq!(secrets[0]["isSet"], json!(true)); assert_eq!(secrets[0]["value_enc"], Value::Null); assert_eq!(secrets[0]["valueEnc"], Value::Null); assert!( !listed.to_string().contains("sk-test-000000000wxyz"),"{listed}" );}#[test]fn refuses_by_name_on_a_build_with_no_vault_rather_than_storing_the_plaintext() {letmut h = Harness::without_services();let secret = mint_token(&mut h, &["read", "write"], "Claude");let refused = call_tool_raw( &h, &secret,"create_secret", json!({ "name": "Key", "service": "anthropic", "value": "sk-test-abcd" }), ); assert!(refused.is_error); assert!( refused.text.contains("vault_unavailable"),"{}", refused.text ); assert_eq!(h.count("SELECT COUNT(*) FROM cotton_secrets", &[]), 0);}#[test]fn replaces_the_value_when_a_key_is_re_pasted_rather_than_minting_a_second_row() {let (h, secret) = writer_harness();let first = call_tool( &h, &secret,"create_secret", json!({ "name": "Key", "service": "anthropic", "value": "sk-test-oldd" }), );let second = call_tool( &h, &secret,"create_secret", json!({ "name": "Key", "service": "anthropic", "value": "sk-test-neww" }), );// One row, the same id, and the rotated value: a person re-pasting a key// means the new one. assert_eq!(second["id"], first["id"]); assert_eq!(second["hint"], json!("neww")); assert_eq!(h.count("SELECT COUNT(*) FROM cotton_secrets", &[]), 1);let id = first["id"].as_str().expect("an id").to_string();let row = stored(&h, &id); assert_eq!( column(&row, "value_enc"),Some(FakeVault::sealed(&id, r#"{"kind":"api_key","key":"sk-test-neww"}"#).as_str()) );}#[test]fn a_login_carries_its_site_and_username_in_the_clear_and_its_password_sealed() {let (h, secret) = writer_harness();let created = call_tool( &h, &secret,"create_secret", json!({"kind": "login","name": "Glasshouse Mail","site": "https://mail.glasshouse.example.invalid","username": "wren@example.invalid","fields": { "password": "hunter-aaaa", "totp": "JBSWY3DPEHPK3PXP" }, }), );let id = created["id"].as_str().expect("an id").to_string();let row = stored(&h, &id); assert_eq!(column(&row, "kind"), Some("login")); assert_eq!(column(&row, "username"), Some("wren@example.invalid")); assert_eq!(column(&row, "service"), None, "a login has no service");let sealed = column(&row, "value_enc").expect("a sealed payload"); assert!(sealed.contains("hunter-aaaa"), "the fake vault does not encrypt");// What matters is that it went through the RAIL — the real one encrypts. assert!(sealed.starts_with(&format!("fake-seal:{id}:")), "{sealed}");// The one-time secret is INSIDE the payload and on no column of its own. assert!(sealed.contains("JBSWY3DPEHPK3PXP")); assert_eq!(column(&row, "name"), Some("Glasshouse Mail")); assert_eq!(created["hint"], json!("aaaa"));}#[test]fn refuses_a_service_the_column_would_refuse_and_an_empty_value() {let (h, secret) = writer_harness();let bad_service = call_tool_raw( &h, &secret,"create_secret", json!({ "name": "Key", "service": "Anthropic Inc", "value": "sk-test-abcd" }), ); assert!(bad_service.is_error); assert!( bad_service.text.contains("lowercase"),"{}", bad_service.text );let blank = call_tool_raw( &h, &secret,"create_secret", json!({ "name": "Key", "service": "anthropic", "value": "" }), ); assert!(blank.is_error); assert!(blank.text.contains("delete_secret"), "{}", blank.text); assert_eq!(h.count("SELECT COUNT(*) FROM cotton_secrets", &[]), 0);}#[test]fn narrows_the_list_by_service_by_kind_and_by_word() {let (h, secret) = writer_harness(); call_tool( &h, &secret,"create_secret", json!({ "name": "Key", "service": "anthropic", "value": "sk-test-aaaa" }), ); call_tool( &h, &secret,"create_secret", json!({ "name": "Key", "service": "openai", "value": "sk-test-bbbb" }), ); call_tool( &h, &secret,"create_secret", json!({"kind": "login","name": "Thimble Bank","site": "https://thimble.example.invalid","value": "hunter-cccc", }), );let narrowed = call_tool(&h, &secret, "list_secrets", json!({ "service": "openai" }));let services: Vec<&str> = narrowed["secrets"] .as_array() .expect("secrets") .iter() .map(|row| row["service"].as_str().unwrap_or_default()) .collect(); assert_eq!(services, vec!["openai"]);let logins = call_tool(&h, &secret, "list_secrets", json!({ "kind": "login" })); assert_eq!(logins["secrets"].as_array().map(Vec::len), Some(1));let asked = call_tool(&h, &secret, "list_secrets", json!({ "q": "thimble" })); assert_eq!(asked["secrets"].as_array().map(Vec::len), Some(1));// The SEALED payload is not searchable, which is the point of sealing it.let nothing = call_tool(&h, &secret, "list_secrets", json!({ "q": "hunter" })); assert_eq!(nothing["secrets"].as_array().map(Vec::len), Some(0));}#[test]fn binning_a_secret_hides_it_from_the_list_and_leaves_it_restorable() {let (h, secret) = writer_harness();let anthropic = call_tool( &h, &secret,"create_secret", json!({ "name": "Key", "service": "anthropic", "value": "sk-test-aaaa" }), );let id = anthropic["id"].as_str().expect("an id").to_string();let binned = call_tool(&h, &secret, "delete_secret", json!({ "id": id })); assert_eq!(binned["binned"], json!(true)); assert_eq!(binned["service"], json!("anthropic"));// The row STAYS: being wrong must cost a tap, not a credential. assert_eq!(h.count("SELECT COUNT(*) FROM cotton_secrets", &[]), 1); assert!(stored(&h, &id).get("trashed_at").and_then(Value::as_str).is_some());let listed = call_tool(&h, &secret, "list_secrets", json!({})); assert_eq!(listed["secrets"].as_array().map(Vec::len), Some(0));// The kind-generic bin knows it by name, and restoring brings it back.let bin = call_tool(&h, &secret, "list_bin", json!({ "kind": "secret" })); assert!(bin.to_string().contains("Key"), "{bin}"); assert!(!bin.to_string().contains("sk-test-aaaa"), "{bin}"); call_tool( &h, &secret,"restore_from_bin", json!({ "kind": "secret", "id": id }), );let back = call_tool(&h, &secret, "list_secrets", json!({})); assert_eq!(back["secrets"].as_array().map(Vec::len), Some(1));let missing = call_tool_raw( &h, &secret,"delete_secret", json!({ "id": "00000000-0000-4000-8000-0000000000aa" }), ); assert!(missing.is_error); assert!(missing.text.contains("no secret with id"), "{}", missing.text);}#[test]fn update_secret_renames_re_seals_and_never_answers_a_value() {let (h, secret) = writer_harness();let created = call_tool( &h, &secret,"create_secret", json!({ "kind": "login", "name": "Gmial", "value": "hunter-aaaa" }), );let id = created["id"].as_str().expect("an id").to_string();let renamed = call_tool( &h, &secret,"update_secret", json!({ "id": id, "name": "Gmail", "username": "wren@example.invalid" }), ); assert_eq!(renamed["name"], json!("Gmail")); assert_eq!(renamed["hint"], json!("aaaa"), "a rename does not re-seal");let re_sealed = call_tool( &h, &secret,"update_secret", json!({ "id": id, "fields": { "password": "hunter-bbbb" } }), ); assert_eq!(re_sealed["hint"], json!("bbbb")); assert!(!re_sealed.to_string().contains("hunter-bbbb"), "{re_sealed}");let row = stored(&h, &id); assert_eq!(column(&row, "name"), Some("Gmail")); assert_eq!(column(&row, "hint"), Some("bbbb"));}#[test]fn a_secret_is_found_by_search_records_over_its_plain_columns_and_never_its_payload() {let (h, secret) = writer_harness(); call_tool( &h, &secret,"create_secret", json!({"kind": "login","name": "Glasshouse Mail","site": "https://mail.glasshouse.example.invalid","username": "glass.owl","value": "needle-in-the-payload", }), );let found = call_tool(&h, &secret, "search_records", json!({ "query": "glasshouse" }));let text = found.to_string(); assert!(text.contains("Glasshouse Mail"), "{text}"); assert!(!text.contains("needle-in-the-payload"), "{text}");// The payload is not in the index at all.let nothing = call_tool(&h, &secret, "search_records", json!({ "query": "needle" })); assert!( !nothing.to_string().contains("Glasshouse Mail"),"the payload is never indexed: {nothing}" );}// ── the person key is not a secret a tool can reach ─────────────────────────/// A sealed value no tool may answer. Invented, like every fixture here.const SEALED_PERSON_KEY: &str = "v1.INVENTED-sealed-person-key-private-half";/// An invented person key (the public half's text) and its fingerprint.const PERSON_KEY: &str = "INVENTEDpersonkey0000000000000000000000000a";const PERSON_FINGERPRINT: &str = "INVENTED";fn tool_sources(dir: &std::path::Path, found: &mutVec<std::path::PathBuf>) {for entry in std::fs::read_dir(dir).expect("the tools' source directory") {let path = entry.expect("a directory entry").path();if path.is_dir() { tool_sources(&path, found); } elseif path.extension().is_some_and(|extension| extension == "rs") { found.push(path); } }}/// RULE: A person key's sealed private half is answered by no MCP tool — no tool's code names cotton_person_keys, and no reading tool's answer carries anything of the row.#[test]fn person_key_private_half_is_never_listed_by_any_mcp_tool() {// THE SCAN: a tool that never names the table cannot read it. The generic// readers take a table's DEFINITION id, never a SQL name, so there is no// argument that reaches a table no definition names.letmut sources = Vec::new(); tool_sources( &cotton_store::manifest::manifest_dir().join("src"), &mut sources, ); assert!(sources.len() > 50, "the scan found the tools' sources");for path in &sources {let text = std::fs::read_to_string(path).expect("a source file");for word in ["cotton_person_keys", "sealed_private"] { assert!( !text.contains(word),"{} names `{word}`: no tool reads the person key's table", path.display() ); } }// THE LIVE HALF: a file that holds a person key, and every reading tool// asked — with no arguments, and the generic readers by every name a// caller might guess.let (h, secret) = writer_harness(); h.run("INSERT INTO cotton_person_keys \ (id, workspace_id, public_key, name, sealed_private, vmk_version, created_at) \ VALUES (?, ?, ?, 'Nobody Invented', ?, 1, '2026-09-08T09:00:00.000Z')", &[SqlValue::Text(PERSON_FINGERPRINT.to_string()),SqlValue::Text(h.workspace_id.clone()),SqlValue::Text(PERSON_KEY.to_string()),SqlValue::Text(SEALED_PERSON_KEY.to_string()), ], );letmut asked = 0;letmut ask = |name: &str, args: Value| {let answer = call_tool_raw(&h, &secret, name, args);let said = format!("{} {}", answer.text, answer.result);for word in [SEALED_PERSON_KEY, PERSON_KEY] { assert!(!said.contains(word), "`{name}` answered the person key: {said}"); } asked += 1; };for tool in cotton_tools::mcp::catalogue::TOOLS {if tool.scope == cotton_tools::mcp::protocol::McpScope::Read { ask(tool.name, json!({})); } } ask("list_secrets", json!({ "query": PERSON_FINGERPRINT }));for table in ["cotton_person_keys", "person_key", "person_keys"] { ask("get_record_by_table", json!({ "table": table, "id": PERSON_FINGERPRINT })); ask("list_records", json!({ "table": table })); } ask("search_records", json!({ "query": PERSON_FINGERPRINT })); assert!(asked > 40, "every reading tool was asked, {asked} of them");}