Cotton code
124 lines · 4.2 KB · RustRaw
//! A member's own signed People claim, read without changing any fact.use crate::{membership, Driver, Result};use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};use ed25519_dalek::{Signature, VerifyingKey};use rusqlite::types::Value as Sql;pub const TABLE: &str = "cotton_member_person_claims";#[derive(Debug, Clone, PartialEq, Eq)]pub struct BoundPerson {    pub person_id: String,    pub photo_key: Option<String>,}/// Shared by the device signer, serving writer and every reader. Including/// the admission prevents an old claim attaching to a later admission.pub fn claim_bytes(    database: &str,    admission: &str,    member: &str,    person: &str,    at: &str,) -> Vec<u8> {    let mut bytes = Vec::new();    for field in [        "cotton-member-person-v1",        database,        admission,        member,        person,        at,    ] {        bytes.extend_from_slice(&(field.len() as u32).to_be_bytes());        bytes.extend_from_slice(field.as_bytes());    }    bytes}fn text(value: &str) -> Sql {    Sql::Text(value.into())}pub fn latest_admission(db: &Driver, database: &str, member: &str) -> Result<Option<String>> {    if membership::of(db, member)?.is_none() {        return Ok(None);    }    Ok(db.get("SELECT id FROM cotton_admissions WHERE workspace_id=? AND person_key=? ORDER BY _hlc DESC,id DESC LIMIT 1",        &[text(database),text(member)])?.and_then(|row| row.text("id").map(str::to_owned)))}/// The owner's person key as his PERSONAL database holds it — the public half,/// and nothing else of the row: the key his claim in a shared database is/// signed by, so the member to ask [`bound_person`] about. `None` before the/// first vault pass has written one.////// It is here, and answers one column, because the same row holds the key's/// sealed private half: no tool's own code names that table (the guard is/// `person_key_private_half_is_never_listed_by_any_mcp_tool`), so a tool that/// needs to know WHO the owner is asks this and can be handed nothing more.pub fn owner_public_key(personal: &Driver) -> Result<Option<String>> {    Ok(personal        .get("SELECT public_key FROM cotton_person_keys ORDER BY created_at, id LIMIT 1", &[])?        .and_then(|row| row.text("public_key").map(str::to_owned)))}/// No pre-link, name join, owner fallback, unsigned overlay or read-time birth.pub fn bound_person(db: &Driver, database: &str, member: &str) -> Result<Option<BoundPerson>> {    let Some(admission) = latest_admission(db, database, member)? else {        return Ok(None);    };    let Some(row) = db.get("SELECT person_key,person_id,p_sig,claimed_at FROM cotton_member_person_claims WHERE workspace_id=? AND admission_id=? ORDER BY claimed_at DESC,_hlc DESC,id DESC LIMIT 1",        &[text(database),text(&admission)])? else { return Ok(None); };    let (Some(key), Some(person), Some(sig), Some(at)) = (        row.text("person_key"),        row.text("person_id"),        row.text("p_sig"),        row.text("claimed_at"),    ) else {        return Ok(None);    };    if key != member        || !verifies(            member,            &claim_bytes(database, &admission, member, person, at),            sig,        )    {        return Ok(None);    }    let Some(person_row) = db.get(        "SELECT avatar_key FROM cotton_people WHERE workspace_id=? AND id=?",        &[text(database), text(person)],    )?    else {        return Ok(None);    };    let prefix = format!("{database}/");    Ok(Some(BoundPerson {        person_id: person.into(),        photo_key: person_row            .text("avatar_key")            .filter(|key| key.starts_with(&prefix))            .map(str::to_owned),    }))}fn verifies(member: &str, bytes: &[u8], signature: &str) -> bool {    let Some(key) = URL_SAFE_NO_PAD        .decode(member)        .ok()        .and_then(|raw| raw.try_into().ok())        .and_then(|raw| VerifyingKey::from_bytes(&raw).ok())    else {        return false;    };    let Some(sig) = URL_SAFE_NO_PAD        .decode(signature)        .ok()        .and_then(|raw| Signature::from_slice(&raw).ok())    else {        return false;    };    key.verify_strict(bytes, &sig).is_ok()}