Cotton code
296 lines · 12.8 KB · RustRaw
//! The membership of the window's database, read from its local facts.use cotton_store::membership::{self, Rights};use cotton_store::Driver;use serde_json::{json, Map, Value};use crate::shell::client::ClientController;pub fn invite(    handle: &crate::handle::CottonHandle,    request: &Value,) -> Result<Value, crate::methods::MethodError> {    super::member_actions::invite(handle, request)}pub fn remove(    handle: &crate::handle::CottonHandle,    request: &Value,) -> Result<Value, crate::methods::MethodError> {    super::member_actions::remove(handle, request)}pub fn read(client: &ClientController, _args: &Map<String, Value>) -> Result<Value, String> {    let device = client.self_device_id();    // The household's person: an owner's device PAIRED into the household    // holds the owner's person key and no device statement in a shared file    // (only a member's devices are stated), so it is the owner by that key.    let household_person = super::vault::person_public_key(client).ok();    // The person's own database (none named, or the one named is it) admits nobody.    let personal = match crate::shell::client::named_database() {        None => true,        Some(named) => client            .databases()            .ok()            .and_then(|held| held.into_iter().find(|database| database.id == named))            .is_some_and(|database| database.personal),    };    client.with_file(|file| {        answer(            file.driver,            device.as_deref(),            household_person.as_deref(),            personal,        )        .map_err(|error| error.to_string())    })}fn answer(    db: &Driver,    device: Option<&str>,    household_person: Option<&str>,    personal: bool,) -> cotton_store::Result<Value> {    let mut me = device        .map(|key| membership::device(db, key))        .transpose()?        .flatten()        .map(|(person, _)| person);    let owner = membership::owner(db)?;    if me.is_none() {        if let Some(person) = household_person {            if membership::of(db, person)?.is_some() {                me = Some(person.to_owned());            }        }    }    let mut members = Vec::new();    for row in db.all(        "SELECT person_key, person_name,workspace_id,suggested_person_id FROM cotton_admissions a \         WHERE id = (SELECT id FROM cotton_admissions b WHERE b.person_key = a.person_key ORDER BY _hlc DESC, id DESC LIMIT 1) \         ORDER BY person_key",        &[],    )? {        let key = row.text("person_key").unwrap_or_default();        let Some(rights) = membership::of(db, key)? else { continue };        let database=row.text("workspace_id").unwrap_or_default();        let bound=cotton_store::member_person::bound_person(db,database,key)?;        members.push(json!({            "personKey": key,            "name": row.text("person_name").unwrap_or_default(),            "rights": if rights.admits() { "admin" } else { "member" },            "isOwner": rights == Rights::Owner,            "personId": bound.as_ref().map(|p| &p.person_id),            "photoKey": bound.as_ref().and_then(|p| p.photo_key.as_ref()),            "suggestedPersonId": row.text("suggested_person_id"),        }));    }    let my_rights = me        .as_deref()        .map(|key| membership::of(db, key))        .transpose()?        .flatten();    let admit_reason = admit_refusal(personal, owner.as_deref(), my_rights);    Ok(json!({        "ownership": membership::resolved_ownership(db)?,        "members": members,        "me": me,        "canAdmit": admit_reason.is_none(),        "admitReason": admit_reason,    }))}/// Why "Admit a person" cannot run in this database, in words, or `None`/// when it can. Admitting is signed against the file's own owner admission/// (`cotton_server::members` refuses with `owner_membership_missing`/// without one), and only the owner or an admin admits; the act is never/// drawn as a button that does nothing.fn admit_refusal(    personal: bool,    owner: Option<&str>,    my_rights: Option<Rights>,) -> Option<&'static str> {    if personal {        return Some(ADMIT_PERSONAL);    }    if owner.is_none() {        return Some(ADMIT_NO_OWNER);    }    match my_rights {        Some(rights) if rights.admits() => None,        Some(_) => Some(ADMIT_NOT_ADMIN),        None => Some(ADMIT_NOT_A_MEMBER),    }}// The words are the Members list's own (`MemberWords` in the app)./// The person's own database admits nobody.pub const ADMIT_PERSONAL: &str =    "Your personal database is yours alone. To share, make a project database and admit people there.";/// The file does not yet hold its signed owner admission.pub const ADMIT_NO_OWNER: &str =    "People can be admitted once your Mac has signed this database as yours. It does that the next time it opens it.";/// The reader is a plain member.pub const ADMIT_NOT_ADMIN: &str = "Only the owner or an admin of this database admits people.";/// This device is not known as a member's device here.pub const ADMIT_NOT_A_MEMBER: &str = "This device is not yet known as one of a member's devices in this database, so it cannot admit a person.";#[cfg(test)]mod tests {    use super::*;    use rusqlite::types::Value as Sql;    const DATABASE: &str = "11111111-1111-4111-8111-111111111111";    const NOW: &str = "2026-10-04T00:00:00.000Z";    // The member row draws only an own signed claim's canonical local print;    // suggestions and an absent/cleared print remain optional, never invented.    #[test]    fn member_person_read_fields_follow_the_signed_claim_and_current_print() {        use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};        let db = file();        let person = cotton_core::keys::PersonKey::from_seed([47; 32].into());        let key = person.public_key();        admission(&db, "fern-admission", &key, "member", "0010");        let photo = format!("{DATABASE}/people/fern/avatar/current.jpg");        db.run("INSERT INTO cotton_people (id,workspace_id,full_name,avatar_key,created_at,updated_at) VALUES ('fern',?,'Mira Fern',?,?,?)",&[text(DATABASE),text(&photo),text(NOW),text(NOW)]).unwrap();        db.run(            "UPDATE cotton_admissions SET suggested_person_id='fern' WHERE id='fern-admission'",            &[],        )        .unwrap();        let read = || {            answer(&db, None, Some("owner-key"), false).unwrap()["members"]                .as_array()                .unwrap()                .iter()                .find(|r| r["personKey"] == key)                .unwrap()                .clone()        };        let suggested = read();        assert_eq!(suggested["suggestedPersonId"], "fern");        assert_eq!(suggested.get("personId"), Some(&Value::Null));        assert_eq!(suggested.get("photoKey"), Some(&Value::Null));        let bytes =            cotton_store::member_person::claim_bytes(DATABASE, "fern-admission", &key, "fern", NOW);        db.run("INSERT INTO cotton_member_person_claims (id,workspace_id,admission_id,person_key,person_id,p_sig,claimed_at) VALUES ('fern-claim',?,'fern-admission',?,'fern',?,?)",&[text(DATABASE),text(&key),text(&URL_SAFE_NO_PAD.encode(person.sign(&bytes))),text(NOW)]).unwrap();        assert_eq!(read()["personId"], "fern");        assert_eq!(read()["photoKey"], photo);        db.run(            "UPDATE cotton_people SET avatar_key=NULL WHERE id='fern'",            &[],        )        .unwrap();        assert_eq!(read()["personId"], "fern");        assert!(read()["photoKey"].is_null());    }    fn text(s: &str) -> Sql {        Sql::Text(s.to_string())    }    fn admission(db: &Driver, id: &str, key: &str, rights: &str, stamp: &str) {        db.run(            "INSERT INTO cotton_admissions (id, workspace_id, person_key, person_name, rights, admitted_by_person, p_sig, admitted_at, _hlc) \             VALUES (?, ?, ?, ?, ?, 'owner-key', 'c2ln', ?, ?)",            &[text(id), text(DATABASE), text(key), text(key), text(rights), text(NOW), text(stamp)],        ).unwrap();    }    fn file() -> Driver {        let db = Driver::open_in_memory().unwrap();        cotton_store::migrate::migrate_store(&db).unwrap();        db.run("INSERT INTO cotton_workspaces (id, name, owner_user_id, created_at) VALUES (?, 'Garden', 'synthetic-owner', ?)", &[text(DATABASE), text(NOW)]).unwrap();        admission(&db, "a1", "owner-key", "owner", "0001");        admission(&db, "a2", "member-key", "member", "0002");        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 ('s1', ?, 'member-key', 'phone-key', 'vault-key', 'Test phone', 'c2ln', 'c2ln', ?, '0003')",            &[text(DATABASE), text(NOW)],        ).unwrap();        db    }    // RULE: The People read identifies this device through a live membership statement, never the boot owner; removed people and removed device identities confer no rights.    #[test]    fn membership_and_me_come_from_live_facts() {        let db = file();        let first = answer(&db, Some("phone-key"), None, false).unwrap();        assert_eq!(first["me"], "member-key");        assert_eq!(first["members"].as_array().unwrap().len(), 2);        assert_eq!(            answer(&db, Some("unknown-phone"), None, false).unwrap()["me"],            Value::Null        );        assert_eq!(answer(&db, None, None, false).unwrap()["me"], Value::Null);        db.run(            "INSERT INTO cotton_revocations (id, workspace_id, subject_table, subject_id, revoked_at, actor, reason, _hlc) \             VALUES ('r1', ?, 'person', 'member-key', ?, 'owner-key', 'revoked', '0004')",            &[text(DATABASE), text(NOW)],        ).unwrap();        let removed = answer(&db, Some("phone-key"), None, false).unwrap();        assert_eq!(removed["me"], Value::Null);        assert_eq!(            removed["members"],            json!([{                "personKey": "owner-key", "name": "owner-key", "rights": "admin", "isOwner": true,                "personId": null, "photoKey": null, "suggestedPersonId": null,            }])        );        admission(&db, "a3", "member-key", "admin", "0005");        let readmitted = answer(&db, Some("phone-key"), None, false).unwrap();        assert_eq!(readmitted["members"].as_array().unwrap().len(), 2);        assert_eq!(            readmitted["me"],            Value::Null,            "an old device statement cannot outlive removal"        );    }    // RULE: Members says whether "Admit a person" can run, and in words why not where the signed owner admission rows are absent, so the act is never a dead button.    #[test]    fn admitting_is_offered_only_where_the_owner_admission_is_written() {        let db = file();        let owner = answer(&db, None, Some("owner-key"), false).unwrap();        assert_eq!(owner["canAdmit"], true);        assert_eq!(owner["admitReason"], Value::Null);        let member = answer(&db, Some("phone-key"), None, false).unwrap();        assert_eq!(member["canAdmit"], false);        assert_eq!(member["admitReason"], ADMIT_NOT_ADMIN);        let stranger = answer(&db, Some("unknown-phone"), None, false).unwrap();        assert_eq!(stranger["canAdmit"], false);        assert_eq!(stranger["admitReason"], ADMIT_NOT_A_MEMBER);        // A file with no owner admission at all: nobody can admit, and it says why.        let bare = Driver::open_in_memory().unwrap();        cotton_store::migrate::migrate_store(&bare).unwrap();        bare.run("INSERT INTO cotton_workspaces (id, name, owner_user_id, created_at) VALUES (?, 'Garden', 'synthetic-owner', ?)", &[text(DATABASE), text(NOW)]).unwrap();        let unowned = answer(&bare, None, Some("owner-key"), false).unwrap();        assert_eq!(unowned["canAdmit"], false);        assert_eq!(unowned["admitReason"], ADMIT_NO_OWNER);        assert_eq!(unowned["members"], json!([]));        // The person's own database admits nobody, owner or not.        let personal = answer(&db, None, Some("owner-key"), true).unwrap();        assert_eq!(personal["canAdmit"], false);        assert_eq!(personal["admitReason"], ADMIT_PERSONAL);    }    // An owner's device PAIRED into the household holds the owner's person key    // and no statement in a shared file: it is the owner by that key.    // RULE: The owner's second device reads "(you)" by the owner's person key and never lists its own person under "with …"; another person's key names nobody.    #[test]    fn an_owners_paired_device_is_the_owner_by_its_person_key() {        let db = file();        assert_eq!(            answer(&db, Some("unknown-phone"), Some("owner-key"), false).unwrap()["me"],            "owner-key"        );        assert_eq!(            answer(&db, Some("unknown-phone"), Some("stranger-key"), false).unwrap()["me"],            Value::Null        );    }}