Cotton code
147 lines · 9.0 KB · RustRaw
mod support;use cotton_store::actor::{Actor, TokenId};use cotton_tools::{clock::Clock, mcp::{dispatch::{self, Ctx}, handlers::tables}};use serde_json::{json, Value};use support::{Harness, mcp::{mint_token, call_tool_as_owner}};// Use the transport's typed token actor (the shared harness normally uses a test job).fn call(h: &Harness, secret: &str, verb: &str, args: Value) -> Result<Value, String> {    support::harness::reconcile_all(&h.db);    let connection = h.connection(secret);    let token = TokenId::in_file(&h.db, &connection.id).unwrap();    call_as_token(h, secret, token, verb, args)}fn call_as_token(h: &Harness, secret: &str, token: TokenId, verb: &str, args: Value) -> Result<Value, String> {    support::harness::reconcile_all(&h.db);    let connection = h.connection(secret);    let audit = |_: &str, _: &str| {};    let actor = Actor::Token(token);    let mut ctx = Ctx::new(&h.db, &h.file, &h.owner_id, &connection.name, &connection.id,        &connection.scopes, h.clock.now(), h.random.clone(), Some(actor), &h.services.services, &audit);    dispatch::call_tool(&mut ctx, verb, args.as_object().unwrap()).map_err(|error| error.message().to_string())}fn define(h: &Harness, producer: Option<&str>) {    define_table(h, "lane", producer);}fn define_table(h: &Harness, table: &str, producer: Option<&str>) {    let fixture = match table {        "lane" => include_str!("fixtures/work/tables/lane.json"),        "cut" => include_str!("fixtures/work/tables/cut.json"),        _ => panic!("unknown synthetic table"),    };    let mut raw: Value = serde_json::from_str(fixture).unwrap();    raw["picture"] = Value::Null;    if let Some(token) = producer { raw["producer"] = json!({"token_id":token}); }    else { raw.as_object_mut().unwrap().remove("producer"); }    cotton_core::definitions::TableDefinition::authored(&raw).unwrap().validate_import().unwrap();    h.run("INSERT INTO cotton_table_definitions (id, workspace_id, definition, builtin, created_at, updated_at) VALUES (?, ?, ?, 0, '2026-10-15', '2026-10-15')",        &[rusqlite::types::Value::Text(table.into()), rusqlite::types::Value::Text(h.workspace_id.clone()), rusqlite::types::Value::Text(raw.to_string())]);}/// RULE: Only the authenticated declared token writes readonly facts; owner edits, other tokens, claimed identities and Undo cannot forge producer state. Where no producer is declared, the app (the owner at a device) fills a readonly fact as it makes the record, and nothing patches it.#[test]fn readonly_producer_authority_is_authenticated_and_undo_is_refused() {    for declared in [false, true] {        let mut h = Harness::new();        let producer = mint_token(&mut h, &["read", "write"], "Work fold");        let other = mint_token(&mut h, &["read", "write"], "Work fold");        let token_id = h.connection(&producer).id;        define(&h, declared.then_some(token_id.as_str()));        let data = json!({"name":"Synthetic lane", "status_line":"Building"});        for secret in [&other, &producer] {            if declared && secret == &producer { continue; }            let error = call(&h, secret, "create_record", json!({"table":"lane","data":data,"producer":{"token_id":token_id}})).unwrap_err();            assert!(error.contains("read only"), "{error}");        }        // The owner at a device is the app: on a table with a declared producer        // only the producer names a readonly fact; with none, the app fills it        // as it makes the record (the readonly rule of 5 Nov 2026).        let by_app = call_tool_as_owner(&h, "synthetic-phone", "create_record", json!({"table":"lane","data":data}));        assert_eq!(by_app.is_error, declared, "{}", by_app.text);        let made = if declared {            call(&h, &producer, "create_record", json!({"table":"lane","data":data})).unwrap()        } else {            call(&h, &producer, "create_record", json!({"table":"lane","data":{"name":"Synthetic lane"}})).unwrap()        };        let id = &made["record"]["id"];        for secret in [&other, &producer] {            if declared && secret == &producer { continue; }            assert!(call(&h, secret, "update_record", json!({"table":"lane","id":id,"patch":{"status_line":"Forged"}})).is_err());        }        assert!(call_tool_as_owner(&h, "synthetic-phone", "update_record", json!({"table":"lane","id":id,"patch":{"status_line":"Forged"}})).is_error);        if declared {            assert_eq!(made["change"]["undoable"], false);            let updated = call(&h, &producer, "update_record", json!({"table":"lane","id":id,"patch":{"status_line":"Landed"}})).unwrap();            assert_eq!(updated["record"]["data"]["status_line"], "Landed");            for change in [&made["change"]["id"], &updated["change"]["id"]] {                for secret in [&producer, &other] {                    assert!(call(&h, secret, "undo", json!({"change_id":change})).unwrap_err().contains("read only"));                }                assert!(call_tool_as_owner(&h, "synthetic-phone", "undo", json!({"change_id":change})).is_error);            }        } else {            // Even an existing producer receipt from before a declaration was removed stays protected.            let audit = |_: &str, _: &str| {};            let mut ctx = Ctx::for_worker(&h.db, &h.file, &h.owner_id,                cotton_tools::mcp::writer::job("test"), "Synthetic producer", h.clock.now(),                h.random.clone(), &h.services.services, &audit);            let changed = tables::update_produced_record(&mut ctx, json!({"table":"lane","id":id,"patch":{"status_line":"Produced"}}).as_object().unwrap()).unwrap();            ctx.commit().unwrap();            drop(ctx);            for secret in [&producer, &other] {                assert!(call(&h, secret, "undo", json!({"change_id":changed["change"]["id"]})).is_err());            }            assert!(call_tool_as_owner(&h, "synthetic-phone", "undo", json!({"change_id":changed["change"]["id"]})).is_error);        }        let kept = call(&h, &producer, "get_record_by_table", json!({"table":"lane","id":id})).unwrap();        assert_eq!(kept["data"]["status_line"], if declared { "Landed" } else { "Produced" });    }}/// RULE: A token carried from another database is identified by both home and token ID, because the same bare ID must not grant authority in a different home.#[test]fn carried_producer_matches_the_authenticated_home_and_token() {    let mut h = Harness::new();    let secret = mint_token(&mut h, &["read", "write"], "Work fold");    let token = h.connection(&secret).id;    define(&h, Some(&format!("synthetic-home:{token}")));    let args = json!({"table":"lane","data":{"name":"Synthetic carried lane", "status_line":"Building"}});    assert!(call(&h, &secret, "create_record", args.clone()).is_err());    let wrong = TokenId::carried(&h.db, "different-home", &token).unwrap();    assert!(call_as_token(&h, &secret, wrong, "create_record", args.clone()).is_err());    let right = TokenId::carried(&h.db, "synthetic-home", &token).unwrap();    let made = call_as_token(&h, &secret, right, "create_record", args).unwrap();    assert_eq!(made["record"]["data"]["status_line"], "Building");}/// RULE: Producer authority belongs to one table, because Work's lane fold must not forge cut reports and its cut writer must not forge lane facts.#[test]fn lane_and_cut_each_admit_only_their_own_producer() {    let mut h = Harness::new();    let lane = mint_token(&mut h, &["read", "write"], "Synthetic lane fold");    let cut = mint_token(&mut h, &["read", "write"], "Synthetic cut writer");    define_table(&h, "lane", Some(&h.connection(&lane).id));    define_table(&h, "cut", Some(&h.connection(&cut).id));    for (table, own, other, facts) in [        ("lane", &lane, &cut, json!({"status_line":"Building", "landed":1, "last_heard_at":"2026-10-15T10:00:00Z"})),        ("cut", &cut, &lane, json!({"reports":"Synthetic check passed", "waiting_on":"Synthetic build", "waiting_since":"2026-10-15T10:00:00Z",            "record_page_ms":10,"record_page_budget_ms":100,"cold_start_ms":20,"cold_start_budget_ms":200,            "speed_measured_on":"Synthetic Mac","speed_gates":true})),    ] {        let mut data = facts.clone();        data["name"] = json!("Synthetic producer row");        assert!(call(&h, other, "create_record", json!({"table":table,"data":data})).is_err());        let made = call(&h, own, "create_record", json!({"table":table,"data":data})).unwrap();        let id = &made["record"]["id"];        let clear = facts.as_object().unwrap().keys().map(|key| (key.clone(), Value::Null)).collect::<serde_json::Map<_,_>>();        assert!(call(&h, other, "update_record", json!({"table":table,"id":id,"patch":clear})).is_err());        assert!(call_tool_as_owner(&h, "synthetic-phone", "update_record", json!({"table":table,"id":id,"patch":clear})).is_error);        let updated = call(&h, own, "update_record", json!({"table":table,"id":id,"patch":clear})).unwrap();        assert_eq!(updated["change"]["undoable"], false);        assert!(call(&h, own, "undo", json!({"change_id":updated["change"]["id"]})).is_err());    }}