Cotton code
61 lines · 2.6 KB · RustRaw
//! An OAuth refresh chain's rotations, as facts (slice 5b-i, step 5).//!//! Every rotation of a grant's refresh chain writes, in the act that moves the//! grant row, one `cotton_grant_rotations` fact at//! [`crate::protocol::derived_id::grant_rotation_id`] — `(file namespace,//! grant, generation)` — carrying the SHA-256 of the token that generation//! is. A fact is only ever inserted (`crate::fact_hooks`): of two different//! writes to one id the earlier `(stamp, op id)` stands on every device and the//! other parks `conflict`. So two Macs that each moved one chain to one//! generation with DIFFERENT tokens leave a standing fact and a parked one on//! both files, and that is what [`forked`] reads: the chain forked, which is//! reuse — the same answer as a spent token presented again.//!//! Two Macs that moved the chain with the SAME token (one presentation in//! flight at both) write the same digest, and that is not reuse.//!//! The grant row's `refresh_generation`, `refresh_rotated_at` and//! `refresh_digest` stay the current value every reader reads, settled by//! `crate::fold::COLUMN_POLICIES`.use rusqlite::types::Value as SqlValue;use sha2::{Digest, Sha256};use crate::driver::Driver;use crate::error::Result;/// The table of rotation facts.pub const TABLE: &str = "cotton_grant_rotations";/// What a rotation fact's `digest` holds for `token`: the SHA-256 hex of the/// whole string, nothing else — the generation and the writer are columns of/// their own, so two Macs that minted the one successor write one digest.pub fn token_digest(token: &str) -> String {    hex::encode(Sha256::digest(token.as_bytes()))}/// Whether some generation of `grant_id`'s chain was reached with two/// different tokens: a standing fact and a parked write of the same fact id/// whose digests differ. Two digests at one generation count as reuse.pub fn forked(db: &Driver, grant_id: &str) -> Result<bool> {    let standing = db.all(        "SELECT id, digest FROM cotton_grant_rotations WHERE grant_id = ?",        &[SqlValue::Text(grant_id.to_string())],    )?;    for fact in &standing {        let (Some(id), Some(digest)) = (fact.text("id"), fact.text("digest")) else {            continue;        };        for parked in crate::rejected::conflicts_of_row(db, TABLE, id)? {            let other = parked                .patch                .as_ref()                .and_then(|patch| patch.get("digest"))                .and_then(serde_json::Value::as_str);            if other.is_some_and(|other| other != digest) {                return Ok(true);            }        }    }    Ok(false)}