Cotton code
186 lines · 8.7 KB · RustRaw
//! The person key on the owner's object: the phone//! publishes it to the kit's `person_key` table, so the object can verify an//! unlock window's grant and an IP allowlist change against its public half.//!//! - **Publish** ([`publish_owed`]): after a pass, a signed-in personal copy//!   that holds its person key (`cotton_person_keys`) posts it to the object//!   once per launch: `create person_key {id: fingerprint, public_key,//!   sealed_private_enc, vmk_version, created_at}`. The object answers the//!   same key again as it stands, so the first pass after every sign-in//!   publishes and nothing is asked twice.//! - **Keep** ([`ensure`]): a signed-in copy that founded its vault on the//!   object (`vault::found_on_need`) has no person key, since only a local//!   founding mints one. The first time the vault opens on such a copy the//!   key is taken from the object when the object holds one (another vault//!   device made it, or this phone was reinstalled: its sealed half opens//!   with the vault key) and minted here when it holds none, then published.//!   The object is asked directly, never the copy, which may not have pulled//!   it yet; a copy with no line to the object makes nothing.//!//! The private half is opened in one place, the vault's signing call//! (`vault::sign_as_person`); here it is only carried sealed between the//! copy and the object, and opened once to check that the object's key//! opens under this vault before the copy keeps it.//!//! The private half leaves only sealed under the vault key; the object never//! holds a key that opens it.use std::collections::BTreeSet;use std::sync::Mutex;use serde_json::{json, Map, Value};use cotton_core::keys::PersonKey;use cotton_core::vault::Vmk;use cotton_tools::mcp::handlers::common::insert_row;use crate::methods::MethodError;use crate::shell::client::ClientController;/// The object's table.pub const TABLE: &str = "person_key";/// The copy's own table (insert-only; never pushed: no storage map names it).const PERSON_KEYS: &str = "cotton_person_keys";/// The databases this launch has published the person key to, by client.static PUBLISHED: Mutex<BTreeSet<(usize, String)>> = Mutex::new(BTreeSet::new());fn latch_key(client: &ClientController, database: &str) -> (usize, String) {    (client as *const ClientController as usize, database.to_string())}fn unreadable(why: String) -> MethodError {    MethodError::new("could_not_read", why)}/// The person key row this copy holds, as the object takes it.struct Held {    id: String,    public_key: String,    sealed: String,    vmk_version: i64,    created_at: String,}fn held(client: &ClientController) -> Result<Option<Held>, MethodError> {    client        .with_file(|replica| {            let row = replica                .driver                .get(                    &format!("SELECT id, public_key, sealed_private, vmk_version, created_at FROM {PERSON_KEYS} WHERE workspace_id = ? ORDER BY created_at, id LIMIT 1"),                    &[rusqlite::types::Value::Text(replica.workspace_id.to_string())],                )                .map_err(|error| error.to_string())?;            Ok(row.and_then(|row| {                Some(Held {                    id: row.text("id")?.to_string(),                    public_key: row.text("public_key")?.to_string(),                    sealed: row.text("sealed_private")?.to_string(),                    vmk_version: row.int("vmk_version").unwrap_or(0),                    created_at: row.text("created_at").unwrap_or_default().to_string(),                })            }))        })        .map_err(unreadable)}/// The person key the object holds, asked of it directly (never a copy/// that may not have pulled it yet: a rival key minted here would be kept/// for good, the copy's table being insert-only).fn served(door: &crate::phone::personal_object::ObjectDoor) -> Result<Option<Held>, MethodError> {    let path = format!("{}?since=0&tables={TABLE}", cotton_client::transport::object::routes::SYNC);    let answer = door.send("GET", &path, None)?;    Ok(answer["rows"].as_array().into_iter().flatten().filter(|row| row["table"] == json!(TABLE) && row["deleted"] != json!(true)).find_map(|row| {        let data = &row["data"];        Some(Held {            id: row["id"].as_str()?.to_string(),            public_key: data["public_key"].as_str()?.to_string(),            sealed: data["sealed_private_enc"].as_str()?.to_string(),            vmk_version: data["vmk_version"].as_i64().unwrap_or(0),            created_at: data["created_at"].as_str().unwrap_or_default().to_string(),        })    }))}/// Whether this copy is a signed-in copy of the PERSONAL database, the one a/// person key belongs to.fn personal_signed_in(client: &ClientController) -> bool {    client.signed_in() && client.write_refusal().is_none() && client.require_personal().is_ok()}/// Give a signed-in personal copy its person key, with the vault open/// (`vmk` at `version`): taken from the object when it holds one, minted/// here when it holds none, then published. A copy that holds one already/// is left as it is.pub(crate) fn ensure(client: &ClientController, vmk: &Vmk, version: u32) -> Result<(), MethodError> {    if !personal_signed_in(client) {        return Ok(());    }    let _personal = client.name_database(None).map_err(unreadable)?;    if held(client)?.is_some() {        return Ok(());    }    // Only a copy that can ask the object makes or takes one.    let Some(door) = client.object_door() else { return Ok(()) };    let row = match served(&door)? {        Some(served) => {            let at = u32::try_from(served.vmk_version).unwrap_or(0);            if PersonKey::open_private(vmk, &served.public_key, at, &served.sealed).is_none() {                return Err(MethodError::new("person_key_does_not_open", "This phone can't open your account yet. One more step: approve this phone from your other phone, or enter your recovery code."));            }            served        }        None => {            let key = PersonKey::mint();            let sealed = key.seal_private(vmk, version).ok_or_else(|| MethodError::new("person_key_unsealable", "The person key could not be sealed."))?;            Held { id: key.fingerprint(), public_key: key.public_key(), sealed, vmk_version: i64::from(version), created_at: client.now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true) }        }    };    let mut patch = Map::new();    patch.insert("public_key".into(), Value::from(row.public_key.clone()));    patch.insert("sealed_private".into(), Value::from(row.sealed.clone()));    patch.insert("vmk_version".into(), Value::from(row.vmk_version));    patch.insert("created_at".into(), Value::from(row.created_at.clone()));    let id = row.id.clone();    client        .write_rows("person.keep", &mut |ctx| {            insert_row(ctx, PERSON_KEYS, &id, patch.clone()).map_err(|failure| failure.to_string())?;            Ok(json!({ "id": id }))        })        .map_err(|why| MethodError::new("refused", why))?;    publish(client).map(|_| ())}/// Post this copy's person key to the object. Answers the fingerprint, or/// `None` when this copy holds no person key yet.pub(crate) fn publish(client: &ClientController) -> Result<Option<String>, MethodError> {    let _personal = client.name_database(None).map_err(unreadable)?;    let database = client.current_database().map_err(unreadable)?;    let Some(row) = held(client)? else { return Ok(None) };    let door = client.object_door().ok_or_else(|| MethodError::new("sign_in_first", "the person key is published once the database is on its object"))?;    let data = json!({ "public_key": row.public_key, "sealed_private_enc": row.sealed, "vmk_version": row.vmk_version, "created_at": row.created_at });    door.send("POST", cotton_client::transport::object::routes::ACT, Some(&json!({ "act": "create", "args": { "table": TABLE, "id": row.id, "data": data } })))?;    PUBLISHED.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert(latch_key(client, &database));    Ok(Some(row.id))}/// What a pass runs when it ends: publish the person key to a signed-in/// personal object once per launch. `None` when nothing is owed.pub fn publish_owed(client: &ClientController) -> Option<Result<String, MethodError>> {    if !personal_signed_in(client) || client.object_door().is_none() {        return None;    }    let database = {        let _personal = client.name_database(None).ok()?;        client.current_database().ok()?    };    if PUBLISHED.lock().unwrap_or_else(std::sync::PoisonError::into_inner).contains(&latch_key(client, &database)) {        return None;    }    publish(client).transpose()}#[cfg(test)]#[path = "person_key_tests.rs"]mod tests;