Cotton code
985 lines · 41.6 KB · RustRaw
//! Revocation: the facts in `cotton_revocations`, and the one reader of a//! device's standing.//!//! A revocation is a FACT (`crate::fact_hooks`): inserted, never updated or//! deleted, its id random, so two devices revoking one subject write two//! facts that never clash. The `revoked_at` columns on the subject rows stay//! as a mirror, and [`revoke`] is the ONE writer of both: the fact and the//! subject row's mirror go into one act, so every reader of `revoked_at` sees//! what [`device_standing`] reads from the facts. This file also holds the//! hook the fold runs when it takes a fact.use std::collections::BTreeSet;use rusqlite::types::Value as SqlValue;use serde_json::{Map, Value as JsonValue};use crate::actor::Actor;use crate::canonical::{Kind, Receipt};use crate::driver::Driver;use crate::error::{Result, StoreError};use crate::mint::{Act, Change};use crate::outbox::LocalChange;use crate::protocol::types::OpKind;use crate::receipts::MIRROR_COLUMNS;/// The subject table of a device's revocation: a fact's `subject_id` is the/// `cotton_devices.id` of the APPROVAL it ends, not the device's key.pub const DEVICES_SUBJECT: &str = "cotton_devices";/// The reason of a fact that hands a device's standing to its `successor`.pub const SUCCEEDED: &str = "succeeded";/// How many `succeeded` facts a standing follows before it gives up and reads/// `Cut` — the bound `cotton_server::code::credentials::SUPERSEDE_HOPS` puts on/// the same chain.pub const SUCCESSOR_HOPS: usize = 8;/// Where a device stands in this file.#[derive(Debug, Clone, PartialEq, Eq)]pub enum Standing {    /// Its first approval, by [`KEY_ORDER`], has no fact and no mirror.    Live,    /// A `succeeded` fact hands it to this LIVE device key. What it minted    /// stands, whatever `revoked` or `lost` facts also name it.    Succeeded(String),    /// Revoked: a fact, or a mirror with no fact, and no live successor.    Cut,    /// This file has no row for the key: never barred, never owed a rotation.    Unknown,}/// The order that answers "the row for this key" where a key holds one row/// per approval: the live approval first, then the newest, then the id. It is/// `cotton_tools::devices::KEY_ORDER` with "revoked" read as "has a fact, or a/// mirror with no fact". `d` is the device row.pub const KEY_ORDER: &str = "ORDER BY (d.revoked_at IS NULL AND NOT EXISTS (\     SELECT 1 FROM cotton_revocations r \     WHERE r.subject_table = 'cotton_devices' AND r.subject_id = d.id)) DESC, \     d.approved_at DESC, d.id ASC";/// An approval ended LATE (slice 12, V10-1 (b)): its create is stamped below/// a device fact, not written by the carry's import (`import:`), on another/// approval of the same key. Such an approval arrived after the key was/// ended — a late or duplicate copy of it — and never makes the key `Live`./// An honest re-pair is created after the fact and is not one. `d` is the/// device row; an approval with no create receipt here is never late.const ENDED_LATE: &str = "EXISTS (SELECT 1 FROM cotton_revocations r \     JOIN cotton_devices o ON o.id = r.subject_id \     WHERE r.subject_table = 'cotton_devices' AND o.device_id = d.device_id AND o.id <> d.id \       AND r.actor NOT LIKE 'import:%' \       AND r._hlc > (SELECT MIN(w.hlc) FROM _writes w \                     WHERE w.tbl = 'cotton_devices' AND w.row_id = d.id AND w.kind = 'create'))";/// The standing of the device whose key is `device_id`.////// A key that a serving fact records as a SKIPPED claimant (slice 12, V11-2)/// reads `Succeeded` by that fact's Mac, whatever its approvals say: the/// claimant's own approval is not in the file, so nothing else can end it.////// Otherwise read from the facts of ONE row: the approval [`KEY_ORDER`] puts/// first, among the approvals not ended late ([`approval_ended_late`]) — or/// among them all when every one is. A device revoked and then approved again/// is `Live`; the facts of its ended approvals are not read. It does not/// depend on the order facts arrived in.pub fn device_standing(db: &Driver, device_id: &str) -> Result<Standing> {    let mut seen = BTreeSet::new();    standing(db, device_id, &mut seen)}fn standing(db: &Driver, device_id: &str, seen: &mut BTreeSet<String>) -> Result<Standing> {    seen.insert(device_id.to_string());    if let Some(mac) = crate::serving::skipped_by(db, device_id)? {        if !seen.contains(&mac) && seen.len() <= SUCCESSOR_HOPS {            if let Standing::Succeeded(by) = standing(db, &mac, seen)? {                return Ok(Standing::Succeeded(by));            }        }        return Ok(Standing::Succeeded(mac));    }    let row = match db.get(        &format!(            "SELECT d.id, d.revoked_at FROM cotton_devices d \             WHERE d.device_id = ? AND NOT {ENDED_LATE} {KEY_ORDER} LIMIT 1"        ),        &[SqlValue::Text(device_id.to_string())],    )? {        Some(row) => row,        None => match db.get(            &format!("SELECT d.id, d.revoked_at FROM cotton_devices d WHERE d.device_id = ? {KEY_ORDER} LIMIT 1"),            &[SqlValue::Text(device_id.to_string())],        )? {            Some(row) => row,            None => return Ok(Standing::Unknown),        },    };    let row_id = row.text("id").unwrap_or_default().to_string();    let facts = db.all(        "SELECT reason, successor FROM cotton_revocations \         WHERE subject_table = ? AND subject_id = ? ORDER BY id",        &[            SqlValue::Text(DEVICES_SUBJECT.to_string()),            SqlValue::Text(row_id),        ],    )?;    if facts.is_empty() {        // A mirror with no fact is a revocation all the same.        return Ok(if row.text("revoked_at").is_some() {            Standing::Cut        } else {            Standing::Live        });    }    for fact in &facts {        if fact.text("reason") != Some(SUCCEEDED) {            continue;        }        let Some(successor) = fact.text("successor") else {            continue;        };        if seen.contains(successor) || seen.len() > SUCCESSOR_HOPS {            continue;        }        match standing(db, successor, seen)? {            Standing::Live => return Ok(Standing::Succeeded(successor.to_string())),            Standing::Succeeded(by) => return Ok(Standing::Succeeded(by)),            Standing::Cut | Standing::Unknown => {}        }    }    Ok(Standing::Cut)}/// Is the approval `row_id` (a `cotton_devices.id`) ended late — skipped by/// [`device_standing`], so the serving Mac's pass owes it a fact and mirror?/// Only while it has neither: one that has its fact is already ended.pub fn approval_ended_late(db: &Driver, row_id: &str) -> Result<bool> {    Ok(db        .get(            &format!(                "SELECT 1 AS late FROM cotton_devices d WHERE d.id = ? AND d.revoked_at IS NULL \                   AND NOT EXISTS (SELECT 1 FROM cotton_revocations f \                                   WHERE f.subject_table = 'cotton_devices' AND f.subject_id = d.id) \                   AND {ENDED_LATE}"            ),            &[SqlValue::Text(row_id.to_string())],        )?        .is_some())}/// Every approval [`approval_ended_late`] answers yes for, each with the fact/// that ended its key — the one the serving Mac's pass copies: a `succeeded`/// fact first (so a key handed to a live successor stays `Succeeded` and what/// it minted stands), else the latest, by stamp then id.pub fn ended_late_approvals(db: &Driver) -> Result<Vec<EndedLate>> {    let late = db.all(        &format!(            "SELECT d.id, d.device_id, \               (SELECT MIN(w.hlc) FROM _writes w \                WHERE w.tbl = 'cotton_devices' AND w.row_id = d.id AND w.kind = 'create') AS created \             FROM cotton_devices d WHERE d.revoked_at IS NULL \               AND NOT EXISTS (SELECT 1 FROM cotton_revocations f \                               WHERE f.subject_table = 'cotton_devices' AND f.subject_id = d.id) \               AND {ENDED_LATE} ORDER BY d.id"        ),        &[],    )?;    let mut ended = Vec::with_capacity(late.len());    for row in &late {        let approval = row.text("id").unwrap_or_default().to_string();        let Some(fact) = db.get(            "SELECT r.reason, r.successor FROM cotton_revocations r \             JOIN cotton_devices o ON o.id = r.subject_id \             WHERE r.subject_table = 'cotton_devices' AND o.device_id = ? AND o.id <> ? \               AND r.actor NOT LIKE 'import:%' AND r._hlc > ? \             ORDER BY (r.reason = 'succeeded' AND r.successor IS NOT NULL) DESC, r._hlc DESC, r.id DESC \             LIMIT 1",            &[                SqlValue::Text(row.text("device_id").unwrap_or_default().to_string()),                SqlValue::Text(approval.clone()),                SqlValue::Text(row.text("created").unwrap_or_default().to_string()),            ],        )?        else {            continue;        };        ended.push(EndedLate {            approval,            reason: fact.text("reason").unwrap_or_default().to_string(),            successor: fact.text("successor").map(str::to_string),        });    }    Ok(ended)}/// Every skipped claimant ([`crate::serving::skipped_claimants`]) whose key/// holds an approval with neither a fact nor a mirror — the claimant's own/// approval, arrived after the act — so the serving Mac's pass owes it the/// `succeeded` fact (successor: the Mac whose serving fact skipped it)./// [`device_standing`] already reads such a key `Succeeded`.pub fn unended_skipped_claimants(db: &Driver) -> Result<Vec<crate::serving::SkippedClaimant>> {    let mut owed = Vec::new();    for claimant in crate::serving::skipped_claimants(db)? {        if unended_approval_of(db, &claimant.device)? {            owed.push(claimant);        }    }    Ok(owed)}/// Does `key` hold an approval with neither a fact nor a mirror?fn unended_approval_of(db: &Driver, key: &str) -> Result<bool> {    Ok(db        .get(            "SELECT 1 AS live FROM cotton_devices d WHERE d.device_id = ? AND d.revoked_at IS NULL \               AND NOT EXISTS (SELECT 1 FROM cotton_revocations f \                               WHERE f.subject_table = 'cotton_devices' AND f.subject_id = d.id)",            &[SqlValue::Text(key.to_string())],        )?        .is_some())}/// A late approval and the reason and successor of the fact that ended its/// key ([`ended_late_approvals`]).#[derive(Debug, Clone, PartialEq, Eq)]pub struct EndedLate {    /// The approval's `cotton_devices.id`.    pub approval: String,    pub reason: String,    pub successor: Option<String>,}/// The table the facts are in.const FACTS: &str = "cotton_revocations";/// The subject that names a DEVICE KEY rather than one row: every live row of/// that key in the file is ended, each with its own fact and mirror.pub const DEVICE_KEY_SUBJECT: &str = "device_key";/// The subject that names a PERSON KEY (`subject_id` the key): their device/// rows (`cotton_devices.person_key`) end with it, each with its own fact and/// mirror, and the person's own fact ends their device statements — a/// statement is an insert-only fact, ended by a revocation naming its person/// (or its device key), never by a column on it.pub const PERSON_SUBJECT: &str = "person";/// The subject that names an invite (`cotton_invites.id`): an insert-only/// fact with no mirror, so its revocation is the fact alone.pub const INVITE_SUBJECT: &str = "cotton_invites";/// Subjects carrying a `revoked_at` mirror./// Mint, the fold and receipt assembly enforce the same declaration.pub const SUBJECT_TABLES: &[&str] = &[    DEVICES_SUBJECT,    "cotton_oauth_grants",    "cotton_mcp_tokens",    "cotton_code_credentials",];/// A fact's `reason`, as the table's CHECK lists them.pub const REASONS: &[&str] = &[    "revoked", "erased", "lost", SUCCEEDED, "restored", "spent", "pruned", "stolen",];/// What `revoked_reason` reads on a device a `succeeded` fact ended — the/// spelling `cotton_server::devices::superseded` parses the successor from.pub fn superseded_by(successor: &str) -> String {    format!("superseded by {successor}")}/// The act a revocation is written into: the caller's own changes, minted by/// the caller in its own transaction. [`revoke`] only adds to it.pub struct RevokeAct<'a> {    /// The file the subject is in.    pub db: &'a Driver,    /// The act's changes so far; the fact and the mirror are pushed onto it.    pub changes: &'a mut Vec<LocalChange>,    /// The database the act is in.    pub workspace_id: &'a str,    /// Who asked, as the fact's `actor` column says it (`Actor::to_wire`).    pub actor: &'a str,    /// The device key acting — a device mirror's `revoked_by_device`, except    /// for `succeeded`, where that column names the successor.    pub by: &'a str,    /// The moment, ISO — the fact's and the mirror's `revoked_at`.    pub at: &'a str,    /// A RANDOM id for each fact, never derived from the subject: two devices    /// revoking one subject write two facts.    pub new_id: &'a mut dyn FnMut() -> String,}/// A person's signature over a revocation: the fact's `p_sig` and/// `signer_person` (keys work, KS0; the signed string is KS3's).#[derive(Debug, Clone, PartialEq, Eq)]pub struct Signer {    /// The signing person key — the fact's `signer_person`.    pub person: String,    /// The signature, as the fact's `p_sig` stores it.    pub signature: String,}/// Revoke a subject: the `cotton_revocations` fact AND the subject row's/// mirror, into the act it is handed. It never mints and never commits — the/// caller's one transaction holds both, with whatever else the act carries.////// The subject is one row of [`SUBJECT_TABLES`] by its id; a device key/// ([`DEVICE_KEY_SUBJECT`], `subject_id` the key): every live row of that key/// in this database, each a fact on that row with its mirror, and the key's/// own fact (`device_key`), which ends its device statements; a person/// ([`PERSON_SUBJECT`]): every live device row of theirs the same way, and/// the person's own fact; or an invite ([`INVITE_SUBJECT`]): its fact alone./// A `signer` puts its `p_sig` and `signer_person` on every fact written.////// A row whose mirror is already set (a second revocation, or one of a row/// that reads `superseded by …`) gets its fact and keeps its mirror: a mirror,/// once set, is never rewritten, and nothing un-revokes. Answers how many/// mirrors it wrote, plus one for a device key's, a person's or an invite's/// own fact — 0 when the subject was already revoked.pub fn revoke(    act: &mut RevokeAct<'_>,    subject_table: &str,    subject_id: &str,    reason: &str,    successor: Option<&str>,    signer: Option<&Signer>,) -> Result<usize> {    if !REASONS.contains(&reason) {        return Err(StoreError::refused(format!(            "revoke: `{reason}` is not a reason a revocation can give"        )));    }    if (reason == SUCCEEDED) != successor.is_some() {        return Err(StoreError::refused(            "revoke: a successor is named by `succeeded`, and by no other reason",        ));    }    if subject_table == PERSON_SUBJECT {        return revoke_person(act, subject_id, reason, signer);    }    if subject_table == INVITE_SUBJECT {        return revoke_invite(act, subject_id, reason, signer);    }    if subject_table == DEVICE_KEY_SUBJECT {        let live = act.db.all(            "SELECT id FROM cotton_devices \             WHERE device_id = ? AND workspace_id = ? AND revoked_at IS NULL \             ORDER BY approved_at DESC, id ASC",            &[                SqlValue::Text(subject_id.to_string()),                SqlValue::Text(act.workspace_id.to_string()),            ],        )?;        let mut written = 0;        for row in &live {            let id = row.text("id").unwrap_or_default().to_string();            written += revoke_row(act, DEVICES_SUBJECT, &id, reason, successor, signer)?;        }        if live.is_empty() && key_already_ended(act.db, subject_id)? {            return Ok(0);        }        if live.is_empty() && !key_is_known(act.db, subject_id)? {            return Ok(0);        }        // THE KEY'S OWN FACT, beside the rows': what `membership::device`        // reads, so a member device with a statement and no row is ended too.        push_fact(act, DEVICE_KEY_SUBJECT, subject_id, reason, successor, signer);        return Ok(written + 1);    }    if !SUBJECT_TABLES.contains(&subject_table) {        return Err(StoreError::refused(format!(            "revoke: {subject_table} carries no revocation — the subject must name a revocable row, a device key, a person or an invite"        )));    }    revoke_row(act, subject_table, subject_id, reason, successor, signer)}/// A replacement ends the stale hardware key, without the succession semantics/// that would leave it able to speak for the new key. The immutable facts carry/// the replacement device as typed data; the existing reason stays `revoked`.pub fn replace_device(act: &mut RevokeAct<'_>, device_id: &str, replaced_by: &str) -> Result<usize> {    if replaced_by.trim().is_empty() || replaced_by == device_id {        return Err(StoreError::refused("a hardware replacement names a different non-empty device key"));    }    let first = act.changes.len();    let written = revoke(act, DEVICE_KEY_SUBJECT, device_id, "revoked", None, None)?;    for change in &mut act.changes[first..] {        if change.table == FACTS {            change.patch.as_mut().expect("a new fact has a patch")                .insert("replaced_by".into(), JsonValue::from(replaced_by));        }    }    Ok(written)}/// A RE-KEY: the device's old key is SUCCEEDED by `successor` — every live row/// of it ends with reason `succeeded` naming the new key, so what the old key/// minted follows the new one (`Standing::Succeeded`), while the old key/// itself is refused like any key that is not live. The facts also carry/// `replaced_by`, which says the new key is the same hardware re-keyed — the/// words a device row is read in ("replaced by device … on …", `rekeyed_at`)./// A start-over on the same hardware is [`replace_device`], and ends what the/// old key minted.pub fn succeed_device(act: &mut RevokeAct<'_>, device_id: &str, successor: &str) -> Result<usize> {    if successor.trim().is_empty() || successor == device_id {        return Err(StoreError::refused("a re-key names a different non-empty device key"));    }    let first = act.changes.len();    let written = revoke(act, DEVICE_KEY_SUBJECT, device_id, SUCCEEDED, Some(successor), None)?;    for change in &mut act.changes[first..] {        if change.table == FACTS {            change.patch.as_mut().expect("a new fact has a patch")                .insert("replaced_by".into(), JsonValue::from(successor));        }    }    Ok(written)}/// The replacement fact of the device approval being read, chosen deterministically.pub const REPLACED_BY_OF_ROW: &str = "(SELECT f.replaced_by FROM cotton_revocations f WHERE f.subject_table = 'cotton_devices' AND f.subject_id = cotton_devices.id AND f.replaced_by IS NOT NULL ORDER BY f.revoked_at, f.id LIMIT 1)";/// The reason a device reader draws, from its typed fact or ordinary mirror.pub fn device_reason(row: &crate::Row) -> Option<String> {    if let Some(device) = row.text("replaced_by") {        let day = row.text("revoked_at").unwrap_or_default().split('T').next().unwrap_or_default();        return Some(format!("replaced by device {device} on {day}"));    }    row.text("revoked_reason").map(str::to_string)}/// A person's revocation: every live device row of theirs ended (fact and/// mirror each), then the person's own fact — unless one already stands/// after their latest admission, which is "already revoked".fn revoke_person(    act: &mut RevokeAct<'_>,    person_key: &str,    reason: &str,    signer: Option<&Signer>,) -> Result<usize> {    if reason == SUCCEEDED {        return Err(StoreError::refused(            "revoke: a person is removed, never succeeded",        ));    }    // Paired devices retain their immutable binding to the birth owner after    // a hand-over. Removing that person also ends those full approvals;    // infrastructure runner approvals belong to the server, not its owner.    let paired = crate::membership::birth_owner(act.db)?.as_deref() == Some(person_key)        && crate::link_rule::file_kind(act.db)? == crate::link_rule::FileKind::Shared;    let live = act.db.all(        "SELECT id FROM cotton_devices \         WHERE (person_key = ? OR (? = 1 AND person_key IS NULL AND scope = 'full')) \         AND workspace_id = ? AND revoked_at IS NULL ORDER BY approved_at DESC, id ASC",        &[            SqlValue::Text(person_key.to_string()),            SqlValue::Integer(i64::from(paired)),            SqlValue::Text(act.workspace_id.to_string()),        ],    )?;    let mut written = 0;    for row in &live {        let id = row.text("id").unwrap_or_default().to_string();        written += revoke_row(act, DEVICES_SUBJECT, &id, reason, None, signer)?;    }    // ALREADY REVOKED: a person fact stamped (`_hlc`) after the latest    // admission of them, or a person fact and no admission — the order    // `membership::standing` reads. A later admission starts a new life,    // which a new revocation may end. The fact written here is stamped by the    // caller's mint, after every stamp the file holds, so it reads as later    // than any admission already in the file.    let already = ended_after(        act.db,        PERSON_SUBJECT,        person_key,        "SELECT MAX(_hlc) AS stamp FROM cotton_admissions \         WHERE person_key = ? AND rights IN ('member','admin')",    )?;    if !already {        push_fact(act, PERSON_SUBJECT, person_key, reason, None, signer);        written += 1;    }    Ok(written)}/// Does a fact of `subject_table` naming `subject_id` stand stamped (`_hlc`)/// after the latest stamp `latest_sql` (one `?`, the subject id; one column,/// `stamp`) reads — or stand at all when that reads none?fn ended_after(db: &Driver, subject_table: &str, subject_id: &str, latest_sql: &str) -> Result<bool> {    let Some(ended) = db        .get(            "SELECT MAX(_hlc) AS stamp FROM cotton_revocations \             WHERE subject_table = ? AND subject_id = ?",            &[                SqlValue::Text(subject_table.to_string()),                SqlValue::Text(subject_id.to_string()),            ],        )?        .and_then(|row| row.text("stamp").map(str::to_string))    else {        return Ok(false);    };    let latest = db        .get(latest_sql, &[SqlValue::Text(subject_id.to_string())])?        .and_then(|row| row.text("stamp").map(str::to_string));    Ok(latest.is_none_or(|latest| ended > latest))}/// A device key whose own fact stands after its latest device statement/// (`membership::device`'s order) — already ended, with no live row left.fn key_already_ended(db: &Driver, device_key: &str) -> Result<bool> {    ended_after(        db,        DEVICE_KEY_SUBJECT,        device_key,        "SELECT MAX(_hlc) AS stamp FROM cotton_device_statements WHERE device_key = ?",    )}/// Does this file know the key at all — a device row, or a statement? An/// unknown key has nothing to end, and gets no fact.fn key_is_known(db: &Driver, device_key: &str) -> Result<bool> {    Ok(db        .get(            "SELECT 1 AS known FROM cotton_devices WHERE device_id = ?1 \             UNION ALL SELECT 1 FROM cotton_device_statements WHERE device_key = ?1 LIMIT 1",            &[SqlValue::Text(device_key.to_string())],        )?        .is_some())}/// An invite's revocation: its fact alone — an invite is an insert-only fact/// with no mirror. A second revocation answers 0 and writes nothing.fn revoke_invite(    act: &mut RevokeAct<'_>,    invite_id: &str,    reason: &str,    signer: Option<&Signer>,) -> Result<usize> {    if reason == SUCCEEDED {        return Err(StoreError::refused(            "revoke: an invite is withdrawn, never succeeded",        ));    }    if act        .db        .get(            "SELECT 1 AS here FROM cotton_invites WHERE id = ? AND workspace_id = ?",            &[                SqlValue::Text(invite_id.to_string()),                SqlValue::Text(act.workspace_id.to_string()),            ],        )?        .is_none()    {        return Err(StoreError::refused(format!(            "revoke: this file holds no cotton_invites row {invite_id}"        )));    }    let revoked = act        .db        .get(            "SELECT 1 AS here FROM cotton_revocations WHERE subject_table = ? AND subject_id = ?",            &[                SqlValue::Text(INVITE_SUBJECT.to_string()),                SqlValue::Text(invite_id.to_string()),            ],        )?        .is_some()        || act.changes.iter().any(|change| {            change.table == FACTS                && change.patch.as_ref().is_some_and(|patch| {                    patch.get("subject_table").and_then(JsonValue::as_str) == Some(INVITE_SUBJECT)                        && patch.get("subject_id").and_then(JsonValue::as_str) == Some(invite_id)                })        });    if revoked {        return Ok(0);    }    push_fact(act, INVITE_SUBJECT, invite_id, reason, None, signer);    Ok(1)}/// One `cotton_revocations` fact, at a random id, onto the act.fn push_fact(    act: &mut RevokeAct<'_>,    subject_table: &str,    subject_id: &str,    reason: &str,    successor: Option<&str>,    signer: Option<&Signer>,) {    let mut fact = Map::new();    fact.insert("workspace_id".into(), JsonValue::from(act.workspace_id));    fact.insert("subject_table".into(), JsonValue::from(subject_table));    fact.insert("subject_id".into(), JsonValue::from(subject_id));    fact.insert("revoked_at".into(), JsonValue::from(act.at));    fact.insert("actor".into(), JsonValue::from(act.actor));    fact.insert("reason".into(), JsonValue::from(reason));    fact.insert(        "successor".into(),        successor.map_or(JsonValue::Null, JsonValue::from),    );    fact.insert(        "p_sig".into(),        signer.map_or(JsonValue::Null, |signer| JsonValue::from(signer.signature.as_str())),    );    fact.insert(        "signer_person".into(),        signer.map_or(JsonValue::Null, |signer| JsonValue::from(signer.person.as_str())),    );    act.changes.push(LocalChange {        delete: Default::default(),        kind: OpKind::Upsert,        table: FACTS.to_string(),        row_id: (act.new_id)(),        patch: Some(fact),    });}/// One row's fact, and its mirror unless that is already set.fn revoke_row(    act: &mut RevokeAct<'_>,    subject_table: &str,    subject_id: &str,    reason: &str,    successor: Option<&str>,    signer: Option<&Signer>,) -> Result<usize> {    let Some(row) = act.db.get(        &format!("SELECT revoked_at FROM {subject_table} WHERE id = ?"),        &[SqlValue::Text(subject_id.to_string())],    )?    else {        return Err(StoreError::refused(format!(            "revoke: this file holds no {subject_table} row {subject_id}"        )));    };    let mirrored = row.text("revoked_at").is_some()        || act.changes.iter().any(|change| {            change.table == subject_table                && change.row_id == subject_id                && change                    .patch                    .as_ref()                    .and_then(|patch| patch.get("revoked_at"))                    .is_some_and(|value| !value.is_null())        });    push_fact(act, subject_table, subject_id, reason, successor, signer);    if mirrored {        return Ok(0);    }    let mut mirror = Map::new();    mirror.insert("revoked_at".into(), JsonValue::from(act.at));    if subject_table == DEVICES_SUBJECT {        let (by, text) = match successor {            Some(successor) => (successor, superseded_by(successor)),            None => (act.by, reason.to_string()),        };        mirror.insert("revoked_by_device".into(), JsonValue::from(by));        mirror.insert("revoked_reason".into(), JsonValue::from(text));    }    if crate::schema::package_shape::spec_on(act.db, subject_table)?        .is_some_and(|spec| spec.columns.iter().any(|(column, _)| *column == "updated_at"))    {        mirror.insert("updated_at".into(), JsonValue::from(act.at));    }    act.changes.push(LocalChange {        delete: Default::default(),        kind: OpKind::Upsert,        table: subject_table.to_string(),        row_id: subject_id.to_string(),        patch: Some(mirror),    });    Ok(1)}/// `mint`'s check of every change naming a mirror column ([`MIRROR_COLUMNS`])/// on one of [`SUBJECT_TABLES`]. A create may name a mirror only as NULL,/// except the carry's offline import (`import:`), which creates a row as the/// old file held it. A change may name one only while the row's is unset,/// and only beside the `cotton_revocations` fact [`revoke`] puts in the same/// act for that row at the same moment — whatever the actor: there is no/// other writer. A mirror, once set, is never cleared or rewritten by a local/// write.pub(crate) fn refuse_mirror_write(db: &Driver, act: &Act) -> Result<()> {    for change in &act.changes {        if change.kind == Kind::Retract || !SUBJECT_TABLES.contains(&change.table.as_str()) {            continue;        }        let Some(patch) = change.patch.as_ref() else {            continue;        };        let named: Vec<(&str, &JsonValue)> = patch            .iter()            .filter(|(column, _)| MIRROR_COLUMNS.contains(&column.as_str()))            .map(|(column, value)| (column.as_str(), value))            .collect();        if named.is_empty() {            continue;        }        let (verb, table, row) = (&act.verb, &change.table, &change.row_id);        if change.kind == Kind::Create {            // THE CARRY is the one create that may hold a set mirror: the            // offline import brings a row across as the old file held it, and            // a revocation the old build wrote (fact or mirror alone) stands            // as it stood before the stop.            if matches!(act.actor, Actor::Import(_)) {                continue;            }            if let Some((column, _)) = named.iter().find(|(_, value)| !value.is_null()) {                return Err(StoreError::refused(format!(                    "`{verb}` creates {table} {row} with {column} set, but a row is born unrevoked and only revocation::revoke sets it afterwards."                )));            }            continue;        }        for (column, _) in &named {            let held = db                .get(                    &format!("SELECT {column} AS held FROM {table} WHERE id = ?"),                    &[SqlValue::Text(row.clone())],                )?                .and_then(|found| found.get("held").cloned())                .is_some_and(|value| !matches!(value, SqlValue::Null));            if held {                return Err(StoreError::refused(format!(                    "`{verb}` writes {table}.{column} of {row}, which is already set, and a revocation's mirror is never cleared or rewritten."                )));            }        }        if !written_beside_its_fact(act, change, patch) {            let (column, _) = named[0];            return Err(StoreError::refused(format!(                "`{verb}` writes {table}.{column} of {row}, which only revocation::revoke writes, beside the cotton_revocations fact it records."            )));        }    }    Ok(())}/// Is this mirror the one [`revoke`] wrote: a set `revoked_at`, and in the/// same act a created `cotton_revocations` fact naming this row at that same/// moment?fn written_beside_its_fact(act: &Act, change: &Change, patch: &Map<String, JsonValue>) -> bool {    let Some(at) = patch.get("revoked_at").filter(|value| !value.is_null()) else {        return false;    };    act.changes.iter().any(|fact| {        fact.table == FACTS            && fact.kind == Kind::Create            && fact.patch.as_ref().is_some_and(|fields| {                fields.get("subject_table").and_then(JsonValue::as_str) == Some(change.table.as_str())                    && fields.get("subject_id").and_then(JsonValue::as_str) == Some(change.row_id.as_str())                    && fields.get("revoked_at") == Some(at)            })    })}/// The revocation fact's hook in the fold's registry (`crate::fact_hooks`):/// a fact that ends a DEVICE's approval marks `_meta.rotation_check_due`, so/// the vault's rotation worker (slice 12) looks at the keys this file wraps.pub(crate) fn fact_folded(db: &Driver, fact: &Receipt) -> Result<()> {    if fact.fields.get("subject_table").and_then(JsonValue::as_str) != Some(DEVICES_SUBJECT) {        return Ok(());    }    let at = fact        .fields        .get("revoked_at")        .and_then(JsonValue::as_str)        .unwrap_or_default();    db.run(        "UPDATE _meta SET rotation_check_due = ?",        &[SqlValue::Text(at.to_string())],    )?;    Ok(())}/// The hook the fold runs when it takes a `cotton_devices` create/// (`crate::fact_hooks::row_taken`): an approval [`device_standing`] skips as/// ended late, or a skipped claimant's own approval/// ([`unended_skipped_claimants`]), marks `_meta.rotation_check_due`, so the/// serving Mac's pass writes its fact and mirror — a late approval arriving/// alone, with no fact beside it, still wakes the pass.pub(crate) fn approval_taken(db: &Driver, approval: &Receipt) -> Result<()> {    if approval.table != DEVICES_SUBJECT || approval.kind != Kind::Create {        return Ok(());    }    if !approval_ended_late(db, &approval.row_id)?        && !approval_of_a_skipped_claimant(db, &approval.row_id)?    {        return Ok(());    }    let at = crate::protocol::hlc::hlc_parts(&approval.stamp)        .ok()        .and_then(|parts| crate::protocol::js::to_iso_string(parts.ms))        .unwrap_or_else(|| approval.stamp.clone());    db.run(        "UPDATE _meta SET rotation_check_due = ?",        &[SqlValue::Text(at)],    )?;    Ok(())}/// The hook the fold runs when it takes a row of what an ended key HOLDS/// (`crate::fact_hooks::row_taken`): a live code credential, an unfinished/// job, or a runner with an unfinished job, whose holder key reads/// `Succeeded` or `Cut` ([`device_standing`]), marks/// `_meta.rotation_check_due` — so a skipped claimant's credential or job/// arriving in a LATER exchange than its approval wakes the serving Mac's/// pass, which ends it by the act's own routine. Nothing is ended here; a/// row already ended, or held by a `Live` or `Unknown` key, marks nothing.pub(crate) fn holding_taken(db: &Driver, receipt: &Receipt) -> Result<()> {    let sql = match receipt.table.as_str() {        "cotton_code_credentials" => {            "SELECT device_id AS holder FROM cotton_code_credentials WHERE id = ? AND revoked_at IS NULL"        }        "cotton_repo_jobs" => {            "SELECT r.device_id AS holder FROM cotton_repo_jobs j \             JOIN cotton_repo_runners r ON r.uuid = j.runner_uuid AND r.workspace_id = j.workspace_id \             WHERE j.id = ? AND j.status <> 'completed'"        }        "cotton_repo_runners" => {            "SELECT r.device_id AS holder FROM cotton_repo_runners r WHERE r.id = ? \               AND EXISTS (SELECT 1 FROM cotton_repo_jobs j \                           WHERE j.runner_uuid = r.uuid AND j.workspace_id = r.workspace_id \                             AND j.status <> 'completed')"        }        _ => return Ok(()),    };    let Some(holder) = db        .get(sql, &[SqlValue::Text(receipt.row_id.clone())])?        .and_then(|row| row.text("holder").map(str::to_string))    else {        return Ok(());    };    if !matches!(device_standing(db, &holder)?, Standing::Succeeded(_) | Standing::Cut) {        return Ok(());    }    let at = crate::protocol::hlc::hlc_parts(&receipt.stamp)        .ok()        .and_then(|parts| crate::protocol::js::to_iso_string(parts.ms))        .unwrap_or_else(|| receipt.stamp.clone());    db.run(        "UPDATE _meta SET rotation_check_due = ?",        &[SqlValue::Text(at)],    )?;    Ok(())}/// Every skipped claimant whose approvals this file holds and has ENDED —/// a fact or a mirror on each ([`crate::serving::skipped_claimants`] less/// [`unended_skipped_claimants`] and those with no approval here): the keys/// the serving Mac's pass has already ended what they hold for, and runs the/// act's routine for again, so what reaches it later is ended too.pub fn ended_skipped_claimants(db: &Driver) -> Result<Vec<crate::serving::SkippedClaimant>> {    let mut ended = Vec::new();    for claimant in crate::serving::skipped_claimants(db)? {        let approved = db            .get(                "SELECT 1 AS held FROM cotton_devices WHERE device_id = ?",                &[SqlValue::Text(claimant.device.clone())],            )?            .is_some();        if approved && !unended_approval_of(db, &claimant.device)? {            ended.push(claimant);        }    }    Ok(ended)}/// Is the approval `row_id` a skipped claimant's ([`crate::serving::skipped_by`])/// with neither a fact nor a mirror — one the serving Mac's pass owes its/// `succeeded` fact?fn approval_of_a_skipped_claimant(db: &Driver, row_id: &str) -> Result<bool> {    let Some(row) = db.get(        "SELECT d.device_id FROM cotton_devices d WHERE d.id = ? AND d.revoked_at IS NULL \           AND NOT EXISTS (SELECT 1 FROM cotton_revocations f \                           WHERE f.subject_table = 'cotton_devices' AND f.subject_id = d.id)",        &[SqlValue::Text(row_id.to_string())],    )?    else {        return Ok(false);    };    let key = row.text("device_id").unwrap_or_default();    Ok(crate::serving::skipped_by(db, key)?.is_some())}/// The store's refusal, shared by local writers and sync and shown verbatim.pub const LAST_FULL_DEVICE: &str =    "this is the last device that can approve others; add another first";/// Databases that have an approved Full device before an atomic fold. The/// first approval has no privilege: its approver is audit data, never a flag./// Both the revocation fact and its mirror end an approval, independently./// A person's revocation ends approvals born before it; a later admission/// and a new approval are another life, never a revival of the old row.pub(crate) fn approving_databases(db: &Driver) -> Result<Vec<String>> {    Ok(db        .all(            "SELECT DISTINCT d.workspace_id FROM cotton_devices d \         WHERE d.scope = 'full' AND d.approved_at <> '' AND d.revoked_at IS NULL \         AND NOT EXISTS (SELECT 1 FROM cotton_revocations r \             WHERE (r.subject_table = 'cotton_devices' AND r.subject_id = d.id) \             OR (r.subject_table = 'device_key' AND r.subject_id = d.device_id) \             OR (r.subject_table = 'person' AND r.subject_id = d.person_key \                 AND r._hlc > COALESCE((SELECT MIN(w.hlc) FROM _writes w \                     WHERE w.tbl='cotton_devices' AND w.row_id=d.id AND w.kind='create'), '')))",            &[],        )?        .into_iter()        .filter_map(|row| row.text("workspace_id").map(str::to_string))        .collect())}/// The store's refusal of a device approving itself where another can.pub const SELF_APPROVAL: &str =    "a device approves itself only when the database has no other approved device; approve this one from a device already in it";/// ONE RULE FOR SELF-APPROVAL: a device approves itself only when its/// database holds no other approved Full device — the first device of a new/// database, or a restore whose act ends the old root it replaces (`except`)/// with nothing else left to approve it; a second self-approval, or a restore/// where approved devices remain, joins by an approval from a device already/// in the database (architect, 14 Oct 2026: self-approval would otherwise/// recreate the privilege the root once was).////// ASKED BY THE ACT THAT SELF-APPROVES (`DeviceWrite::self_approve`), NEVER BY/// THE FOLD: a row already self-approved is history, and a copy of the file/// (the mover, a replica folding from the start) carries it beside every other/// device. Judging carried rows would drop a live device from the copy.pub fn other_approved_full(db: &Driver, workspace_id: &str, device_id: &str, except: Option<&str>) -> Result<bool> {    Ok(db        .get(            "SELECT 1 AS n FROM cotton_devices d \             WHERE d.workspace_id = ? AND d.device_id <> ? AND d.device_id <> ? \             AND d.scope = 'full' AND d.approved_at <> '' AND d.revoked_at IS NULL \             AND NOT EXISTS (SELECT 1 FROM cotton_revocations r \                 WHERE (r.subject_table = 'cotton_devices' AND r.subject_id = d.id) \                 OR (r.subject_table = 'device_key' AND r.subject_id = d.device_id) \                 OR (r.subject_table = 'person' AND r.subject_id = d.person_key \                 AND r._hlc > COALESCE((SELECT MIN(w.hlc) FROM _writes w \                     WHERE w.tbl='cotton_devices' AND w.row_id=d.id AND w.kind='create'), ''))) LIMIT 1",            &[                SqlValue::Text(workspace_id.to_string()),                SqlValue::Text(device_id.to_string()),                SqlValue::Text(except.unwrap_or(device_id).to_string()),            ],        )?        .is_some())}/// Check the committed shape, not intermediate writes: a key replacement can/// admit its successor and retire the previous approval in either order./// Called inside the fold transaction, so a refusal rolls back every receipt,/// fact, mirror and side effect. Mint, routes and pulled sync all use it.pub(crate) fn retain_approving_devices(db: &Driver, before: &[String]) -> Result<()> {    if before.is_empty() {        return Ok(());    }    let after = approving_databases(db)?;    if before.iter().any(|workspace| !after.contains(workspace)) {        return Err(StoreError::refused(LAST_FULL_DEVICE));    }    Ok(())}