391 lines · 20.3 KB · RustRaw
//! The connection-mapping tools (Spec 9.7 piece 4) — `propose_connection_mapping`//! and `set_connection_mapping` — driven through the dispatcher over connection//! rows the phone's Connect… writes. Every server here is invented except//! Cloudflare's own URL, whose mapping is the one this crate ships.mod support;use cotton_tools::connections::{self, ConnectionKind};use cotton_tools::mcp::dispatch::{Ctx, ToolServices};use serde_json::{json, Value};use std::sync::Arc;use support::mcp::{call_tool, call_tool_raw, mint_token};use support::Harness;const CLOUDFLARE: &str = "https://mcp.cloudflare.com/mcp";const ELSEWHERE: &str = "https://mcp.example-notes.test/mcp";/// A connection as the phone's Connect… makes it, with `config` as sign-in leaves it.fn connect(h: &Harness, kind: ConnectionKind, reaches: &str, config: Value) -> String { let services = ToolServices::none(); let audit = |_tool: &str, _summary: &str| {}; h.with(|db| { let mut ctx = Ctx::for_worker( db, &h.file, &h.owner_id, cotton_tools::mcp::writer::job("connections"), "job:connections", cotton_tools::clock::Clock::now(&h.clock), Arc::clone(&h.random), &services, &audit, ); let id = connections::create(&mut ctx, kind, "", reaches, None, config).expect("connects"); ctx.commit().expect("commits"); id })}fn cloudflare_tools() -> Value { json!([ {"name": "search", "description": "Search the Cloudflare API spec.", "inputSchema": {"type": "object"}}, {"name": "execute", "description": "Run code against the Cloudflare API.", "inputSchema": {"type": "object"}} ])}fn config_of(h: &Harness, id: &str) -> Value { let row = h.one("SELECT config FROM cotton_connections WHERE id = ?", &[id.to_string().into()]).expect("the row"); serde_json::from_str(row["config"].as_str().expect("config is text")).expect("config is JSON")}fn refused(h: &Harness, secret: &str, tool: &str, args: Value) -> String { let answer = call_tool_raw(h, secret, tool, args); assert!(answer.is_error, "{tool} was expected to refuse: {}", answer.text); answer.text}/// RULE: An assistant connects Cloudflare in two calls — propose answers the shipped mapping ready to keep, and set keeps it beside the server's tools before Domains is installed.#[test]fn cloudflare_is_proposed_ready_and_kept_before_domains_is_installed() { let mut h = Harness::new(); let secret = mint_token(&mut h, &["read", "write"], "Assistant"); let id = connect(&h, ConnectionKind::McpServer, CLOUDFLARE, json!({ "tools": cloudflare_tools() })); let proposed = call_tool(&h, &secret, "propose_connection_mapping", json!({ "id": id })); assert_eq!(proposed["proposal"]["ready"], json!(true), "{proposed}"); assert_eq!(proposed["proposal"]["installs"], json!(["domains"])); assert_eq!(proposed["current"], Value::Null); let kept = call_tool( &h, &secret, "set_connection_mapping", json!({ "id": id, "mapping": proposed["proposal"]["mapping"].clone() }), ); assert_eq!(kept["tables"], json!(["dns_record", "domain"]), "{kept}"); let config = config_of(&h, &id); assert_eq!(config["mapping"], proposed["proposal"]["mapping"], "the mapping is on the row"); assert_eq!(config["tools"], cloudflare_tools(), "the server's tools are kept beside it"); let again = call_tool(&h, &secret, "propose_connection_mapping", json!({ "id": id })); assert_eq!(again["current"], proposed["proposal"]["mapping"], "propose shows what is kept");}/// RULE: A mapping that does not fit this database's tables is refused with the call and column named, and nothing is kept.#[test]fn a_mapping_that_does_not_fit_is_refused_and_not_kept() { let mut h = Harness::new(); let secret = mint_token(&mut h, &["read", "write"], "Assistant"); let tools = json!([{ "name": "list_pages", "description": "Every page.", "inputSchema": {"type": "object"} }]); let id = connect(&h, ConnectionKind::McpServer, ELSEWHERE, json!({ "tools": tools })); let proposed = call_tool(&h, &secret, "propose_connection_mapping", json!({ "id": id })); assert_eq!(proposed["proposal"]["ready"], json!(false), "an unknown server gets a skeleton: {proposed}"); assert_eq!(proposed["proposal"]["mapping"]["calls"][0]["tool"], json!("list_pages")); let mapping = json!({ "calls": [{ "tool": "list_pages", "args": {}, "every": "1d", "into": "todo", "rows": "pages", "key": "id", "key_column": "title", "columns": { "no_such_column": "title" } }]}); let why = refused(&h, &secret, "set_connection_mapping", json!({ "id": id, "mapping": mapping })); assert!(why.contains("calls[0]") && why.contains("no_such_column"), "{why}"); assert!(config_of(&h, &id).get("mapping").is_none(), "nothing was kept"); let why = refused( &h, &secret, "set_connection_mapping", json!({ "id": id, "mapping": { "calls": [{ "tool": "list_pages", "into": "no_such_table", "key": "id", "key_column": "external_id", "columns": { "title": "title" } }] } }), ); assert!(why.contains("no_such_table"), "{why}");}/// RULE: Only a signed-in MCP server connection takes a mapping — a connection of another kind, or one whose tools are not known yet, is refused in words that say what to do.#[test]fn only_a_signed_in_mcp_server_takes_a_mapping() { let mut h = Harness::new(); let secret = mint_token(&mut h, &["read", "write"], "Assistant"); let unsigned = connect(&h, ConnectionKind::McpServer, ELSEWHERE, json!({})); let why = refused(&h, &secret, "propose_connection_mapping", json!({ "id": unsigned })); assert!(why.contains("Sign it in"), "{why}"); let git = connect(&h, ConnectionKind::GitHost, "git.example.test", json!({})); let why = refused(&h, &secret, "set_connection_mapping", json!({ "id": git, "mapping": { "calls": [] } })); assert!(why.contains("only an MCP server connection"), "{why}"); let why = refused(&h, &secret, "propose_connection_mapping", json!({ "id": "conn:mcp_server:gone" })); assert!(why.contains("not here any more"), "{why}");}// ── connect: a mailbox or a calendar wired to a password already filed ─────/// A vault secret as the phone files one: the row and a sealed value this/// test never opens (an invented placeholder — `connect` never reads it).fn a_filed_secret(h: &Harness, id: &str, kind: &str) { h.run( "INSERT INTO cotton_secrets (id, workspace_id, kind, name, value_enc, vmk_version, created_at, updated_at) \ VALUES (?, ?, ?, 'Invented app password', 'sealed-placeholder', 1, '2026-10-01T00:00:00.000Z', '2026-10-01T00:00:00.000Z')", &[id.to_string().into(), h.workspace_id.clone().into(), kind.to_string().into()], );}fn connection_rows(h: &Harness) -> Vec<serde_json::Map<String, Value>> { h.all("SELECT id, kind, name, reaches, state, secret_id, config FROM cotton_connections ORDER BY id", &[])}/// RULE: connect writes the row the phone's Connect… writes — the same id, kind, name, address (lower-cased), state reading and secret_id the named vault secret — and answers it.#[test]fn connect_names_an_existing_secret_and_writes_the_phones_row() { let mut h = Harness::new(); let token = mint_token(&mut h, &["read", "write"], "Assistant"); a_filed_secret(&h, "secret-app-password", "api_key"); let answer = call_tool( &h, &token, "connect", json!({ "kind": "mail", "reaches": "Someone@Example.test", "secret": "secret-app-password" }), ); assert_eq!(answer["connection"]["id"], json!("conn:mail:someone@example.test"), "{answer}"); assert_eq!(answer["connection"]["state"], json!("reading")); // The phone's own path, for a second address: the two rows agree column by column. let services = ToolServices::none(); let audit = |_tool: &str, _summary: &str| {}; h.with(|db| { let mut ctx = Ctx::for_worker( db, &h.file, &h.owner_id, cotton_tools::mcp::writer::job("connections"), "job:connections", cotton_tools::clock::Clock::now(&h.clock), Arc::clone(&h.random), &services, &audit, ); connections::create(&mut ctx, ConnectionKind::Mail, "", "Other@Example.test", Some("secret-app-password"), json!({})) .expect("connects"); ctx.commit().expect("commits"); }); let rows = connection_rows(&h); assert_eq!(rows.len(), 2); let (other, ours) = (&rows[0], &rows[1]); assert_eq!(ours["reaches"], json!("someone@example.test")); assert_eq!(other["reaches"], json!("other@example.test")); for column in ["kind", "state", "secret_id", "config"] { assert_eq!(ours[column], other[column], "{column} differs from the phone's row"); } assert_eq!(ours["secret_id"], json!("secret-app-password"));}/// RULE: connect never takes a password, a token or a key: its schema names none, and a call that carries one is refused by name with nothing written.#[test]fn connect_never_accepts_a_password_or_a_token() { let mut h = Harness::new(); let token = mint_token(&mut h, &["read", "write"], "Assistant"); a_filed_secret(&h, "secret-app-password", "login"); let schema = cotton_tools::mcp::catalogue::TOOLS .iter() .find(|tool| tool.name == "connect") .expect("connect is in the catalogue") .input_schema; let properties: Value = serde_json::from_str::<Value>(schema).expect("JSON")["properties"].clone(); let names: Vec<&str> = properties.as_object().expect("properties").keys().map(String::as_str).collect(); for field in ["password", "token", "key", "value", "credential"] { assert!(!names.contains(&field), "connect's schema names {field}"); } for field in ["password", "token"] { let said = refused( &h, &token, "connect", json!({ "kind": "mail", "reaches": "someone@example.test", "secret": "secret-app-password", field: "invented" }), ); assert!(said.contains(field), "{said}"); } assert!(connection_rows(&h).is_empty(), "nothing is written");}/// RULE: connect refuses by name a secret id this database's vault does not hold, one in the bin, and one that holds no password; a Gmail calendar is sent to the Google door — each with nothing written.#[test]fn a_wrong_secret_or_a_gmail_calendar_is_refused_by_name() { let mut h = Harness::new(); let token = mint_token(&mut h, &["read", "write"], "Assistant"); a_filed_secret(&h, "secret-note", "note"); a_filed_secret(&h, "secret-binned", "login"); h.run("UPDATE cotton_secrets SET trashed_at = '2026-10-02T00:00:00.000Z' WHERE id = 'secret-binned'", &[]); a_filed_secret(&h, "secret-app-password", "api_key"); for (secret, says) in [ ("secret-nowhere", "No secret secret-nowhere"), ("secret-binned", "No secret secret-binned"), ("secret-note", "is a note"), ] { let said = refused(&h, &token, "connect", json!({ "kind": "mail", "reaches": "someone@example.test", "secret": secret })); assert!(said.contains(says), "{secret}: {said}"); } let said = refused( &h, &token, "connect", json!({ "kind": "calendar", "reaches": format!("someone@{}", cotton_tools::mcp::handlers::connections::GOOGLE_MAIL_DOMAINS[0]), "secret": "secret-app-password" }), ); assert!(said.contains("Google"), "{said}"); let said = refused(&h, &token, "connect", json!({ "kind": "whatsapp", "reaches": "someone@example.test", "secret": "secret-app-password" })); assert!(said.contains("mail"), "{said}"); assert!(connection_rows(&h).is_empty(), "nothing is written");}/// RULE: connect wires a Cloudflare account by the id of an API token already in the vault — no address, no token in the call — and the row is the one the phone's Connect… writes: kind cloudflare, reading, naming that secret.////// The Cloudflare reader on the serving Mac opens exactly the secret the row/// names; a row without one would wait for a sign-in no reader can do.#[test]fn connect_wires_cloudflare_by_a_filed_api_token() { let mut h = Harness::new(); let token = mint_token(&mut h, &["read", "write"], "Assistant"); a_filed_secret(&h, "secret-cloudflare-token", "api_key"); let answer = call_tool(&h, &token, "connect", json!({ "kind": "cloudflare", "name": "Sites", "secret": "secret-cloudflare-token" })); assert_eq!(answer["connection"]["kind"], json!("cloudflare"), "{answer}"); assert_eq!(answer["connection"]["name"], json!("Sites")); assert_eq!(answer["connection"]["state"], json!("reading")); let rows = connection_rows(&h); assert_eq!(rows.len(), 1); assert_eq!(rows[0]["secret_id"], json!("secret-cloudflare-token")); let said = refused(&h, &token, "connect", json!({ "kind": "cloudflare", "name": "Sites" })); assert!(said.contains("Cloudflare API token"), "{said}"); let said = refused(&h, &token, "connect", json!({ "kind": "cloudflare", "token": "anything" })); assert!(said.contains("never takes a password or a token"), "{said}");}// ── connect: the household's tailnet ───────────────────────────────────────/// RULE: connect wires a tailnet to an OAuth client the owner already filed as one vault login (the client id its username) — the row is kind tailscale, reaches the tailnet's name, names that login by id, and the client's secret is never asked for.#[test]fn connect_names_a_filed_oauth_client_for_the_tailnet() { let mut h = Harness::new(); let token = mint_token(&mut h, &["read", "write"], "Assistant"); a_filed_secret(&h, "secret-oauth-client", "login"); h.run("UPDATE cotton_secrets SET username = 'invented-client-id' WHERE id = 'secret-oauth-client'", &[]); let answer = call_tool( &h, &token, "connect", json!({ "kind": "tailscale", "reaches": "Tail0000.ts.net.", "secret": "secret-oauth-client" }), ); assert_eq!(answer["connection"]["id"], json!("conn:tailscale:tail0000.ts.net"), "{answer}"); assert_eq!(answer["connection"]["name"], json!("Tailscale")); assert_eq!(answer["connection"]["state"], json!("reading")); let rows = connection_rows(&h); assert_eq!(rows.len(), 1); assert_eq!(rows[0]["kind"], json!("tailscale")); assert_eq!(rows[0]["reaches"], json!("tail0000.ts.net")); assert_eq!(rows[0]["secret_id"], json!("secret-oauth-client")); assert_eq!(rows[0]["config"], json!("{}"));}/// RULE: a tailnet is refused by name, with nothing written, when its secret is not a login, when the login names no client id, when it carries a server, or when it names no tailnet.#[test]fn a_tailnet_without_a_filed_oauth_client_is_refused_by_name() { let mut h = Harness::new(); let token = mint_token(&mut h, &["read", "write"], "Assistant"); a_filed_secret(&h, "secret-key", "api_key"); a_filed_secret(&h, "secret-unnamed", "login"); let said = refused(&h, &token, "connect", json!({ "kind": "tailscale", "reaches": "tail0000.ts.net", "secret": "secret-key" })); assert!(said.contains("not a login"), "{said}"); let said = refused(&h, &token, "connect", json!({ "kind": "tailscale", "reaches": "tail0000.ts.net", "secret": "secret-unnamed" })); assert!(said.contains("names no client id"), "{said}"); let said = refused(&h, &token, "connect", json!({ "kind": "tailscale", "reaches": "tail0000.ts.net", "secret": "secret-gone" })); assert!(said.contains("No secret secret-gone"), "{said}"); let said = refused( &h, &token, "connect", json!({ "kind": "tailscale", "reaches": "tail0000.ts.net", "secret": "secret-unnamed", "server": "api.example.test" }), ); assert!(said.contains("takes no `server`"), "{said}"); let said = refused(&h, &token, "connect", json!({ "kind": "tailscale", "reaches": " ", "secret": "secret-unnamed" })); assert!(said.contains("tailnet's name"), "{said}"); assert!(connection_rows(&h).is_empty());}/// RULE: Connection reads preserve stored state, errors and timestamps as typed columns, because assistants diagnose failures from facts rather than app prose./// RULE: Connection reads expose only a secret's id and remove credential keys recursively, because an assistant's transcript must never hold a connection credential.#[test]fn connection_reads_remove_credentials_and_keep_typed_state() { let mut h = Harness::new(); let token = mint_token(&mut h, &["read"], "Reader"); a_filed_secret(&h, "vault-id-only", "api_key"); let id = connect(&h, ConnectionKind::McpServer, ELSEWHERE, json!({ "accessToken": "invented-credential", "nested": [{"PASSWORD": "invented-credential", "secret": "invented-credential", "api_key": "invented-credential", "cookie": "invented-credential", "sessionId": "invented-credential", "every": 60}], "host": "example.test", "other": "Bearer syntheticCredential123" })); h.run("UPDATE cotton_connections SET secret_id = 'vault-id-only', state = 'failed', last_error = 'HTTP 503', last_read_at = '2026-10-01T00:00:00.000Z', read_requested_at = '2026-10-02T00:00:00.000Z', schedule = 'hourly' WHERE id = ?", &[id.clone().into()]); for answer in [ call_tool(&h, &token, "get_connection", json!({"id": id}))["connection"].clone(), call_tool(&h, &token, "list_connections", json!({}))["connections"][0].clone(), ] { assert!(!answer.to_string().contains("invented-credential")); assert!(!answer.to_string().contains("sealed-placeholder")); assert!(!answer.to_string().contains("syntheticCredential123")); assert_eq!(answer["secret_id"], "vault-id-only"); assert_eq!(answer["config"]["nested"], json!([{"every":60}])); assert_eq!(answer["config"]["host"], "example.test"); assert_eq!(answer["state"], "failed"); assert_eq!(answer["last_error"], "HTTP 503"); assert_eq!(answer["last_read_at"], "2026-10-01T00:00:00.000Z"); assert_eq!(answer["read_requested_at"], "2026-10-02T00:00:00.000Z"); assert_eq!(answer["schedule"], "hourly"); assert_eq!(answer["database"], h.workspace_id); } assert!(call_tool(&h, &token, "list_connections", json!({"kind":"mail"}))["connections"].as_array().unwrap().is_empty()); assert_eq!(call_tool(&h, &token, "list_connections", json!({"kind":"mcp_server"}))["connections"][0]["id"], id); assert!(call_tool_raw(&h, &token, "get_connection", json!({"id":"absent"})).is_error);}/// RULE: No credential reaches a connection read — not three levels deep under an unusual key, not as a JWT or bare hex value, not in the address or the last error — because an assistant's transcript keeps what it reads.#[test]fn a_connection_read_carries_no_credential_from_any_column_at_any_depth() { let mut h = Harness::new(); let token = mint_token(&mut h, &["read"], "Reader"); let jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJpbnZlbnRlZCJ9.c2lnbmF0dXJlLWludmVudGVk"; let hex = "0123456789abcdef0123456789abcdef"; let id = connect(&h, ConnectionKind::McpServer, ELSEWHERE, json!({ "one": {"two": {"three": { "x-api-key": "INVENTED-1", "Authorization": "INVENTED-2", "refreshToken": "INVENTED-3", "client_secret": "INVENTED-4", "carried": jwt, "plain": hex, "basicHeader": "INVENTED-5", "headerValue": "Basic SU5WRU5URUQ6Ng=="}}}, "host": "example.test" })); h.run("UPDATE cotton_connections SET reaches = 'https://someone:INVENTED-7@example.test/mcp?api_key=INVENTED-8', \ last_error = 'HTTP 401: key sk-INVENTED-9abcdefghijklmnop refused, Bearer INVENTED-10abcdef' WHERE id = ?", &[id.clone().into()]); for answer in [ call_tool(&h, &token, "get_connection", json!({"id": id}))["connection"].clone(), call_tool(&h, &token, "list_connections", json!({}))["connections"][0].clone(), ] { let text = answer.to_string(); for leaked in ["INVENTED-", jwt, hex, "SU5WRU5URUQ6Ng"] { assert!(!text.contains(leaked), "{leaked} reached the answer: {text}"); } assert_eq!(answer["config"]["host"], "example.test"); assert!(answer["reaches"].as_str().unwrap().contains("example.test/mcp"), "{text}"); assert!(answer["last_error"].as_str().unwrap().starts_with("HTTP 401"), "{text}"); }}