Cotton code
369 lines · 18.3 KB · RustRaw
//! The Mac importer's vault over a synthetic workspace: it publishes, the//! phone approves through `cotton_client::vault::devices::approve` (the method//! `vault.approveDevice` runs), and the importer opens a v2-sealed value and a//! passkey row. No Chrome, no network: the object is a map of rows. Every key//! is invented (`[26u8; 32]` style), as `founding.rs`'s tests use.use std::cell::RefCell;use std::collections::BTreeMap;use std::sync::Arc;use chrono::{DateTime, Utc};use cotton_core::keys::passkey::{make, Algorithm};use cotton_store::Driver;use cotton_tools::mcp::dispatch::{Ctx, ToolServices};use rusqlite::types::Value as SqlValue;use super::*;const WORKSPACE: &str = "00000000-0000-4000-8000-0000000000d1";const OWNER: &str = "00000000-0000-4000-8000-0000000000d2";const PHONE: &str = "device:owner-phone";const MAC: &str = "mac-install-invented";const NOW: &str = "2026-11-07T10:00:00.000Z";/// The object's `vault_key` rows, by id.#[derive(Default)]struct Object {    rows: RefCell<BTreeMap<String, Map<String, Value>>>,    puts: RefCell<usize>,}impl KeyRows for Object {    fn key_row(&self, device_id: &str) -> Result<Option<(String, Map<String, Value>)>, ObjectError> {        Ok(self            .rows            .borrow()            .iter()            .find(|(_, data)| data.get("device_id").and_then(Value::as_str) == Some(device_id))            .map(|(id, data)| (id.clone(), data.clone())))    }    fn put_key_row(&self, id: &str, data: &Value) -> Result<(), ObjectError> {        *self.puts.borrow_mut() += 1;        self.rows.borrow_mut().insert(id.to_string(), data.as_object().unwrap().clone());        Ok(())    }}fn vmk() -> Vmk {    Vmk::from_bytes([40u8; 32])}// ── the phone's side: its copy, its founding row, its approval ─────────────fn phone_file() -> Driver {    let db = cotton_store::test_template::create_workspace_in_memory_for_test(&cotton_store::meta::Meta {        workspace_id: WORKSPACE.into(),        owner_id: OWNER.into(),        device_id: "device:phone-copy".into(),        last_server_seq: 0,        last_hlc: None,    })    .unwrap();    let text = |s: &str| SqlValue::Text(s.into());    db.run(        "INSERT INTO cotton_workspaces (id, name, owner_user_id, created_at, _hlc) VALUES (?, 'Vault', ?, ?, '')",        &[text(WORKSPACE), text(OWNER), text(NOW)],    )    .unwrap();    db.run(        "INSERT INTO cotton_devices (id, workspace_id, device_id, name, approved_at, approved_by_device, created_at, updated_at)         VALUES ('row-phone', ?, ?, 'Owner phone', ?, 'self', ?, ?)",        &[text(WORKSPACE), text(PHONE), text(NOW), text(NOW), text(NOW)],    )    .unwrap();    // The founding phone: its own wrap at version 1, and the vault's state.    let wrapped = wrap::wrap(&wrap::public_of(&[26u8; 32]), vmk().expose()).unwrap();    db.run(        "INSERT INTO cotton_vault_keys (id, workspace_id, device_id, public_key, wrapped_vmk, vmk_version, created_at, updated_at)         VALUES ('key-phone', ?, ?, ?, ?, 1, ?, ?)",        &[text(WORKSPACE), text(PHONE), text(&URL_SAFE_NO_PAD.encode(wrap::public_of(&[26u8; 32]))), text(&wrapped), text(NOW), text(NOW)],    )    .unwrap();    db.run(        "INSERT INTO cotton_vault_state (workspace_id, vmk_version, rotated_at, created_at, updated_at) VALUES (?, 1, ?, ?, ?)",        &[text(WORKSPACE), text(NOW), text(NOW), text(NOW)],    )    .unwrap();    db}static FILE: std::sync::LazyLock<cotton_store::file_identity::FileIdentity> =    std::sync::LazyLock::new(|| cotton_store::file_identity::FileIdentity::for_tests(WORKSPACE));/// The object's row coming down into the phone's copy, as a pull lays it.fn pull_into_phone(db: &Driver, id: &str, data: &Map<String, Value>) {    db.run(        "INSERT INTO cotton_vault_keys (id, workspace_id, device_id, public_key, wrapped_vmk, vmk_version, created_at, updated_at)         VALUES (?, ?, ?, ?, NULL, 0, ?, ?)",        &[            SqlValue::Text(id.into()),            SqlValue::Text(WORKSPACE.into()),            SqlValue::Text(data["device_id"].as_str().unwrap().into()),            SqlValue::Text(data["public_key"].as_str().unwrap().into()),            SqlValue::Text(NOW.into()),            SqlValue::Text(NOW.into()),        ],    )    .unwrap();}/// The phone approves, as `vault.approveDevice` does with the VMK its own wrap/// opened to, and the change goes up to the object.fn phone_approves(db: &Driver, object: &Object, id: &str) {    let mine = db.get("SELECT wrapped_vmk FROM cotton_vault_keys WHERE id = 'key-phone'", &[]).unwrap().unwrap();    let opened: [u8; 32] = wrap::unwrap(&[26u8; 32], mine.text("wrapped_vmk").unwrap()).unwrap().try_into().unwrap();    let services = ToolServices::none();    let actor = cotton_store::actor::Actor::Owner(cotton_store::actor::DeviceId::in_file(db, "row-phone").unwrap());    let mut ctx = Ctx::phone(        db,        &FILE,        OWNER,        PHONE,        actor,        cotton_store::mint::Held::Replica,        NOW.parse::<DateTime<Utc>>().unwrap(),        Arc::new(cotton_tools::random::SystemRandom),        &services,    );    cotton_client::vault::devices::approve(&mut ctx, MAC, &Vmk::from_bytes(opened), 1).unwrap();    ctx.commit().unwrap();    let row = db.get("SELECT wrapped_vmk, vmk_version FROM cotton_vault_keys WHERE id = ?", &[SqlValue::Text(id.into())]).unwrap().unwrap();    let mut rows = object.rows.borrow_mut();    let data = rows.get_mut(id).unwrap();    data.insert("wrapped_vmk".into(), json!(row.text("wrapped_vmk").unwrap()));    data.insert("vmk_version".into(), json!(row.int("vmk_version").unwrap()));}#[test]fn the_mac_publishes_waits_and_opens_a_sealed_value_once_the_phone_approves() {    let keyring = MemoryKeyring::default();    let object = Object::default();    let vault = ImporterVault::new(&keyring, MAC, "Owner's Mac mini");    // First pass: a key is minted and kept, its public half published.    let Pass::Waiting { fingerprint } = vault.pass(&object).unwrap() else { panic!("waiting first") };    let kept = keyring.load().unwrap().expect("the private half is in the keyring");    let row_id = vault.row_id();    let published = object.rows.borrow()[&row_id].clone();    assert_eq!(published["device_id"], json!(MAC));    assert_eq!(published["name"], json!("Owner's Mac mini"));    assert_eq!(published["public_key"], json!(URL_SAFE_NO_PAD.encode(wrap::public_of(&kept))));    assert_eq!(published["wrapped_vmk"], Value::Null);    assert!(!Value::Object(published.clone()).to_string().contains(&URL_SAFE_NO_PAD.encode(*kept)), "never the private half");    assert_eq!(fingerprint, vault.fingerprint().unwrap());    // Second pass, nothing approved yet: still waiting, nothing written again.    assert!(matches!(vault.pass(&object).unwrap(), Pass::Waiting { .. }));    assert_eq!(*object.puts.borrow(), 1);    // The signer's open, before approval, opens nothing and writes nothing.    assert!(vault.open_only(&object).unwrap().is_none());    assert!(ImporterVault::new(&MemoryKeyring::default(), MAC, "m").open_only(&object).unwrap().is_none(), "no key, no vault, no mint");    assert_eq!(*object.puts.borrow(), 1);    // The row comes down to the phone, which lists it pending and approves it.    let phone = phone_file();    pull_into_phone(&phone, &row_id, &published);    let listed = cotton_client::vault::devices::keys(&phone, WORKSPACE).unwrap();    assert_eq!(listed[0].device_id, MAC);    assert_eq!(listed[0].fingerprint.as_deref(), Some(fingerprint.as_str()), "both screens show one fingerprint");    phone_approves(&phone, &object, &row_id);    // The next pass opens the vault and a value the phone sealed v2.    let Pass::Open(open) = vault.pass(&object).unwrap() else { panic!("open once approved") };    assert_eq!(open.version(), 1);    assert_eq!(vault.open_only(&object).unwrap().expect("the signer opens it too").version(), 1);    let sealed = seal::seal(&vmk(), "secret-row-1", 1, b"synthetic payload").unwrap();    assert_eq!(open.open("secret-row-1", 1, &sealed).unwrap().as_slice(), b"synthetic payload");    assert!(open.open("secret-row-2", 1, &sealed).is_none());    // And a passkey row the phone sealed: the WhatsApp signer's input.    let key = make("web.whatsapp.com", "dXNlci0x", Algorithm::Es256).unwrap();    let row = passkey_row::seal(&key, &vmk(), "passkey-row-1", 1).unwrap();    let opened = open.passkey("passkey-row-1", &row.columns()).unwrap();    assert_eq!(opened.verifying_key(), key.verifying_key());    assert!(!format!("{open:?}").contains("40"), "the debug line names the version only");}#[test]fn a_lost_keychain_item_publishes_the_new_key_and_waits_again() {    let keyring = MemoryKeyring::default();    let object = Object::default();    let vault = ImporterVault::new(&keyring, MAC, "Owner's Mac mini");    vault.pass(&object).unwrap();    let first = object.rows.borrow()[&vault.row_id()]["public_key"].clone();    // An approval for the first key arrived, then the Keychain item was lost.    object.rows.borrow_mut().get_mut(&vault.row_id()).unwrap().insert("wrapped_vmk".into(), json!("w1:for-the-old-key"));    keyring.store(&[29u8; 32]).unwrap();    assert!(matches!(vault.pass(&object).unwrap(), Pass::Waiting { .. }));    let row = object.rows.borrow()[&vault.row_id()].clone();    assert_ne!(row["public_key"], first);    assert_eq!(row["wrapped_vmk"], Value::Null, "the old wrap is for a key this Mac no longer has");}#[test]fn a_wrap_for_another_key_is_named_and_a_system_without_a_keychain_waits_with_words() {    let keyring = MemoryKeyring::default();    let object = Object::default();    let vault = ImporterVault::new(&keyring, MAC, "Owner's Mac mini");    vault.pass(&object).unwrap();    let other = wrap::wrap(&wrap::public_of(&[31u8; 32]), vmk().expose()).unwrap();    object.rows.borrow_mut().get_mut(&vault.row_id()).unwrap().insert("wrapped_vmk".into(), json!(other));    assert!(matches!(vault.pass(&object), Err(VaultError::WrapDoesNotOpen)));    let none = ImporterVault::new(&NoKeyring, MAC, "Owner's Mac mini");    let error = none.pass(&Object::default()).err().expect("no keychain, no key");    assert_eq!(error.to_string(), "this system has no Keychain to keep the vault key in");}/// The login Keychain itself, under a synthetic service removed as the test/// ends: it keeps a key, gives it back, replaces it and forgets it, with no/// prompt (a prompt would hang a non-interactive run). The bytes are invented/// and never printed: comparisons are `assert!`, not `assert_eq!`.#[cfg(target_os = "macos")]#[test]fn the_login_keychain_keeps_gives_back_and_forgets_a_key_without_asking() {    struct Forget(String);    impl Drop for Forget {        fn drop(&mut self) {            let _ = security_framework::passwords::delete_generic_password(&self.0, MAC);        }    }    let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();    let service = format!("{KEYCHAIN_SERVICE}.test-{}-{nanos}", std::process::id());    let forget = Forget(service.clone());    let keychain = LoginKeychain::under(&service, MAC);    assert!(keychain.load().expect("an empty Keychain answers").is_none());    keychain.store(&[26u8; 32]).expect("the Keychain keeps the key");    assert!(keychain.load().unwrap().is_some_and(|key| *key == [26u8; 32]));    keychain.store(&[27u8; 32]).expect("the Keychain replaces the key");    assert!(keychain.load().unwrap().is_some_and(|key| *key == [27u8; 32]));    drop(forget);    assert!(keychain.load().unwrap().is_none(), "the test's item is gone");}// ── the recovery code (e2e rulings R7c) ────────────────────────────────────/// The object's way back in by a code, as `/v1/recovery` keeps it: the salt and stretch, the hash of the proof,/// and the VMK's wrap; a wrong proof is refused and counted.struct Recovery {    held: Value,    auth_hash: String,    wrapped: String,    version: u32,    tries: RefCell<u32>,}impl Recovery {    fn set(code: &str, vmk: &Vmk, version: u32) -> Recovery {        use cotton_core::vault::recovery_code as rc;        let salt = [9u8; 16];        let kdf = rc::Kdf::SCRYPT;        let keys = rc::derive(rc::normalize(code).unwrap().as_bytes(), &salt, kdf).unwrap();        Recovery {            held: json!({ "code": { "salt": URL_SAFE_NO_PAD.encode(salt), "kdf": kdf.text(), "vmk_version": version }, "google": null, "apple": null }),            auth_hash: rc::auth_hash(&keys.auth),            wrapped: rc::wrap(&keys.wrap, rc::Kind::Code, version, vmk.expose()).unwrap(),            version,            tries: RefCell::new(0),        }    }}impl RecoveryDoor for Recovery {    fn held(&self) -> Result<Value, ObjectError> {        Ok(self.held.clone())    }    fn open_code(&self, auth: &str) -> Result<Value, ObjectError> {        let auth: [u8; 32] = URL_SAFE_NO_PAD.decode(auth).unwrap().try_into().unwrap();        if cotton_core::vault::recovery_code::auth_hash(&auth) != self.auth_hash {            *self.tries.borrow_mut() += 1;            return Err(ObjectError::Refused { status: 403, code: "recovery_wrong".into(), message: "That code is not the one saved.".into() });        }        Ok(json!({ "wrapped": self.wrapped, "vmk_version": self.version }))    }}/// RULE (e2e rulings R7c, step 1): the recovery code typed once on the Mac opens the vault with no phone at hand: the Mac proves the code to the object, opens the vault key, and writes its own row approved, so the next pass opens with the Keychain alone. A code that is mistyped is said before anything is sent; a wrong one is the object's refusal and changes nothing; the code is in nothing the Mac writes.#[test]fn a_recovery_code_typed_once_opens_the_vault_and_approves_this_mac() {    let code = cotton_core::vault::recovery_code::mint();    let recovery = Recovery::set(&code, &vmk(), 3);    let object = Object::default();    let keyring = MemoryKeyring::default();    let vault = ImporterVault::new(&keyring, MAC, "Synthetic Mac");    // Mistyped: its check does not hold, and nothing is asked of the object.    let mut wrong_check: Vec<char> = code.chars().collect();    let last = wrong_check.len() - 1;    wrong_check[last] = if wrong_check[last] == '2' { '3' } else { '2' };    let mistyped: String = wrong_check.into_iter().collect();    assert!(matches!(vault.open_by_code(&object, &recovery, &mistyped), Err(VaultError::Code(_))));    assert_eq!((*recovery.tries.borrow(), *object.puts.borrow()), (0, 0));    // Another real code: the object refuses it, and no row is written.    let other = cotton_core::vault::recovery_code::mint();    assert!(matches!(vault.open_by_code(&object, &recovery, &other), Err(VaultError::Object(ObjectError::Refused { ref code, .. })) if code == "recovery_wrong"));    assert_eq!((*recovery.tries.borrow(), *object.puts.borrow()), (1, 0));    // The code, typed in lower case with spaces: the vault opens and this Mac's row is approved.    let typed = code.to_lowercase().replace('-', " ");    let open = vault.open_by_code(&object, &recovery, &typed).unwrap();    assert_eq!(open.version(), 3);    let sealed = seal::seal(&vmk(), "row-1", 3, b"a secret").unwrap();    assert_eq!(open.open("row-1", 3, &sealed).unwrap().as_slice(), b"a secret");    let (_, row) = object.key_row(MAC).unwrap().unwrap();    assert_eq!(row["vmk_version"], 3);    assert!(row["wrapped_vmk"].as_str().unwrap().starts_with("w1:"));    assert!(!Value::Object(row).to_string().contains(&cotton_core::vault::recovery_code::normalize(&code).unwrap()), "the code is in nothing written");    // The next pass opens with the Keychain alone: no code, no phone.    assert!(matches!(vault.pass(&object).unwrap(), Pass::Open(_)));}/// RULE: a Mac that opens the vault lets a waiting device in, as Keys › Devices › Approve does on a phone: the wrap it writes opens with that device's own key to the same vault key, at the Mac's version. A Mac that is still waiting, a device with no row and a device already let in change nothing.#[test]fn a_mac_that_opens_the_vault_lets_a_waiting_device_in() {    let code = cotton_core::vault::recovery_code::mint();    let recovery = Recovery::set(&code, &vmk(), 3);    let object = Object::default();    let keyring = MemoryKeyring::default();    let vault = ImporterVault::new(&keyring, MAC, "Synthetic Mac");    let phone_secret = wrap::mint_vault_key();    let phone_public = URL_SAFE_NO_PAD.encode(wrap::public_of(&phone_secret));    object.put_key_row("vault-key-phone", &json!({ "device_id": PHONE, "name": "Synthetic phone", "public_key": phone_public, "wrapped_vmk": Value::Null, "vmk_version": 0 })).unwrap();    // Still waiting itself: it can let nobody in.    assert!(matches!(vault.pass(&object).unwrap(), Pass::Waiting { .. }));    assert!(matches!(vault.approve(&object, PHONE), Err(VaultError::NotOpen)));    vault.open_by_code(&object, &recovery, &code).unwrap();    assert!(matches!(vault.approve(&object, "device:nobody"), Err(VaultError::NoSuchDevice)));    let puts = *object.puts.borrow();    let print = vault.approve(&object, PHONE).unwrap();    assert_eq!(Some(print), wrap::fingerprint(&phone_public));    assert_eq!(*object.puts.borrow(), puts + 1);    let (_, row) = object.key_row(PHONE).unwrap().unwrap();    assert_eq!((row["vmk_version"].as_u64(), row["name"].as_str(), row["public_key"].as_str()), (Some(3), Some("Synthetic phone"), Some(phone_public.as_str())));    let opened = wrap::unwrap(&phone_secret, row["wrapped_vmk"].as_str().unwrap()).unwrap();    assert_eq!(opened.as_slice(), vmk().expose());    // Already in: nothing more is written.    assert!(matches!(vault.approve(&object, PHONE), Err(VaultError::AlreadyApproved)));    assert_eq!(*object.puts.borrow(), puts + 1);}/// RULE (e2e rulings R7c): an account that saved no recovery code says so, and nothing is written.#[test]fn an_account_with_no_recovery_code_says_so() {    let mut recovery = Recovery::set(&cotton_core::vault::recovery_code::mint(), &vmk(), 1);    recovery.held = json!({ "code": null, "google": null, "apple": null });    let object = Object::default();    let keyring = MemoryKeyring::default();    let vault = ImporterVault::new(&keyring, MAC, "Synthetic Mac");    assert!(matches!(vault.open_by_code(&object, &recovery, &cotton_core::vault::recovery_code::mint()), Err(VaultError::NoCode)));    assert_eq!(*object.puts.borrow(), 0);}