Cotton code
283 lines · 13.5 KB · RustRaw
//! The connection-mapping tools — `propose_connection_mapping` and//! `set_connection_mapping` (Spec 9.7 piece 4, Cotton note 7767ed9c).//!//! An MCP server connection reads nothing until its row carries a//! `config.mapping`: which of the server's tools to call, how often, and how//! one answer becomes rows of one table. An assistant writes it in one turn://! propose reads the server's tools (kept on the row at sign-in) and answers//! the known mapping (Cloudflare's, with the Domains tool to install) or a//! skeleton to fill; set checks the mapping against this database's live//! tables and keeps it. The serving Mac's `mcp-bridge` worker runs it.//!//! And `connect`: a mailbox or a calendar wired to an app password the owner//! already filed in the vault from the phone. It takes the secret's ID and//! never its value — an assistant that held the password would be one more//! place it could leak — and writes the row the phone's Connect… writes.use cotton_core::definitions::TableDefinition;use serde_json::{json, Map, Value};use crate::connections::domains::{self, DNS_RECORD, DOMAIN};use crate::connections::mapping::Mapping;use crate::connections::row::ConnectionRow;use crate::connections::{create, existing, set_mapping, ConnectionKind};use crate::mcp::dispatch::{Ctx, HandlerGroup, ToolResult};use crate::mcp::handlers::common::require_string;use crate::mcp::protocol::ToolFailure;#[path = "connections_read.rs"]mod read;pub fn handlers() -> HandlerGroup {    &[        ("list_connections", read::list_connections),        ("get_connection", read::get_connection),        ("propose_connection_mapping", propose_connection_mapping),        ("set_connection_mapping", set_connection_mapping),        ("connect", connect),    ]}/// The MCP server connection by id, or the refusal that says what to do.fn mcp_connection(ctx: &Ctx<'_>, args: &Map<String, Value>) -> Result<ConnectionRow, ToolFailure> {    let id = require_string(args, "id")        .ok_or_else(|| ToolFailure::new("Pass id: the connection's id, from its page."))?;    let row = ConnectionRow::from_json(&Value::Object(existing(ctx, &id)?)).map_err(ToolFailure::new)?;    if !row.is_mcp_server() {        return Err(ToolFailure::new(format!(            "{} is a {} connection; only an MCP server connection takes a mapping.",            row.name, row.kind        )));    }    Ok(row)}pub fn propose_connection_mapping(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let row = mcp_connection(ctx, args)?;    let tools = row.tools();    if tools.is_empty() {        return Err(ToolFailure::new(format!(            "{} has not been signed in yet, so its tools are not known. Sign it in from its page, then propose again.",            row.name        )));    }    Ok(json!({        "connection": { "id": row.id, "name": row.name, "reaches": row.reaches, "state": row.state },        "current": row.mapping().cloned().unwrap_or(Value::Null),        "proposal": domains::propose(&row.reaches, &tools),        "tools": tools,    }))}pub fn set_connection_mapping(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let row = mcp_connection(ctx, args)?;    let raw = args        .get("mapping")        .filter(|value| value.is_object())        .ok_or_else(|| ToolFailure::new("Pass mapping: an object with calls, as propose_connection_mapping answers it."))?;    let mapping = Mapping::parse(raw).map_err(|why| ToolFailure::new(format!("The mapping is not readable: {why}")))?;    mapping        .validate(&tables_for(ctx, &mapping)?)        .map_err(|why| ToolFailure::new(format!("The mapping does not fit this database's tables: {why}")))?;    set_mapping(ctx, &row.id, mapping.to_json())?;    ctx.commit()?;    Ok(json!({        "connection": { "id": row.id, "name": row.name, "state": row.state },        "mapping": mapping.to_json(),        "tables": mapping.tables(),        "note": "Kept. The serving Mac reads it at its next pass; Read now on the connection's page reads it at once."    }))}/// The tables a mapping is checked against: this database's live ones, and —/// for a mapping that writes only Domains' tables, which connecting Cloudflare/// adds and the worker brings to this build's shape — the Domains package's/// own, where not yet added or added by an older build.fn tables_for(ctx: &Ctx<'_>, mapping: &Mapping) -> Result<Vec<TableDefinition>, ToolFailure> {    let mut tables = crate::definitions::table_definitions(ctx)?.definitions;    if mapping.tables().iter().all(|table| *table == DOMAIN || *table == DNS_RECORD) {        for table in domains::package().tables {            match tables.iter_mut().find(|live| live.id == table.id) {                Some(live) if domains::behind(live, &table) => *live = table,                Some(_) => {}                None => tables.push(table),            }        }    }    Ok(tables)}/// The arguments `connect` reads. Anything else — a password, a token, a/// key — is refused by name rather than ignored, so a caller that put the/// value in the call learns it was never meant to be there.const CONNECT_ARGS: [&str; 5] = ["kind", "reaches", "secret", "name", "server"];pub fn connect(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    if let Some(stray) = args.keys().find(|key| !CONNECT_ARGS.contains(&key.as_str())) {        return Err(ToolFailure::new(format!(            "connect takes no `{stray}`: it never takes a password or a token. File the app password in the vault from the phone, then pass that secret's id as `secret`."        )));    }    let kind = match require_string(args, "kind").as_deref() {        Some("mail") => ConnectionKind::Mail,        Some("calendar") => ConnectionKind::Calendar,        Some("cloudflare") => ConnectionKind::Cloudflare,        Some("tailscale") => return connect_tailscale(ctx, args),        other => {            return Err(ToolFailure::new(format!(                "connect wires a mailbox (kind mail), a calendar (kind calendar) a Cloudflare account (kind cloudflare) or a tailnet (kind tailscale){}; other connections are made from the Connections tool.",                other.map(|kind| format!(", not `{kind}`")).unwrap_or_default()            )))        }    };    // A Cloudflare account is reached by its token alone: `reaches` is the    // person's own word for the account, or nothing.    let reaches = if kind == ConnectionKind::Cloudflare {        require_string(args, "reaches").unwrap_or_default()    } else {        require_string(args, "reaches")            .filter(|address| address.contains('@'))            .ok_or_else(|| ToolFailure::new("Pass reaches: the address, like you@example.org."))?            .to_lowercase()    };    let server = require_string(args, "server").filter(|_| kind != ConnectionKind::Cloudflare);    if kind == ConnectionKind::Calendar && server.is_none() && is_google_address(&reaches) {        return Err(ToolFailure::new(            "A Gmail calendar is not read with an app password: Google's calendar takes only Google's own sign-in, so connect it as a Google account on the serving Mac. Gmail's mail connects here as kind mail.",        ));    }    let secret = require_string(args, "secret")        .ok_or_else(|| ToolFailure::new(if kind == ConnectionKind::Cloudflare {            "Pass secret: the id of the vault secret that holds the Cloudflare API token."        } else {            "Pass secret: the id of the vault secret that holds the app password."        }))?;    // Only that a secret is there, of a kind that holds a password — never    // its value, which stays sealed until the serving Mac's reader opens it.    let held = ctx        .db()        .get(            "SELECT kind FROM cotton_secrets WHERE id = ?1 AND workspace_id = ?2 AND trashed_at IS NULL",            &[                rusqlite::types::Value::Text(secret.clone()),                rusqlite::types::Value::Text(ctx.workspace_id.to_string()),            ],        )        .map_err(|error| ToolFailure::new(error.to_string()))?        .and_then(|row| row.text("kind").map(str::to_string));    match held.as_deref() {        Some("login" | "api_key") => {}        Some(other) => {            return Err(ToolFailure::new(format!(                "The vault secret {secret} is a {other}, not a login or an API key, so it holds no app password."            )))        }        None => {            return Err(ToolFailure::new(format!(                "No secret {secret} is in this database's vault (or it is in the bin). Pass the id of the app password the owner filed."            )))        }    }    let name = require_string(args, "name")        .or_else(|| Some(reaches.clone()).filter(|reaches| !reaches.is_empty()))        .unwrap_or_else(|| "Cloudflare".to_string());    let config = match &server {        Some(server) if kind == ConnectionKind::Calendar => json!({ "url": server }),        Some(server) => json!({ "host": server }),        None => json!({}),    };    let id = create(ctx, kind, &name, &reaches, Some(&secret), config)?;    // Connecting Cloudflare is the owner's act that adds Domains, once, by    // add_tool's own path; after a removal only the owner brings it back.    if kind == ConnectionKind::Cloudflare {        domains::add(ctx)?;    }    ctx.commit()?;    let row = existing(ctx, &id)?;    let text = |key: &str| row.get(key).cloned().unwrap_or(Value::Null);    Ok(json!({        "connection": {            "id": id,            "kind": kind.as_str(),            "name": text("name"),            "reaches": text("reaches"),            "state": text("state"),        },        "note": "Connected. The serving Mac reads it at its next pass; its page in Connections says when it last read and what went wrong."    }))}/// `connect { kind: tailscale, reaches, secret, name? }`: the household's/// tailnet, signed in by an OAuth client the owner ALREADY filed in the vault/// as one login — the client id as its username, the client secret as its/// password. `reaches` is the tailnet's name as Tailscale shows it (a/// `tail1234.ts.net`, a domain, or the address a personal tailnet is named/// by). Only that the login is there and names a client id is read; its/// password stays sealed until the serving Mac opens it.fn connect_tailscale(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    if args.contains_key("server") {        return Err(ToolFailure::new(            "A tailnet takes no `server`: Tailscale's own API is the only one it asks.",        ));    }    let reaches = require_string(args, "reaches")        .map(|name| name.trim().trim_end_matches('.').to_lowercase())        .filter(|name| !name.is_empty() && !name.chars().any(char::is_whitespace))        .ok_or_else(|| ToolFailure::new("Pass reaches: the tailnet's name, like tail1234.ts.net."))?;    let secret = require_string(args, "secret").ok_or_else(|| {        ToolFailure::new("Pass secret: the id of the vault login that holds the tailnet's OAuth client.")    })?;    let held = ctx        .db()        .get(            "SELECT kind, length(trim(coalesce(username, ''))) > 0 AS named FROM cotton_secrets WHERE id = ?1 AND workspace_id = ?2 AND trashed_at IS NULL",            &[                rusqlite::types::Value::Text(secret.clone()),                rusqlite::types::Value::Text(ctx.workspace_id.to_string()),            ],        )        .map_err(|error| ToolFailure::new(error.to_string()))?;    match held.as_ref().map(|row| (row.text("kind").unwrap_or_default().to_string(), row.int("named") == Some(1))) {        Some((kind, true)) if kind == "login" => {}        Some((kind, false)) if kind == "login" => {            return Err(ToolFailure::new(format!(                "The vault login {secret} names no client id: file the OAuth client with its client id as the username and its secret as the password."            )))        }        Some((other, _)) => {            return Err(ToolFailure::new(format!(                "The vault secret {secret} is a {other}, not a login, so it holds no OAuth client (the client id as the username, the secret as the password)."            )))        }        None => {            return Err(ToolFailure::new(format!(                "No secret {secret} is in this database's vault (or it is in the bin). Pass the id of the OAuth client the owner filed."            )))        }    }    let name = require_string(args, "name").unwrap_or_else(|| ConnectionKind::Tailscale.default_name().to_string());    let id = create(ctx, ConnectionKind::Tailscale, &name, &reaches, Some(&secret), json!({}))?;    ctx.commit()?;    let row = existing(ctx, &id)?;    let text = |key: &str| row.get(key).cloned().unwrap_or(Value::Null);    Ok(json!({        "connection": {            "id": id,            "kind": "tailscale",            "name": text("name"),            "reaches": text("reaches"),            "state": text("state"),        },        "note": "Connected. From now on every device tries the tailnet after the home network and before the relay; nothing else changes."    }))}/// Gmail's own domains: their calendar is Google's OAuth door, never CalDAV./// Public so the connect test names a Gmail mailbox from this table and never/// writes one into the tree (the no-real-identities guard reads any/// `<local>@gmail.com` literal as a person's).pub const GOOGLE_MAIL_DOMAINS: [&str; 2] = ["gmail.com", "googlemail.com"];fn is_google_address(address: &str) -> bool {    matches!(address.rsplit_once('@').map(|(_, domain)| domain), Some(domain) if GOOGLE_MAIL_DOMAINS.contains(&domain))}