384 lines · 19.4 KB · RustRaw
//! `passkey.*` on a Cotton Keys phone: what the credential provider hands the//! app becomes a row sealed under the vault, counts its uses, lists as//! identities and mirrors back. Every key and id is invented.use base64::engine::general_purpose::URL_SAFE_NO_PAD;use base64::Engine as _;use serde_json::{json, Value};use zeroize::Zeroizing;use cotton_core::keys::passkey::{make_from, Algorithm};use cotton_core::vault::{seal, wrap, Vmk};use super::over;use crate::handle::CottonHandle;const RP: &str = "passkey.example";/// A fresh Cotton Keys phone, kept local (local first).fn phone() -> (tempfile::TempDir, CottonHandle) { let dir = tempfile::tempdir().expect("a temp container"); // Cotton Keys' manifest, said here (a Rust source reads only inside crates/). let manifest = json!({ "genesis": "personal", "flavour": "keys", "name": "Cotton Keys", "databases": "single", "database": "personal", "fan": {"home": false, "tools": false, "opens": "keys"}, "kit": "keys", }); let handle = CottonHandle::open(crate::handle::OpenConfig { mode: crate::handle::OpenMode::Phone { container_path: dir.path().to_string_lossy().to_string(), previous_container_path: None }, app_version: None, time_zone: Some("Asia/Kolkata".to_string()), device_secret: Some(crate::fixture::paired_secret()), vault_secret: None, flavor: cotton_core::flavor::Flavor::Real, manifest: Some(manifest), }) .expect("an open core"); crate::methods::dispatch(&handle, "workspace.startLocal", &json!({"deviceName": "An invented phone"})).expect("started"); (dir, handle)}/// This device's vault key, fixed: 32 bytes counting up. Opens nothing real.fn device_secret() -> [u8; 32] { std::array::from_fn(|i| i as u8)}fn vmk() -> Vmk { Vmk::from_bytes(std::array::from_fn(|i| 200u8.wrapping_sub(i as u8)))}fn b64(bytes: &[u8]) -> String { URL_SAFE_NO_PAD.encode(bytes)}fn exec(handle: &CottonHandle, sql: &str, params: &[&str]) { handle .client() .with_writer(|replica| { let bound: Vec<rusqlite::types::Value> = params.iter().map(|v| rusqlite::types::Value::Text((*v).to_string())).collect(); replica.driver.run(sql, &bound).map(|_| ()).map_err(|e| e.to_string()) }) .expect("the seed");}/// The vault as it stands once this device's key is wrapped at version 1.fn wrapped(handle: &CottonHandle) { let client = handle.client(); let workspace = client.with_writer(|replica| Ok(replica.workspace_id.to_string())).unwrap(); let device = client.self_device_id().expect("a device id"); let now = "2026-11-08T09:00:00.000Z"; exec(handle, "INSERT INTO cotton_vault_state (workspace_id, vmk_version, rotated_at, created_at, updated_at) VALUES (?, 1, ?, ?, ?)", &[&workspace, now, now, now]); let public = wrap::public_of(&device_secret()); let wrapped = wrap::wrap(&public, vmk().expose()).expect("a wrap"); exec( handle, "INSERT INTO cotton_vault_keys (id, workspace_id, device_id, public_key, wrapped_vmk, vmk_version, created_at, updated_at) VALUES ('vk-1', ?, ?, ?, ?, 1, ?, ?)", &[&workspace, &device, &b64(&public), &wrapped, now, now], );}/// What the provider's mailbox entry carries, with the scalar the app read/// from the keychain for this one call.fn registered(seed: u8, credential: u8) -> Value { let id = [credential; 16]; let handle = b64(b"synthetic-user-1"); let key = make_from(RP, &handle, Algorithm::Es256, id, Zeroizing::new([seed; 32])).unwrap(); json!({ "rp_id": RP, "rp_name": "Passkey Example", "user_name": "ada@passkey.example", "user_handle": handle, "credential_id": key.credential_id, "algorithm": "ES256", "public_key": key.public_key, "created_at": "2026-11-08T09:30:00Z", "privateScalar": b64(&[seed; 32]), })}fn row(handle: &CottonHandle, id: &str) -> serde_json::Map<String, Value> { handle .client() .with_writer(|replica| { let row = replica .driver .get("SELECT * FROM cotton_passkey WHERE id = ?", &[rusqlite::types::Value::Text(id.to_string())]) .map_err(|e| e.to_string())? .expect("the row"); Ok(row .columns() .iter() .map(|(name, value)| { let value = match value { rusqlite::types::Value::Text(t) => Value::from(t.clone()), rusqlite::types::Value::Integer(n) => Value::from(*n), rusqlite::types::Value::Real(x) => Value::from(*x), _ => Value::Null, }; (name.clone(), value) }) .collect()) }) .unwrap()}// RULE (Cotton Keys provider, 8 Nov 2026): a passkey the provider registered// becomes one passkey row through the app's own producer path, its private// half sealed v2 under the VMK and bound to the row's id, sign_count 0 and// uses 0; the readonly columns no person writes are written by this path// alone; saying it twice makes no second row.#[test]fn a_registered_passkey_becomes_a_sealed_row_once() { let (_dir, handle) = phone(); wrapped(&handle); let mut asked = registered(0x5a, 0xc0); asked["privateKey"] = json!(b64(&device_secret())); let made = over(&handle.client(), "passkey.register", &asked).expect("registered"); assert_eq!(made["made"], true); let id = made["id"].as_str().unwrap().to_string(); let stored = row(&handle, &id); assert_eq!(stored["rp_id"], RP); assert_eq!(stored["rp_name"], "Passkey Example"); assert_eq!(stored["sign_count"], 0); assert_eq!(stored["uses"], 0); assert_eq!(stored["vmk_version"], 1); assert_eq!(stored["created_at"], "2026-11-08T09:30:00Z"); let sealed = stored["private_key_enc"].as_str().unwrap(); assert!(sealed.starts_with(seal::SEAL_PREFIX), "sealed v2"); assert!(!sealed.contains(&b64(&[0x5a; 32])), "the scalar is not in the row"); assert_eq!(seal::open(&vmk(), &id, 1, sealed).unwrap(), vec![0x5a; 32], "bound to this row's id"); let again = over(&handle.client(), "passkey.register", &asked).expect("said twice"); assert_eq!(again, json!({"id": id, "made": false})); // A person or token patching the sealed column is still refused. let patch = crate::methods::dispatch(&handle, "records.update", &json!({"table": "passkey", "id": id, "patch": {"private_key_enc": "v2:forged"}})); assert!(patch.is_err(), "the readonly column refuses an authored patch: {patch:?}");}// RULE: a locked vault writes nothing and says vault_locked, so the mailbox// entry waits; a scalar that does not make the public key is refused.#[test]fn a_locked_vault_or_a_wrong_scalar_writes_nothing() { let (_dir, handle) = phone(); wrapped(&handle); let locked = over(&handle.client(), "passkey.register", ®istered(0x5a, 0xc1)).unwrap_err(); assert_eq!(locked.code, "vault_locked"); let mut wrong = registered(0x5a, 0xc1); wrong["privateScalar"] = json!(b64(&[0x5b; 32])); wrong["privateKey"] = json!(b64(&device_secret())); let refused = over(&handle.client(), "passkey.register", &wrong).unwrap_err(); assert_eq!(refused.code, "bad_request"); assert!(!refused.message.contains(&b64(&[0x5b; 32])), "the refusal never echoes the scalar"); assert_eq!(over(&handle.client(), "passkey.identities", &json!({})).unwrap()["identities"], json!([]));}// RULE: a signature counts a use and the last-used time; the sign count stays// 0; a credential id with no row yet waits as passkey_not_found.#[test]fn a_use_counts_and_the_sign_count_stays_zero() { let (_dir, handle) = phone(); wrapped(&handle); let early = over(&handle.client(), "passkey.used", &json!({"credential_id": b64(&[0xc2; 16]), "used_at": "2026-11-08T10:00:00Z"})).unwrap_err(); assert_eq!(early.code, "passkey_not_found"); let mut asked = registered(0x5a, 0xc2); asked["privateKey"] = json!(b64(&device_secret())); let id = over(&handle.client(), "passkey.register", &asked).unwrap()["id"].as_str().unwrap().to_string(); for _ in 0..2 { over(&handle.client(), "passkey.used", &json!({"credential_id": asked["credential_id"], "used_at": "2026-11-08T10:00:00Z"})).unwrap(); } let stored = row(&handle, &id); assert_eq!(stored["uses"], 2); assert_eq!(stored["last_used_at"], "2026-11-08T10:00:00Z"); assert_eq!(stored["sign_count"], 0);}// RULE: identities list every kept passkey by site, account and ids and// never a key; mirror opens the asked rows' scalars under the vault (a key// made on another device signs here too) and refuses while locked.#[test]fn identities_name_no_key_and_mirror_opens_under_the_vault() { let (_dir, handle) = phone(); wrapped(&handle); let mut asked = registered(0x5a, 0xc3); asked["privateKey"] = json!(b64(&device_secret())); over(&handle.client(), "passkey.register", &asked).unwrap(); let listed = over(&handle.client(), "passkey.identities", &json!({})).unwrap(); let one = &listed["identities"][0]; assert_eq!(one["rp_id"], RP); assert_eq!(one["user_name"], "ada@passkey.example"); assert_eq!(one["credential_id"], asked["credential_id"]); let text = listed.to_string(); assert!(!text.contains("private_key_enc") && !text.contains("v2:"), "{text}"); // A sign-in (Android's provider) is offered the site's passkeys and only those it allows, by the core's rule. let offered = |request: Value| over(&handle.client(), "passkey.identities", &request).unwrap()["identities"].as_array().unwrap().len(); assert_eq!(offered(json!({"rpId": RP})), 1); assert_eq!(offered(json!({"rpId": RP.to_uppercase(), "allow": [asked["credential_id"]]})), 1); assert_eq!(offered(json!({"rpId": RP, "allow": ["AAAA"]})), 0); assert_eq!(offered(json!({"rpId": format!("login.{RP}")})), 0); assert_eq!(over(&handle.client(), "passkey.identities", &json!({"rpId": RP, "allow": "AAAA"})).unwrap_err().code, "bad_request"); let ids = json!({"credentialIds": [asked["credential_id"]]}); assert_eq!(over(&handle.client(), "passkey.mirror", &ids).unwrap_err().code, "vault_locked"); let mut lent = ids.clone(); lent["privateKey"] = json!(b64(&device_secret())); let mirrored = over(&handle.client(), "passkey.mirror", &lent).unwrap(); assert_eq!(mirrored["keys"][0]["privateScalar"], b64(&[0x5a; 32])); assert_eq!(mirrored["keys"][0]["user_handle"], asked["user_handle"]); assert_eq!(mirrored["refused"], json!([]));}/// The core's minimal CXF 1.0 export: two synthetic passkeys and one TOTP.const MINIMAL_CXF: &str = include_str!("../../../cotton-core/tests/fixtures/cxf/minimal.json");// RULE (keys-cxf-phone, 8 Nov 2026): a Credential Exchange export lands each// passkey as register lands one (sealed v2 under the VMK, bound to its row,// sign_count 0, uses 0, created_at the export's or now, note "Imported from// <exporter>"); what the export skipped is said with its title and reason; a// credential id already kept is skipped and said, never a second row.#[test]fn a_cxf_export_lands_each_passkey_sealed_and_skips_what_is_held() { let (_dir, handle) = phone(); wrapped(&handle); let asked = json!({"json": MINIMAL_CXF, "privateKey": b64(&device_secret())}); let answer = over(&handle.client(), "passkey.importCxf", &asked).expect("imported"); assert_eq!(answer["exporter"], "Synthetic Exporter"); let imported = answer["imported"].as_array().unwrap(); assert_eq!(imported.len(), 2, "{answer}"); assert_eq!(imported[0]["rp_id"], "example.com"); assert_eq!(imported[0]["user_name"], "person@example.com"); assert_eq!(imported[1]["rp_id"], "login.example.org"); assert_eq!(answer["skipped"].as_array().unwrap().len(), 1); assert_eq!(answer["skipped"][0]["title"], "Example 2FA"); assert_eq!(answer["unnamed"], json!([])); let first = row(&handle, imported[0]["id"].as_str().unwrap()); assert_eq!(first["rp_name"], "Example"); assert_eq!(first["sign_count"], 0); assert_eq!(first["uses"], 0); assert_eq!(first["vmk_version"], 1); assert_eq!(first["created_at"], "2025-01-01T00:00:00Z"); assert_eq!(first["note"], "Imported from Synthetic Exporter"); let id = first["id"].as_str().unwrap(); let sealed = first["private_key_enc"].as_str().unwrap(); assert!(sealed.starts_with(seal::SEAL_PREFIX), "sealed v2"); assert_eq!(seal::open(&vmk(), id, 1, sealed).unwrap().len(), 32, "bound to this row's id"); let second = row(&handle, imported[1]["id"].as_str().unwrap()); assert_eq!(second["note"], "Imported from Synthetic Exporter\nwork account"); assert!(second["created_at"].as_str().unwrap().starts_with("20"), "now, when the export has none"); // The imported keys mirror out like any other row: they sign on this phone. let ids = json!({"credentialIds": [first["credential_id"]], "privateKey": b64(&device_secret())}); assert_eq!(over(&handle.client(), "passkey.mirror", &ids).unwrap()["keys"].as_array().unwrap().len(), 1); let again = over(&handle.client(), "passkey.importCxf", &asked).expect("imported twice"); assert_eq!(again["imported"], json!([])); let skipped = again["skipped"].as_array().unwrap(); assert_eq!(skipped.len(), 3, "{again}"); assert_eq!(skipped[1], json!({"title": "Example", "reason": "this passkey is already kept here"})); assert_eq!(over(&handle.client(), "passkey.identities", &json!({})).unwrap()["identities"].as_array().unwrap().len(), 2);}// RULE: a locked vault refuses the whole export and writes nothing; an// export that does not read refuses in its own words.#[test]fn a_cxf_import_while_locked_or_unreadable_writes_nothing() { let (_dir, handle) = phone(); wrapped(&handle); let locked = over(&handle.client(), "passkey.importCxf", &json!({"json": MINIMAL_CXF})).unwrap_err(); assert_eq!(locked.code, "vault_locked"); assert_eq!(over(&handle.client(), "passkey.identities", &json!({})).unwrap()["identities"], json!([])); let broken = over(&handle.client(), "passkey.importCxf", &json!({"json": "{\"version\": 0}", "privateKey": b64(&device_secret())})).unwrap_err(); assert_eq!(broken.code, "bad_export"); assert!(broken.message.contains("working draft"), "{}", broken.message);}#[test]fn every_passkey_method_is_a_phone_method() { for method in super::METHODS { assert!(crate::methods::CLIENT_METHODS.contains(&method), "{method}"); assert!(crate::methods::ALL_METHODS.contains(&method), "{method}"); }}// RULE (Android's provider, 16 Nov 2026): a passkey Android's provider asks// for is made in the core, its private half sealed v2 under the VMK and bound// to the row (the object never reads it, and no scalar is answered); its// attestation carries the key the row names; a sign-in opens the row here and// signs what a site verifies with the public key it was handed, at counter 0,// and counts a use.#[test]fn android_creates_a_sealed_passkey_and_signs_in_with_it() { use p256::ecdsa::signature::Verifier as _; use p256::pkcs8::DecodePublicKey as _; let (_dir, handle) = phone(); wrapped(&handle); let user = b64(b"synthetic-user-7"); let created = over( &handle.client(), "passkey.create", &json!({"rp_id": RP, "rp_name": "Passkey Example", "user_name": "ada@passkey.example", "user_handle": user, "clientDataHash": b64(&[7u8; 32]), "privateKey": b64(&device_secret())}), ) .expect("created"); let id = created["id"].as_str().unwrap().to_string(); let credential = created["credential_id"].as_str().unwrap().to_string(); assert_eq!(created["algorithm"], -7); let answered = created.to_string(); assert!(!answered.contains("privateScalar") && !answered.contains("private_key"), "no private half is answered: {answered}"); let stored = row(&handle, &id); assert_eq!(stored["rp_id"], RP); assert_eq!(stored["credential_id"], credential.as_str()); assert_eq!(stored["vmk_version"], 1); let sealed = stored["private_key_enc"].as_str().unwrap(); assert!(sealed.starts_with(seal::SEAL_PREFIX), "sealed v2"); assert_eq!(seal::open(&vmk(), &id, 1, sealed).unwrap().len(), 32, "the private half opens only under the VMK"); // The attestation's authData names the credential and is over this site. let auth = URL_SAFE_NO_PAD.decode(created["authenticator_data"].as_str().unwrap()).unwrap(); use sha2::Digest as _; assert_eq!(&auth[..32], sha2::Sha256::digest(RP.as_bytes()).as_slice(), "rpIdHash"); assert_eq!(auth[32] & 0x45, 0x45, "UP, UV and AT"); let id_len = u16::from_be_bytes([auth[53], auth[54]]) as usize; assert_eq!(b64(&auth[55..55 + id_len]), credential); let spki = URL_SAFE_NO_PAD.decode(created["public_key"].as_str().unwrap()).unwrap(); let site_key = p256::ecdsa::VerifyingKey::from_public_key_der(&spki).expect("an SPKI the site reads"); // Sign-in: the site's challenge hash, signed by the sealed key. let hash = [9u8; 32]; let signed = over( &handle.client(), "passkey.sign", &json!({"credential_id": credential, "rp_id": RP, "clientDataHash": b64(&hash), "used_at": "2026-11-16T10:00:00Z", "privateKey": b64(&device_secret())}), ) .expect("signed"); assert_eq!(signed["user_handle"], user.as_str()); assert_eq!(signed["user_name"], "ada@passkey.example"); let data = URL_SAFE_NO_PAD.decode(signed["authenticator_data"].as_str().unwrap()).unwrap(); assert_eq!(&data[33..37], &[0, 0, 0, 0], "counter 0"); let mut message = data.clone(); message.extend_from_slice(&hash); let signature = p256::ecdsa::Signature::from_der(&URL_SAFE_NO_PAD.decode(signed["signature"].as_str().unwrap()).unwrap()).unwrap(); site_key.verify(&message, &signature).expect("the site verifies the sign-in"); let stored = row(&handle, &id); assert_eq!(stored["uses"], 1); assert_eq!(stored["last_used_at"], "2026-11-16T10:00:00Z");}// RULE: a locked vault makes nothing; an excluded credential already kept// refuses already_kept; a sign-in for an unknown id or with no key refuses.#[test]fn android_create_and_sign_refuse_without_the_vault_or_a_row() { let (_dir, handle) = phone(); wrapped(&handle); let asked = json!({"rp_id": RP, "user_handle": b64(b"u"), "clientDataHash": b64(&[1u8; 32])}); assert_eq!(over(&handle.client(), "passkey.create", &asked).unwrap_err().code, "vault_locked"); assert_eq!(over(&handle.client(), "passkey.identities", &json!({})).unwrap()["identities"], json!([])); let mut opened = asked.clone(); opened["privateKey"] = json!(b64(&device_secret())); let credential = over(&handle.client(), "passkey.create", &opened).unwrap()["credential_id"].clone(); let mut again = opened.clone(); again["exclude"] = json!([credential]); assert_eq!(over(&handle.client(), "passkey.create", &again).unwrap_err().code, "already_kept"); let mut short = opened.clone(); short["clientDataHash"] = json!(b64(&[1u8; 8])); assert_eq!(over(&handle.client(), "passkey.create", &short).unwrap_err().code, "bad_request"); let sign = json!({"credential_id": credential, "rp_id": RP, "clientDataHash": b64(&[2u8; 32])}); assert_eq!(over(&handle.client(), "passkey.sign", &sign).unwrap_err().code, "vault_locked"); let unknown = json!({"credential_id": b64(&[3u8; 16]), "rp_id": RP, "clientDataHash": b64(&[2u8; 32]), "privateKey": b64(&device_secret())}); assert_eq!(over(&handle.client(), "passkey.sign", &unknown).unwrap_err().code, "passkey_not_found");}