Cotton code
207 lines · 9.5 KB · RustRaw
//! The Mac hands Your Claude its keys (HANDING STUCK, 25 Nov 2026; contract: assets/design/shared/OPEN-TABLES.md,//! "Contract: the Mac hands Your Claude's keys too").//!//! A phone hands every live grant to the person's own Claude the keys of the tables the object serves sealed//! (`cotton-ffi` `assistants::top_up`), so the open tables lock's gate 2 can clear. A phone on an old build hands only//! its kit's tables. This Mac holds the data key and reads the object's whole definitions, so after its vault pass it//! hands them too, the way the phone does and with the core's own functions://!//! 1. the live account grants: rows of `unlock_grant`, by `cotton_core::rules::assistants::live`;//! 2. the sealed tables: every table of the whole `GET /v1/definitions` answer whose `seal` is an object;//! 3. what to hand: `rules::assistants::to_hand(grant, sealed, handed, version)`, `handed` this Mac's own record per//!    `request_id` ([`Record`], `hand_handed` in `importer.db`) and `version` each table's current key version from//!    the `seal_key` rows (`Sealer::version`, 1 when none): never a table the grant withholds, has turned off or to//!    ask, and never saved secrets (`NEVER`);//! 4. the wrap: `cotton_core::seal::agent::addition`, to the grant's member key;//! 5. `assistant_add { grant_id, tables, wrapped }` with this Mac's device credential, and on 200 those versions//!    recorded. A 409 `grant_ended` skips the grant.//!//! Nothing is signed: an addition widens no policy, and the object refuses a withheld table. The log says counts//! only, never a table's name, an id or a key.use std::sync::Arc;use base64::engine::general_purpose::URL_SAFE_NO_PAD;use base64::Engine as _;use cotton_client::seal::{DataKeyStore, Sealer, SEAL_KEY_TABLE};use cotton_core::rules::assistants as rules;use cotton_core::seal::agent::addition;use serde_json::{json, Value};use crate::object::{ObjectClient, ObjectError};/// The object's table of unlock grants; Your Claude's are its `account` rows.pub const GRANTS: &str = "unlock_grant";/// What this Mac handed each grant: the newest version of each table, by the grant's `request_id`.pub trait Record {    fn handed(&self, request_id: &str) -> Result<Vec<(String, u32)>, String>;    fn note(&self, request_id: &str, versions: &[(String, u32)]) -> Result<(), String>;}impl Record for crate::store::Store {    fn handed(&self, request_id: &str) -> Result<Vec<(String, u32)>, String> {        self.hand_handed(request_id).map_err(|e| e.to_string())    }    fn note(&self, request_id: &str, versions: &[(String, u32)]) -> Result<(), String> {        self.note_hand_handed(request_id, versions).map_err(|e| e.to_string())    }}/// What one hand-over did: counts only.#[derive(Debug, Default, Clone, PartialEq, Eq)]pub struct Handed {    /// Live grants to your Claude the object holds.    pub live: usize,    /// Grants handed at least one key.    pub grants: usize,    /// Tables' keys handed, summed over the grants.    pub tables: usize,    /// Grants whose addition was not made or the object refused (other than an ended grant).    pub refused: usize,}impl Handed {    /// The log's line: counts only.    pub fn line(&self) -> String {        format!("hand: {} live grant(s); {} handed {} table key(s); {} refused", self.live, self.grants, self.tables, self.refused)    }}/// One hand-over's outcome and the object version to look for changes from next time.#[derive(Debug, Clone, PartialEq, Eq)]pub struct Pass {    pub handed: Handed,    /// Whether anything was read and decided (false: nothing changed since `since`, or no data key).    pub looked: bool,    /// Ask `GET /v1/sync` from here next time; `since` again when a grant was refused, so it is asked again.    pub next_since: i64,}/// Every live row of `table` over `/v1/sync` from the start, each its data with its `id`.fn all_rows(object: &ObjectClient, table: &str) -> Result<Vec<Value>, String> {    let mut out = Vec::new();    let mut cursor: Option<String> = None;    loop {        let page = object.sync_page(0, &[table], cursor.as_deref()).map_err(|e| format!("a read failed ({})", code(&e)))?;        for row in page["rows"].as_array().into_iter().flatten() {            if row["table"] != table || row.get("deleted") == Some(&Value::Bool(true)) {                continue;            }            let (Some(id), Some(data)) = (row["id"].as_str(), row["data"].as_object()) else { continue };            let mut data = data.clone();            data.insert("id".into(), Value::String(id.to_string()));            out.push(Value::Object(data));        }        match page["next"].as_str() {            Some(next) => cursor = Some(next.to_string()),            None => break,        }    }    Ok(out)}/// Every table the whole definitions answer serves sealed (its `seal` is an object), sorted.fn served_sealed(object: &ObjectClient) -> Result<Vec<String>, String> {    let served = object.definitions().map_err(|e| format!("a read failed ({})", code(&e)))?;    let mut out: Vec<String> = served["tables"]        .as_array()        .into_iter()        .flatten()        .filter(|table| table.get("seal").is_some_and(Value::is_object))        .filter_map(|table| table["id"].as_str().map(str::to_string))        .collect();    out.sort();    out.dedup();    Ok(out)}fn text(row: &Value, key: &str) -> Option<String> {    row.get(key).and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()).map(str::to_string)}fn key32(text: &str) -> Option<[u8; 32]> {    URL_SAFE_NO_PAD.decode(text.trim_end_matches('=')).ok().and_then(|bytes| bytes.try_into().ok())}/// An object error by its status and code alone (never its words, which may name a table).fn code(error: &ObjectError) -> String {    match error {        ObjectError::Refused { status, code, .. } => format!("{status} {code}"),        ObjectError::SignedOut => "signed_out".into(),        ObjectError::Transport(_) => "unreachable".into(),        ObjectError::Decode(_) => "unparsed".into(),        ObjectError::File(_) => "file".into(),    }}/// One hand-over. `since` is the object version the last one looked from (`None` at launch: always look). Nothing/// while this Mac holds no data key for `database_id`. When `GET /v1/sync` of the grants and seal keys since `since`/// brings no row, nothing more is read. A read that fails fails the pass, asked again next time.pub fn hand(object: &ObjectClient, database_id: &str, keys: &Arc<dyn DataKeyStore>, record: &dyn Record, since: Option<i64>) -> Result<Pass, String> {    let Some(dk) = keys.data_key(database_id).map_err(|e| e.to_string())? else {        return Ok(Pass { handed: Handed::default(), looked: false, next_since: since.unwrap_or(0) });    };    let changed = object.sync_page(since.unwrap_or(0), &[GRANTS, SEAL_KEY_TABLE], None).map_err(|e| format!("a read failed ({})", code(&e)))?;    let now = changed["version"].as_i64().unwrap_or(since.unwrap_or(0));    let moved = changed["rows"].as_array().is_some_and(|rows| !rows.is_empty()) || changed["next"].is_string();    if since.is_some() && !moved {        return Ok(Pass { handed: Handed::default(), looked: false, next_since: now });    }    let grants = all_rows(object, GRANTS)?;    let live: Vec<&Value> = rules::live(&grants);    let mut handed = Handed { live: live.len(), ..Handed::default() };    if live.is_empty() {        return Ok(Pass { handed, looked: true, next_since: now });    }    let sealed = served_sealed(object)?;    let sealer = Sealer::new(database_id, Arc::clone(keys));    for row in all_rows(object, SEAL_KEY_TABLE)? {        if let (Some(id), Some(data)) = (text(&row, "id"), row.as_object()) {            sealer.learn(&id, data);        }    }    for g in live {        let (Some(grant_id), Some(member_id), Some(member_pub), Some(request_id)) = (text(g, "id"), text(g, "member_id"), text(g, "member_pub").as_deref().and_then(key32), text(g, "request_id")) else { continue };        let had = record.handed(&request_id)?;        let more = rules::to_hand(g, &sealed, &had, |t| sealer.version(t));        if more.is_empty() {            continue;        }        let wrapped = match addition(&dk, database_id, &member_id, &member_pub, &more, &rules::list(g, "withheld")) {            Ok(wrapped) => wrapped,            Err(error) => {                eprintln!("hand: a grant's addition was not made ({})", error.code());                handed.refused += 1;                continue;            }        };        let tables: Vec<String> = more.iter().map(|(t, _)| t.clone()).collect();        match object.post_act("assistant_add", &json!({ "grant_id": grant_id, "tables": tables, "wrapped": wrapped })) {            Ok(_) => {                record.note(&request_id, &more)?;                handed.grants += 1;                handed.tables += tables.len();            }            // The grant ended meanwhile: nothing to hand it, ever.            Err(ObjectError::Refused { status: 409, code, .. }) if code == "grant_ended" => {}            Err(error) => {                eprintln!("hand: the object refused a grant's addition ({})", self::code(&error));                handed.refused += 1;            }        }    }    let next_since = if handed.refused > 0 { since.unwrap_or(0) } else { now };    Ok(Pass { handed, looked: true, next_since })}#[cfg(test)]mod tests {    use super::*;    #[test]    fn the_log_line_is_counts_only() {        let line = Handed { live: 2, grants: 1, tables: 4, refused: 0 }.line();        assert_eq!(line, "hand: 2 live grant(s); 1 handed 4 table key(s); 0 refused");    }}