Cotton code
395 lines · 12.3 KB · RustRaw
//! Public, structured membership actions. The signing device reconstructs the//! statement bytes itself and binds a plan to its own request before signing.use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};use serde::{Deserialize, Serialize};use sha2::{Digest, Sha256};use super::statements;#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "lowercase")]pub enum GrantRights {    #[default]    Member,    Admin,}impl GrantRights {    pub fn as_str(self) -> &'static str {        match self {            Self::Member => "member",            Self::Admin => "admin",        }    }}#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]#[serde(    tag = "kind",    rename_all = "camelCase",    rename_all_fields = "camelCase",    deny_unknown_fields)]pub enum MembershipAction {    Invite {        #[serde(default)]        rights: GrantRights,    },    Admit {        pairing_id: String,        #[serde(default)]        person_id: Option<String>,    },    ClaimPerson {        person_id: String,    },    Remove {        person_key: String,    },}#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase", deny_unknown_fields)]pub struct MembershipPrepare {    pub action: MembershipAction,}#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]#[serde(    tag = "kind",    rename_all = "camelCase",    rename_all_fields = "camelCase",    deny_unknown_fields)]pub enum MembershipPreparedAction {    Invite {        invite_id: String,        secret: String,        rights: GrantRights,        expires_at: String,    },    Admit {        pairing_id: String,        invite_id: String,        person_key: String,        device_key: String,        rights: GrantRights,        admitted_at: String,        #[serde(default)]        person_id: Option<String>,    },    ClaimPerson {        admission_id: String,        person_id: String,        claimed_at: String,    },    Remove {        person_key: String,        device_keys: Vec<String>,        stamp: String,    },}#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase", deny_unknown_fields)]pub struct MembershipPlan {    pub database: String,    pub signer_person: String,    pub action: MembershipPreparedAction,}#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase", deny_unknown_fields)]pub struct MembershipApply {    pub plan: MembershipPlan,    pub signatures: Vec<String>,}#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]pub enum PlanError {    #[error("membership plan does not match the requested action")]    RequestMismatch,    #[error("membership plan contains an invalid identifier, key, secret, or timestamp")]    InvalidField,    #[error("membership removal device keys must be unique and sorted")]    DeviceOrder,}impl MembershipPlan {    /// Run before opening the local person key. A server cannot substitute a    /// different database, signer, grant, claim, or removal target.    pub fn matches_request(        &self,        database: &str,        signer_person: &str,        action: &MembershipAction,    ) -> Result<(), PlanError> {        use MembershipAction as Requested;        use MembershipPreparedAction as Prepared;        let matches = match (action, &self.action) {            (Requested::Invite { rights: a }, Prepared::Invite { rights: b, .. }) => a == b,            (                Requested::Admit {                    pairing_id: a,                    person_id: ap,                },                Prepared::Admit {                    pairing_id: b,                    person_id: bp,                    ..                },            ) => a == b && ap == bp,            (                Requested::ClaimPerson { person_id: a },                Prepared::ClaimPerson { person_id: b, .. },            ) => a == b,            (Requested::Remove { person_key: a }, Prepared::Remove { person_key: b, .. }) => a == b,            _ => false,        };        if self.database != database || self.signer_person != signer_person || !matches {            return Err(PlanError::RequestMismatch);        }        self.signing_messages().map(|_| ())    }    /// Invite and admission each have one signature. Removal signatures are    /// person first, followed by each device in strictly ascending key order.    pub fn signing_messages(&self) -> Result<Vec<Vec<u8>>, PlanError> {        identifier(&self.database)?;        key(&self.signer_person)?;        let messages = match &self.action {            MembershipPreparedAction::Invite {                invite_id,                secret,                rights,                expires_at,            } => {                identifier(invite_id)?;                timestamp(expires_at)?;                let secret = bytes32(secret)?;                let hash: [u8; 32] = Sha256::digest(secret).into();                vec![invite_signed_bytes(                    &self.database,                    invite_id,                    &hash,                    rights.as_str(),                    expires_at,                )]            }            MembershipPreparedAction::Admit {                pairing_id,                invite_id,                person_key,                device_key,                rights,                admitted_at,                person_id,            } => {                identifier(pairing_id)?;                identifier(invite_id)?;                key(person_key)?;                key(device_key)?;                timestamp(admitted_at)?;                let mut messages = vec![statements::admission_bytes(                    &self.database,                    person_key,                    rights.as_str(),                    Some(invite_id),                    admitted_at,                )];                if let Some(person) = person_id {                    identifier(person)?;                    messages.push(suggestion_signed_bytes(                        &self.database,                        person_key,                        person,                        invite_id,                        admitted_at,                    ));                }                messages            }            MembershipPreparedAction::ClaimPerson {                admission_id,                person_id,                claimed_at,            } => {                identifier(admission_id)?;                identifier(person_id)?;                timestamp(claimed_at)?;                vec![cotton_store::member_person::claim_bytes(                    &self.database,                    admission_id,                    &self.signer_person,                    person_id,                    claimed_at,                )]            }            MembershipPreparedAction::Remove {                person_key,                device_keys,                stamp,            } => {                key(person_key)?;                timestamp(stamp)?;                if device_keys.windows(2).any(|pair| pair[0] >= pair[1]) {                    return Err(PlanError::DeviceOrder);                }                let mut messages = vec![statements::removal_bytes(                    &self.database,                    statements::PERSON_SUBJECT,                    person_key,                    stamp,                )];                for device in device_keys {                    key(device)?;                    messages.push(statements::removal_bytes(                        &self.database,                        statements::DEVICE_KEY_SUBJECT,                        device,                        stamp,                    ));                }                messages            }        };        Ok(messages)    }}pub const INVITE_TAG: &str = "cotton-invite-v1";pub fn suggestion_signed_bytes(    database: &str,    member: &str,    person: &str,    invite: &str,    at: &str,) -> Vec<u8> {    let mut bytes = Vec::new();    for field in [        "cotton-admission-person-suggestion-v1",        database,        member,        person,        invite,        at,    ] {        crate::invite_link::lp(&mut bytes, field.as_bytes());    }    bytes}/// Unlike the legacy text byline, identity requires an explicitly signed/// device statement and a live member's own People claim in this database.pub fn author_person(    db: &cotton_store::Driver,    database: &str,    hlc: &str,) -> cotton_store::Result<Option<cotton_store::member_person::BoundPerson>> {    let Some(author) = cotton_store::fold::author_of(hlc) else {        return Ok(None);    };    let Some(device) = db        .get(            "SELECT device_id FROM cotton_authors WHERE workspace_id=? AND id=?",            &[database.to_owned().into(), author.to_owned().into()],        )?        .and_then(|r| r.text("device_id").map(str::to_owned))    else {        return Ok(None);    };    let Some(row) = db.get("SELECT person_key,vault_public_key,p_sig,d_sig FROM cotton_device_statements WHERE workspace_id=? AND device_key=? ORDER BY _hlc DESC,id DESC LIMIT 1", &[database.to_owned().into(),device.clone().into()])? else { return Ok(None); };    let (Some(person), Some(vault), Some(p_sig), Some(d_sig)) = (        row.text("person_key"),        row.text("vault_public_key"),        row.text("p_sig"),        row.text("d_sig"),    ) else {        return Ok(None);    };    if !statements::verifies(        person,        &statements::device_statement_bytes(database, person, &device, vault),        p_sig,    ) || !statements::verifies(        &device,        &statements::device_consent_bytes(database, person, &device, vault),        d_sig,    ) || !cotton_store::membership::device(db, &device)?.is_some_and(|(key, _)| key == person)    {        return Ok(None);    }    cotton_store::member_person::bound_person(db, database, person)}/// Shared with the serving Mac's invite verifier; these bytes retain the/// original invite signature format.pub fn invite_signed_bytes(    database_id: &str,    invite_id: &str,    secret_hash: &[u8; 32],    rights: &str,    expires_at: &str,) -> Vec<u8> {    let mut out = Vec::new();    for field in [        INVITE_TAG.as_bytes(),        database_id.as_bytes(),        invite_id.as_bytes(),        secret_hash,        rights.as_bytes(),        expires_at.as_bytes(),    ] {        crate::invite_link::lp(&mut out, field);    }    out}fn bytes32(value: &str) -> Result<[u8; 32], PlanError> {    URL_SAFE_NO_PAD        .decode(value)        .ok()        .and_then(|bytes| bytes.try_into().ok())        .ok_or(PlanError::InvalidField)}fn key(value: &str) -> Result<(), PlanError> {    ed25519_dalek::VerifyingKey::from_bytes(&bytes32(value)?)        .map(|_| ())        .map_err(|_| PlanError::InvalidField)}fn identifier(value: &str) -> Result<(), PlanError> {    if value.is_empty() || value.chars().any(char::is_control) {        Err(PlanError::InvalidField)    } else {        Ok(())    }}fn timestamp(value: &str) -> Result<(), PlanError> {    chrono::DateTime::parse_from_rfc3339(value)        .map(|_| ())        .map_err(|_| PlanError::InvalidField)}#[cfg(test)]#[path = "member_actions_tests.rs"]mod tests;/// A target hint for a fresh own claim or a person pick. Canonical prints/// still require the current admission's own claim.pub fn last_signed_person_claim(    db: &cotton_store::Driver,    database: &str,    key: &str,) -> cotton_store::Result<Option<String>> {    for row in db.all("SELECT c.person_id,c.admission_id,c.p_sig,c.claimed_at FROM cotton_member_person_claims c JOIN cotton_admissions a ON a.id=c.admission_id AND a.person_key=c.person_key AND a.workspace_id=c.workspace_id WHERE c.workspace_id=? AND c.person_key=? ORDER BY c._hlc DESC,c.id DESC",&[database.to_owned().into(),key.to_owned().into()])? {        let person=row.text("person_id").unwrap_or_default();        let bytes=cotton_store::member_person::claim_bytes(database,row.text("admission_id").unwrap_or_default(),key,person,row.text("claimed_at").unwrap_or_default());        if cotton_store::signed::verifies(key,&bytes,row.text("p_sig").unwrap_or_default()) {return Ok(Some(person.into()))}    }    Ok(None)}