Cotton code
224 lines · 9.6 KB · RustRaw
//! A shared editor's identity is a signed key binding, never their display name.mod support;use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};use cotton_core::keys::{statements, PersonKey};use cotton_tools::clock::Clock;use cotton_tools::mcp::dispatch::{self, Ctx};use rusqlite::types::Value as Sql;use serde_json::{json, Value};use support::harness::Harness;const NOW: &str = "2026-10-04T07:00:00.000Z";fn text(s: &str) -> Sql {    Sql::Text(s.into())}// These signed serving facts keep their ordered admission/device/author stamps;// fixture reconciliation would replace them all with device:fixture.fn stamp(n: u32, author: &str) -> String {    format!("1700000000000:{n:04}:{author}")}fn admission(h: &Harness, id: &str, key: &PersonKey, rights: &str, owner: &PersonKey, n: u32) {    let p = key.public_key();    let o = owner.public_key();    let sig = URL_SAFE_NO_PAD.encode(owner.sign(&statements::admission_bytes(        &h.workspace_id,        &p,        rights,        None,        NOW,    )));    h.db.run("INSERT INTO cotton_admissions (id,workspace_id,person_key,person_name,rights,admitted_by_person,p_sig,admitted_at,_hlc,_born) VALUES (?,?,?,'Mira Fern',?,?,?,?,?,?)",        &[text(id),text(&h.workspace_id),text(&p),text(rights),text(&o),text(&sig),text(NOW),text(&stamp(n,"serving")),text(&stamp(n,"serving"))]).unwrap();}fn claim(h: &Harness, admission_id: &str, key: &PersonKey, person: &str) {    // Independently construct the statement: the reader must verify the stored    // proof, so a raw/unsigned overlay can never silently create a byline.    let mut bytes = Vec::new();    for part in [        "cotton-member-person-v1",        &h.workspace_id,        admission_id,        &key.public_key(),        person,        NOW,    ] {        bytes.extend_from_slice(&(part.len() as u32).to_be_bytes());        bytes.extend_from_slice(part.as_bytes());    }    h.db.run("INSERT INTO cotton_member_person_claims (id,workspace_id,admission_id,person_key,person_id,p_sig,claimed_at,_hlc) VALUES (?,?,?,?,?,?,?,?)",        &[text(&format!("claim-{admission_id}")),text(&h.workspace_id),text(admission_id),text(&key.public_key()),text(person),text(&URL_SAFE_NO_PAD.encode(key.sign(&bytes))),text(NOW),text(&stamp(30,"serving"))]).unwrap();}fn author(h: &Harness, id: &str, key: &PersonKey, device: &PersonKey, n: u32) {    let p = key.public_key();    let d = device.public_key();    let vault = URL_SAFE_NO_PAD.encode([42; 32]);    let ps = URL_SAFE_NO_PAD.encode(key.sign(&statements::device_statement_bytes(        &h.workspace_id,        &p,        &d,        &vault,    )));    let ds = URL_SAFE_NO_PAD.encode(device.sign(&statements::device_consent_bytes(        &h.workspace_id,        &p,        &d,        &vault,    )));    h.db.run("INSERT INTO cotton_device_statements (id,workspace_id,person_key,device_key,vault_public_key,device_name,p_sig,d_sig,made_at,_hlc) VALUES (?,?,?,?,?,'Invented phone',?,?,?,?)",        &[text(&format!("st-{id}")),text(&h.workspace_id),text(&p),text(&d),text(&vault),text(&ps),text(&ds),text(NOW),text(&stamp(n,"serving"))]).unwrap();    h.db.run("INSERT INTO cotton_authors (id,workspace_id,device_id,minted_at,reason,first_stamp,_hlc) VALUES (?,?,?,?,'first',?,?)",        &[text(id),text(&h.workspace_id),text(&d),text(NOW),text(&stamp(n,id)),text(&stamp(n,"serving"))]).unwrap();}fn record(h: &Harness, id: &str, author: &str) {    h.db.run("INSERT INTO cotton_notes (id,workspace_id,kind,title,body,created_at,updated_at,_hlc) VALUES (?,?,'note','Invented note','Invented words',?,?,?)",        &[text(id),text(&h.workspace_id),text(NOW),text(NOW),text(&stamp(40,author))]).unwrap();}fn page(h: &Harness, id: &str) -> Value {    // Exercise the real read dispatcher without the shared write-test helper's    // reconciliation, which rewrites the deliberately ordered signed stamps.    let scopes = vec!["read".to_string()];    let audit = |_: &str, _: &str| {};    let mut ctx = Ctx::new(        &h.db,        &h.file,        &h.owner_id,        "Invented reader",        "invented-read-token",        &scopes,        h.clock.now(),        h.random.clone(),        None,        &h.services.services,        &audit,    );    let args = json!({"table":"note","id":id});    dispatch::call_tool(&mut ctx, "get_record_by_table", args.as_object().unwrap()).unwrap()}// Equal names, pre-links and the paired-owner fallback must not invent an// editor identity. Reads resolve the signed member's current local People row// and canonical avatar, without writing or creating a person.#[test]fn member_person_byline_uses_only_own_claim_and_current_local_print() {    let h = Harness::new();    h.run(        "UPDATE cotton_workspaces SET kind='shared' WHERE id=?",        &[text(&h.workspace_id)],    );    let owner = PersonKey::from_seed([11; 32].into());    let a = PersonKey::from_seed([12; 32].into());    let b = PersonKey::from_seed([13; 32].into());    admission(&h, "owner-admission", &owner, "owner", &owner, 0);    admission(&h, "a-admission", &a, "member", &owner, 10);    admission(&h, "b-admission", &b, "member", &owner, 11);    let photo_a = format!("{}/people/fern-a/avatar/current.jpg", h.workspace_id);    let photo_b = format!("{}/people/fern-b/avatar/current.jpg", h.workspace_id);    for (id, photo) in [("fern-a", &photo_a), ("fern-b", &photo_b)] {        h.run("INSERT INTO cotton_people (id,workspace_id,full_name,avatar_key,created_at,updated_at) VALUES (?,?,'Mira Fern',?,?,?)",            &[text(id),text(&h.workspace_id),text(photo),text(NOW),text(NOW)]);    }    author(        &h,        "author-a",        &a,        &PersonKey::from_seed([21; 32].into()),        20,    );    author(        &h,        "author-b",        &b,        &PersonKey::from_seed([22; 32].into()),        21,    );    record(&h, "note-a", "author-a");    record(&h, "note-b", "author-b");    record(&h, "note-unknown", "unknown-author");    h.db.run(        "UPDATE cotton_admissions SET suggested_person_id='fern-a' WHERE id='b-admission'",        &[],    )    .unwrap();    let people_before =        h.db.get("SELECT COUNT(*) AS n FROM cotton_people", &[])            .unwrap()            .unwrap()            .int("n");    let suggested = page(&h, "note-b");    assert_eq!(suggested.get("edited_by_person_id"), Some(&Value::Null));    assert_eq!(suggested.get("edited_by_photo_key"), Some(&Value::Null));    claim(&h, "a-admission", &a, "fern-a");    claim(&h, "b-admission", &b, "fern-b");    assert!(        cotton_store::member_person::bound_person(&h.db, &h.workspace_id, &a.public_key())            .unwrap()            .is_some(),        "signed claim fixture resolves"    );    assert!(        cotton_core::keys::member_actions::author_person(            &h.db,            &h.workspace_id,            &stamp(40, "author-a")        )        .unwrap()        .is_some(),        "signed device fixture resolves"    );    let page_a = page(&h, "note-a");    let page_b = page(&h, "note-b");    assert_eq!(page_a["edited_by"], page_b["edited_by"]);    assert_eq!(page_a["edited_by_person_id"], "fern-a");    assert_eq!(page_b["edited_by_person_id"], "fern-b");    assert_eq!(page_a["edited_by_photo_key"], photo_a);    assert_eq!(page_b["edited_by_photo_key"], photo_b);    let replacement = format!("{}/people/fern-a/avatar/replacement.jpg", h.workspace_id);    h.run(        "UPDATE cotton_people SET avatar_key=? WHERE id='fern-a'",        &[text(&replacement)],    );    assert_eq!(page(&h, "note-a")["edited_by_photo_key"], replacement);    h.run(        "UPDATE cotton_people SET avatar_key=NULL WHERE id='fern-a'",        &[],    );    assert!(page(&h, "note-a")["edited_by_photo_key"].is_null());    assert_eq!(page(&h, "note-a")["edited_by_person_id"], "fern-a");    h.db.run(        "UPDATE cotton_member_person_claims SET person_id='fern-a' WHERE id='claim-b-admission'",        &[],    )    .unwrap();    assert!(        page(&h, "note-b")["edited_by_person_id"].is_null(),        "unsigned substituted id verifies nothing"    );    assert!(page(&h, "note-unknown")["edited_by_person_id"].is_null());    // A paired device has the legacy owner's text, but no explicit signed link.    h.run("INSERT INTO cotton_authors (id,workspace_id,device_id,minted_at,reason,first_stamp) VALUES ('owner-author',?,'paired-owner',?,'first',?)",&[text(&h.workspace_id),text(NOW),text(&stamp(30,"owner-author"))]);    claim(&h, "owner-admission", &owner, "fern-a");    record(&h, "note-owner", "owner-author");    assert_eq!(page(&h, "note-owner")["edited_by"], "Mira Fern");    assert!(page(&h, "note-owner")["edited_by_person_id"].is_null());    h.run("INSERT INTO cotton_workspaces (id,name,owner_user_id,created_at) VALUES ('22222222-2222-4222-8222-222222222222','Invented foreign database','invented-owner',?)",&[text(NOW)]);    h.db.run("UPDATE cotton_people SET workspace_id='22222222-2222-4222-8222-222222222222' WHERE id='fern-a'",&[]).unwrap();    assert!(        page(&h, "note-a")["edited_by_person_id"].is_null(),        "foreign database person is never an editor identity"    );    h.db.run(        "UPDATE cotton_people SET workspace_id=? WHERE id='fern-a'",        &[text(&h.workspace_id)],    )    .unwrap();    h.run("DELETE FROM cotton_people WHERE id='fern-a'", &[]);    assert!(page(&h, "note-a")["edited_by_person_id"].is_null());    assert_eq!(        h.db.get("SELECT COUNT(*) AS n FROM cotton_people", &[])            .unwrap()            .unwrap()            .int("n"),        people_before.map(|n| n - 1),        "identity reads never create People rows"    );}