Cotton code
435 lines · 16.1 KB · RustRaw
//! Who is in this database: the one reader of its membership facts.//!//! Membership is written in the database's own file, only on its serving Mac,//! and only ever added to://!//! - an ADMISSION (`cotton_admissions`) names a person key and their rights;//!   the valid chain of admissions with rights `owner` names its owner;//! - a DEVICE STATEMENT (`cotton_device_statements`) names one device key of//!   a person;//! - a REMOVAL is a `cotton_revocations` fact whose subject is a person key//!   (`subject_table = 'person'`) or one device key (`'device_key'`).//!//! The rule, read from the stamps (`_hlc`) the serving Mac gave the facts://!//! - A person is a member with the rights of their LATEST admission, when the//!   admitter was the owner or an admin at that admission's stamp and no//!   removal of the person is stamped after it. Nobody admits themselves.//! - A device is a member's device when its latest statement is stamped after//!   the first valid admission of its person's current life, and no removal//!   of that device key is stamped after the statement. Another admission in//!   the same life changes rights without ending earlier device statements.//! - A removal ends what came before it. An admission stamped after a removal//!   starts a new life, which needs a new device statement.//!//! Signatures are checked where a fact is made (`cotton_server::members`); a//! push of one is refused by the serving screen, so a fact in the file is one//! its serving Mac made. This file reads the facts and checks no signature.#[path = "membership_ownership.rs"]mod ownership;use rusqlite::types::Value as SqlValue;use crate::driver::Driver;use crate::error::Result;pub use crate::revocation::{DEVICE_KEY_SUBJECT, PERSON_SUBJECT};/// What a person may do in this database.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum Rights {    /// Reads and writes records.    Member,    /// Also admits and removes members.    Admin,    /// Every right; changes only by a hand-over admission.    Owner,}impl Rights {    /// Whether these rights admit and remove people.    pub fn admits(self) -> bool {        matches!(self, Rights::Admin | Rights::Owner)    }    /// The word an admission row carries.    pub fn as_str(self) -> &'static str {        match self {            Rights::Member => "member",            Rights::Admin => "admin",            Rights::Owner => "owner",        }    }    /// The rights an admission or an invite may give: `member` or `admin`.    pub fn given(word: &str) -> Option<Rights> {        match word {            "member" => Some(Rights::Member),            "admin" => Some(Rights::Admin),            _ => None,        }    }}fn text(value: &str) -> SqlValue {    SqlValue::Text(value.to_string())}/// The current owner, resolved from the valid admission chain.pub fn owner(db: &Driver) -> Result<Option<String>> {    Ok(ownership::read(db, None)?        .owner()        .map(|owner| owner.person.clone()))}/// The immutable birth admission's person, even after a hand-over.pub fn birth_owner(db: &Driver) -> Result<Option<String>> {    Ok(ownership::read(db, None)?        .owners        .first()        .map(|owner| owner.person.clone()))}/// The resolved owner admission, for membership readers.pub fn owner_admission(db: &Driver) -> Result<Option<String>> {    Ok(ownership::read(db, None)?        .owner()        .map(|owner| owner.id.clone()))}/// Who wrote a row, by name — the BYLINE of a record in a shared database.////// The row's `_hlc` names its author ([`crate::fold::author_of`]), an author is/// a device (`cotton_authors`), a device belongs to a person by its latest/// device statement, and the owner's devices — paired, never stated — are the/// owner's. The name is the person's latest admission's `person_name`, the one/// People draws. `None` when any link is missing (an old file, a row folded/// before authors were minted): a page then shows no byline, never a wrong one.pub fn author_name(db: &Driver, hlc: &str) -> Result<Option<String>> {    let Some(author) = crate::fold::author_of(hlc) else {        return Ok(None);    };    let Some(device) = db        .get(            "SELECT device_id FROM cotton_authors WHERE id = ? LIMIT 1",            &[text(author)],        )?        .and_then(|row| row.text("device_id").map(str::to_string))    else {        return Ok(None);    };    let stated = db        .get(            "SELECT person_key FROM cotton_device_statements \             WHERE device_key = ? ORDER BY _hlc DESC, id DESC LIMIT 1",            &[text(&device)],        )?        .and_then(|row| row.text("person_key").map(str::to_string));    let person = match stated {        Some(person) => person,        None => match birth_owner(db)? {            Some(owner) => owner,            None => return Ok(None),        },    };    person_name(db, &person)}/// A person's name: their latest admission's `person_name`, the one People/// draws. `None` for a person with no admission or an empty name.pub fn person_name(db: &Driver, person: &str) -> Result<Option<String>> {    Ok(db        .get(            "SELECT person_name FROM cotton_admissions WHERE person_key = ? \             ORDER BY _hlc DESC, id DESC LIMIT 1",            &[text(person)],        )?        .and_then(|row| row.text("person_name").map(str::trim).map(str::to_string))        .filter(|name| !name.is_empty()))}/// WHO REMOVED a device, by name: the person who signed the latest removal/// fact naming any of `subjects` (the device's approval row id, its key, its/// person key). `None` when no such fact carries a signer — a revocation made/// at the Mac's own devices list signs nothing — or the signer has no name.pub fn remover_name(db: &Driver, subjects: &[&str]) -> Result<Option<String>> {    if subjects.is_empty() {        return Ok(None);    }    let marks = vec!["?"; subjects.len()].join(", ");    let sql = format!(        "SELECT signer_person FROM cotton_revocations \         WHERE subject_id IN ({marks}) AND signer_person IS NOT NULL \           AND reason IN ('revoked', 'erased', 'lost', 'stolen') \         ORDER BY _hlc DESC, id DESC LIMIT 1"    );    let params: Vec<SqlValue> = subjects.iter().map(|subject| text(subject)).collect();    let Some(signer) = db        .get(&sql, &params)?        .and_then(|row| row.text("signer_person").map(str::to_string))    else {        return Ok(None);    };    person_name(db, &signer)}/// Rights and their membership life boundary (`None` for an unbroken owner life). The latest/// reader returns the rights-giving admission; `standing` selects the life start.struct Standing {    rights: Rights,    since: Option<String>,}fn owner_life_start(db: &Driver, owner: &ownership::Owner, birth: bool) -> Result<Option<String>> {    if birth {        return Ok(None);    }    Ok(standing(db, &owner.person, Some(&owner.stamp))?        .map(|standing| standing.since)        .unwrap_or_else(|| Some(owner.stamp.clone())))}/// Latest admission's rights and stamp just before `before`, or now.fn latest_standing(    db: &Driver,    person_key: &str,    before: Option<&str>,) -> Result<Option<Standing>> {    let history = ownership::read(db, before)?;    if let Some(owner) = history.owner().filter(|owner| owner.person == person_key) {        // Promotion keeps the person's existing membership life. A person who        // previously left needs a fresh device statement, even when returning        // as owner; historical reads stop before this promotion and terminate.        let since = owner_life_start(db, owner, history.owners.len() == 1)?;        return Ok(Some(Standing {            rights: Rights::Owner,            since,        }));    }    // An empty bound sorts before every stamp, so `'' = ?` means "no bound".    let bound = text(before.unwrap_or(""));    let admission = db.get(        "SELECT rights, admitted_by_person, _hlc FROM cotton_admissions \         WHERE person_key = ? AND rights IN ('member','admin') AND (? = '' OR _hlc < ?) \         ORDER BY _hlc DESC, id DESC LIMIT 1",        &[text(person_key), bound.clone(), bound.clone()],    )?;    let Some(admission) = admission else {        return Ok(None);    };    let stamp = admission.text("_hlc").unwrap_or_default().to_string();    // An owner admission supersedes older member/admin grants. The new    // owner gives staff rights by a new member admission; birth is untouched.    if history        .last_owned(person_key)        .is_some_and(|owner| owner.stamp >= stamp)    {        return Ok(None);    }    let admitter = admission.text("admitted_by_person").unwrap_or_default();    let Some(rights) = admission.text("rights").and_then(Rights::given) else {        return Ok(None);    };    if admitter == person_key {        return Ok(None);    }    // Each step back reads strictly earlier stamps, so this ends.    let admitted =        latest_standing(db, admitter, Some(&stamp))?.is_some_and(|by| by.rights.admits());    if !admitted {        return Ok(None);    }    let removed = db        .get(            "SELECT 1 AS removed FROM cotton_revocations \             WHERE subject_table = ? AND subject_id = ? AND _hlc > ? AND (? = '' OR _hlc < ?) LIMIT 1",            &[                text(PERSON_SUBJECT),                text(person_key),                text(&stamp),                bound.clone(),                bound,            ],        )?        .is_some();    if removed {        return Ok(None);    }    Ok(Some(Standing {        rights,        since: Some(stamp),    }))}/// A later admission consumes another invite or changes rights; only a person/// revocation starts a new life. Keep latest rights, but find the first valid/// admission after that life boundary. Every historical read uses the same bound.fn standing(db: &Driver, person_key: &str, before: Option<&str>) -> Result<Option<Standing>> {    let Some(latest) = latest_standing(db, person_key, before)? else {        return Ok(None);    };    if latest.rights == Rights::Owner || latest.since.is_none() {        return Ok(Some(latest));    }    let bound = text(before.unwrap_or(""));    let ended = db        .get(            "SELECT MAX(_hlc) AS stamp FROM cotton_revocations \         WHERE subject_table = ? AND subject_id = ? AND (? = '' OR _hlc < ?)",            &[                text(PERSON_SUBJECT),                text(person_key),                bound.clone(),                bound.clone(),            ],        )?        .and_then(|row| row.text("stamp").map(str::to_string))        .unwrap_or_default();    let history = ownership::read(db, before)?;    // Staff keeps the owner's actual life boundary. A returning owner began    // a new life after leaving; demotion cannot revive its ended statements.    if let Some(owner) = history        .last_owned(person_key)        .filter(|owner| owner.stamp > ended)    {        let birth = history            .owners            .first()            .is_some_and(|first| first.id == owner.id);        let since = owner_life_start(db, owner, birth)?;        return Ok(Some(Standing {            rights: latest.rights,            since,        }));    }    let admissions = db.all(        "SELECT admitted_by_person, _hlc FROM cotton_admissions \         WHERE person_key = ? AND rights IN ('member','admin') AND _hlc > ? \         AND (? = '' OR _hlc < ?) ORDER BY _hlc, id",        &[text(person_key), text(&ended), bound.clone(), bound],    )?;    for admission in admissions {        let stamp = admission.text("_hlc").unwrap_or_default();        let admitter = admission.text("admitted_by_person").unwrap_or_default();        // A planted self-admission or one made without authority cannot move        // the life start earlier and revive an otherwise inadmissible device.        if admitter != person_key            && latest_standing(db, admitter, Some(stamp))?.is_some_and(|by| by.rights.admits())        {            return Ok(Some(Standing {                rights: latest.rights,                since: Some(stamp.to_string()),            }));        }    }    // The latest admission was valid, so absence here is inconsistent history.    Ok(None)}/// The rights `person_key` holds in this database now, or `None` when they/// are not a member of it.pub fn of(db: &Driver, person_key: &str) -> Result<Option<Rights>> {    Ok(latest_standing(db, person_key, None)?.map(|standing| standing.rights))}/// The rights `person_key` held just before `stamp` — what an admission or a/// removal stamped there is judged by.pub fn at(db: &Driver, person_key: &str, stamp: &str) -> Result<Option<Rights>> {    Ok(latest_standing(db, person_key, Some(stamp))?.map(|standing| standing.rights))}/// The person `device_key` belongs to and their rights, when it is a member's/// device now: named by a statement of this life, and not removed since.pub fn device(db: &Driver, device_key: &str) -> Result<Option<(String, Rights)>> {    let Some(statement) = db.get(        "SELECT person_key, _hlc FROM cotton_device_statements \         WHERE device_key = ? ORDER BY _hlc DESC, id DESC LIMIT 1",        &[text(device_key)],    )?    else {        return Ok(None);    };    let person = statement.text("person_key").unwrap_or_default().to_string();    let stated = statement.text("_hlc").unwrap_or_default().to_string();    let Some(standing) = standing(db, &person, None)? else {        return Ok(None);    };    // A statement from before this life's admission stays ended.    if standing        .since        .as_deref()        .is_some_and(|since| stated.as_str() <= since)    {        return Ok(None);    }    let removed = db        .get(            "SELECT 1 AS removed FROM cotton_revocations \             WHERE subject_table = ? AND subject_id = ? AND _hlc > ? LIMIT 1",            &[text(DEVICE_KEY_SUBJECT), text(device_key), text(&stated)],        )?        .is_some();    if removed {        return Ok(None);    }    // A device whose approval in this file was revoked is no member's device,    // whichever fact ended it.    if crate::revocation::device_standing(db, device_key)? == crate::revocation::Standing::Cut {        return Ok(None);    }    Ok(Some((person, standing.rights)))}/// The names of `person_key`'s devices that are members' devices now/// (`device`), oldest statement first: what a member's page says they use,/// never a key.pub fn device_names(db: &Driver, person_key: &str) -> Result<Vec<String>> {    let rows = db.all(        "SELECT device_key, device_name FROM cotton_device_statements a \         WHERE person_key = ? AND id = (SELECT id FROM cotton_device_statements b \         WHERE b.device_key = a.device_key ORDER BY _hlc DESC, id DESC LIMIT 1) \         ORDER BY made_at, device_key",        &[text(person_key)],    )?;    let mut names = Vec::new();    for row in &rows {        let key = row.text("device_key").unwrap_or_default();        let name = row.text("device_name").unwrap_or_default().trim();        if name.is_empty() || names.iter().any(|known| known == name) {            continue;        }        if device(db, key)?.is_some_and(|(person, _)| person == person_key) {            names.push(name.to_string());        }    }    Ok(names)}/// Resolved admission facts for every renderer. The definition supplies words.#[derive(Clone, serde::Serialize)]#[serde(rename_all = "camelCase")]pub struct Ownership {    pub admission_id: String,    pub owner_person_key: String,    pub owner_name: String,    pub admitted_at: String,}pub fn resolved_ownership(db: &Driver) -> Result<Option<Ownership>> {    let Some(owner) = ownership::read(db, None)?.owner().cloned() else {        return Ok(None);    };    let Some(row) = db.get(        "SELECT person_name,admitted_at FROM cotton_admissions WHERE id=?",        &[text(&owner.id)],    )?    else {        return Ok(None);    };    Ok(Some(Ownership {        admission_id: owner.id,        owner_person_key: owner.person,        owner_name: row.text("person_name").unwrap_or_default().into(),        admitted_at: row.text("admitted_at").unwrap_or_default().into(),    }))}