Cotton code
221 lines · 12.8 KB · RustRaw
//! The Domains tool as data, installed by the bridge and filled through the//! generic verbs with rows the Cloudflare mapping shaped — the two halves//! meeting: what `connections::mapping` produces is what `create_record`//! takes, dates, numbers, bools and the link included.mod support;use cotton_tools::connections::domains::{self, DNS_RECORD, DOMAIN};use cotton_tools::mcp::dispatch::{Ctx, ToolServices};use serde_json::{json, Value};use cotton_tools::mcp::handlers::tables::{create_produced_record, update_produced_record};use std::sync::Arc;use support::{    mcp::{call_tool, call_tool_raw, mint_token},    Harness,};fn as_bridge<T>(h: &Harness, f: impl FnOnce(&mut Ctx<'_>) -> T) -> T {    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("mcp-bridge"),            "job:mcp-bridge",            cotton_tools::clock::Clock::now(&h.clock),            Arc::clone(&h.random),            &services,            &audit,        );        let out = f(&mut ctx);        ctx.commit().expect("commits");        out    })}/// RULE: The bridge installs Domains once, idempotently, and the rows the Cloudflare mapping shapes are rows the tables take.////// A column the mapping writes that the table refuses would fail here, not on/// the serving Mac.#[test]fn domains_installs_once_and_takes_the_rows_the_cloudflare_mapping_shapes() {    let mut h = Harness::new();    assert!(as_bridge(&h, |ctx| domains::add(ctx).unwrap()), "installed the first time");    assert!(!as_bridge(&h, |ctx| domains::add(ctx).unwrap()), "already there the second time");    let secret = mint_token(&mut h, &["read", "write"], "Assistant");    let tools = call_tool(&h, &secret, "list_tools", json!({}));    assert!(tools["tools"].as_array().unwrap().iter().any(|tool| tool["definition"]["id"] == "domains"), "{tools}");    let mapping = domains::cloudflare_mapping();    let zone = json!({"id":"023e105f4ecef8ad9ca31a8372d0c353","name":"cottondb.com","status":"active","plan":{"name":"Free Website"},        "name_servers":["ada.ns.cloudflare.com","bob.ns.cloudflare.com"],"created_on":"2024-05-01T10:00:00.000000Z","account":{"name":"Asha's Account"}});    let shaped = mapping.calls[0].shape(&zone).unwrap();    let made = as_bridge(&h, |ctx| create_produced_record(ctx, json!({"table": DOMAIN, "data": Value::Object(shaped.data.clone())}).as_object().unwrap()).expect("a producer write"));    let domain_id = made["record"]["id"].as_str().expect("a record id").to_string();    assert_eq!(made["record"]["data"]["name"], "cottondb.com");    assert_eq!(made["record"]["data"]["created"], "2024-05-01");    assert_eq!(made["record"]["data"]["external_id"], "023e105f4ecef8ad9ca31a8372d0c353");    let registrar = json!({"name":"cottondb.com","expires_at":"2027-04-30T00:00:00Z","auto_renew":true,"registrar":"cloudflare"});    let shaped = mapping.calls[1].shape(&registrar).unwrap();    assert_eq!(shaped.key, "cottondb.com");    let mut patch = shaped.data.clone();    patch.remove("name");    let updated = as_bridge(&h, |ctx| update_produced_record(ctx, json!({"table": DOMAIN, "id": domain_id, "patch": Value::Object(patch)}).as_object().unwrap()).expect("a producer write"));    assert_eq!(updated["record"]["data"]["expires"], "2027-04-30");    assert_eq!(updated["record"]["data"]["auto_renew"], true);    let record = json!({"id":"372e67954025e0ba6aaa6d586b9e0b59","zone_id":"023e105f4ecef8ad9ca31a8372d0c353","name":"www.cottondb.com","type":"CNAME",        "content":"cottondb.pages.dev","ttl":1,"proxied":true,"priority":null,"comment":"the site"});    let shaped = mapping.calls[2].shape(&record).unwrap();    assert_eq!(shaped.links, vec![("domain".to_string(), DOMAIN.to_string(), "external_id".to_string(), "023e105f4ecef8ad9ca31a8372d0c353".to_string())]);    let mut data = shaped.data.clone();    data.insert("domain".into(), Value::from(domain_id.clone()));    let made = as_bridge(&h, |ctx| create_produced_record(ctx, json!({"table": DNS_RECORD, "data": Value::Object(data)}).as_object().unwrap()).expect("a producer write"));    assert_eq!(made["record"]["data"]["domain"], domain_id);    assert_eq!(made["record"]["data"]["proxied"], true);    assert_eq!(made["record"]["data"]["ttl"], 1);    assert!(made["record"]["data"].get("priority").is_none_or(Value::is_null));    let listed = call_tool(&h, &secret, "list_records", json!({"table": DNS_RECORD, "where": {"external_id": "372e67954025e0ba6aaa6d586b9e0b59"}}));    assert_eq!(listed["records"].as_array().map(Vec::len), Some(1), "{listed}");}/// RULE: Only trusted producers fill readonly facts; authored writes and Undo cannot rewrite them, and producer writes still check types and column names so a bad provider response cannot corrupt records.#[test]fn producer_facts_are_checked_and_cannot_be_authored() {    let mut h = Harness::new();    as_bridge(&h, |ctx| domains::add(ctx).unwrap());    let secret = mint_token(&mut h, &["read", "write"], "Assistant");    let data = json!({"name":"example.test", "external_id":"provider-zone"});    assert!(call_tool_raw(&h, &secret, "create_record", json!({"table": DOMAIN, "data":data})).is_error);    let made = as_bridge(&h, |ctx| create_produced_record(ctx, json!({"table":DOMAIN,"data":data}).as_object().unwrap()).unwrap());    let id = made["record"]["id"].as_str().unwrap();    assert!(call_tool_raw(&h, &secret, "undo", json!({"change_id":made["change"]["id"]})).is_error,        "Undo cannot rewrite a producer's readonly facts");    assert!(call_tool_raw(&h, &secret, "update_record", json!({"table":DOMAIN,"id":id,"patch":{"external_id":"authored"}})).is_error);    for patch in [json!({"external_id":42}), json!({"invented":"value"})] {        assert!(as_bridge(&h, |ctx| update_produced_record(ctx, json!({"table":DOMAIN,"id":id,"patch":patch}).as_object().unwrap())).is_err());    }    let kept = call_tool(&h, &secret, "get_record_by_table", json!({"table":DOMAIN,"id":id}));    assert_eq!(kept["data"]["external_id"], "provider-zone");}/// RULE: Domains needs no connection — add_tool puts it in a database and a domain written by hand takes the whole row: registrar, expiry, DNS at, what it points to, whom it is managed for.////// Before this, the only door was the Cloudflare bridge's first pass, so a/// person with a domain at any other registrar had no place to write it.#[test]fn domains_is_added_with_no_connection_and_takes_a_row_written_by_hand() {    let mut h = Harness::new();    let secret = mint_token(&mut h, &["read", "write"], "Assistant");    assert_eq!(call_tool(&h, &secret, "add_tool", json!({"tool_id": "domains"}))["added"], true);    assert_eq!(call_tool(&h, &secret, "add_tool", json!({"tool_id": "domains"}))["added"], false, "adding it again changes nothing");    let made = call_tool(        &h,        &secret,        "create_record",        json!({"table": DOMAIN, "data": {            "name": "example.com", "registrar": "A registrar", "expires": "2027-04-30", "dns_at": "cloudflare",            "points_to": "front_door", "managed_for": "Rina's kitchen"        }}),    );    let data = &made["record"]["data"];    assert_eq!(data["dns_at"], "cloudflare", "{made}");    assert_eq!(data["points_to"], "front_door");    assert_eq!(data["managed_for"], "Rina's kitchen");    assert_eq!(data["expires"], "2027-04-30");    let table = domains::package().tables.into_iter().find(|table| table.id == DOMAIN).unwrap();    let points_to = table.columns.iter().find(|column| column.key == "points_to").expect("points_to");    assert_eq!(points_to.choices.as_deref(), Some(&["front_door".to_string(), "page".to_string(), "elsewhere".to_string()][..]));}/// The package as a build before these columns shipped it: the same tool,/// `domain` without what was added since.fn package_before(dropped: &[&str]) -> cotton_core::definitions::package::ToolPackage {    let mut package = domains::package();    for table in package.tables.iter_mut().filter(|table| table.id == DOMAIN) {        let mut raw = serde_json::to_value(&*table).unwrap();        let keeps = |key: &Value| !key.as_str().is_some_and(|key| dropped.contains(&key));        raw["columns"].as_array_mut().unwrap().retain(|column| keeps(&column["key"]));        raw["slip"]["subtitle"].as_array_mut().unwrap().retain(keeps);        let page = raw["page"].as_array_mut().unwrap();        for section in page.iter_mut() {            if let Some(columns) = section["columns"].as_array_mut() {                columns.retain(keeps);            }        }        page.retain(|section| section["columns"].as_array().is_none_or(|columns| !columns.is_empty()));        *table = serde_json::from_value(raw).expect("the older table parses");        table.validate().expect("the older table validates");    }    package}/// RULE: A Domains installed by an older build is brought to this build's columns in place, its rows untouched, and a table already holding every column is never rewritten.////// A package's definitions are not seeded at server start, so without this/// the owner's database — which has held Domains since the first Cloudflare/// pass — would never gain DNS at, Points to or Managed for; and rewriting a/// table that lacks nothing would undo whatever the person changed on it.#[test]fn a_domains_installed_by_an_older_build_gains_the_new_columns_and_keeps_its_rows() {    let mut h = Harness::new();    let older = package_before(&["dns_at", "points_to", "destination", "managed_for"]);    as_bridge(&h, |ctx| {        cotton_tools::mcp::handlers::tool_packages::install_package(ctx, &older, cotton_tools::mcp::handlers::tool_packages::Door::Cotton, false).expect("the older package installs")    });    let secret = mint_token(&mut h, &["read", "write"], "Assistant");    let made = call_tool(&h, &secret, "create_record", json!({"table": DOMAIN, "data": {"name": "example.com", "expires": "2027-04-30"}}));    let id = made["record"]["id"].as_str().expect("a record id").to_string();    assert!(as_bridge(&h, |ctx| domains::add(ctx).unwrap()), "an older shape is upgraded");    assert!(!as_bridge(&h, |ctx| domains::add(ctx).unwrap()), "and then left alone");    let updated = call_tool(&h, &secret, "update_record", json!({"table": DOMAIN, "id": id, "patch": {"dns_at": "cloudflare", "points_to": "elsewhere"}}));    assert_eq!(updated["record"]["data"]["dns_at"], "cloudflare", "{updated}");    assert_eq!(updated["record"]["data"]["name"], "example.com", "the row made before the upgrade is the same row");    assert_eq!(updated["record"]["data"]["expires"], "2027-04-30");}/// RULE: Whatever door Domains comes in by, the table that is written is this build's own — a kit or a package that carries a `domain` table with other commands installs the shipped one.////// Domains' page offers acts an engine does (Register spends the owner's/// money). Its commands are the build's; a saved kit is data anyone can edit,/// and must not be a way to put another act on that page.#[test]fn a_domain_table_from_any_other_door_is_written_as_the_build_ships_it() {    let h = Harness::new();    let mut doctored = domains::package();    for table in doctored.tables.iter_mut().filter(|table| table.id == DOMAIN) {        let mut raw = serde_json::to_value(&*table).unwrap();        raw["commands"].as_array_mut().unwrap().push(json!({            "id": "forget", "label": "Forget this database", "kind": "update", "method": "databases.remove", "bindings": {"id": "$id"}        }));        raw["commands"][0]["label"] = json!("Something else");        *table = serde_json::from_value(raw).expect("the doctored table parses");    }    as_bridge(&h, |ctx| {        cotton_tools::mcp::handlers::tool_packages::install_package(ctx, &doctored, cotton_tools::mcp::handlers::tool_packages::Door::Kit, false).expect("installs");    });    let stored = as_bridge(&h, |ctx| cotton_tools::mcp::handlers::tables::definition(ctx, DOMAIN).unwrap());    let shipped = domains::carried_table(DOMAIN).expect("domain is carried");    assert_eq!(stored.commands, shipped.commands, "the commands are the build's");    let ids: Vec<&str> = shipped.commands.iter().flatten().map(|command| command.id.as_str()).collect();    assert_eq!(ids, ["check_price", "register", "hand_over", "reach_here"]);    // The domain's own acts, and the household's reach set to it — the one    // write that is not the domain's (`workspace.setReach`).    for command in shipped.commands.iter().flatten() {        assert!(            command.method.as_deref().is_some_and(|method| method.starts_with("domains.") || method == "workspace.setReach"),            "{}",            command.id        );    }    assert!(domains::carried_table(DNS_RECORD).is_none(), "only the table that carries acts is carried");}