273 lines · 11.3 KB · RustRaw
//! The vault signer over synthetic keys: a passkey row sealed under a//! synthetic VMK answers WhatsApp-shaped options in the Chrome page script's//! shape, the signature verifies, the row's use is written; every way the//! vault cannot answer goes to Chrome and says why.use std::sync::{Arc, Mutex};use base64::engine::general_purpose::URL_SAFE_NO_PAD;use cotton_core::keys::passkey::{cose_public_key, make_from, Algorithm, FLAG_UP, FLAG_UV};use cotton_core::keys::passkey_row;use cotton_core::vault::Vmk;use p256::ecdsa::signature::Verifier as _;use p256::ecdsa::Signature;use serde_json::{json, Map, Value};use sha2::{Digest, Sha256};use zeroize::Zeroizing;use super::*;use crate::object::ObjectError;use crate::vault::OpenVault;use crate::whatsapp_passkey::{PasskeyBrowser, ORIGIN};const ROW: &str = "passkey-wa-1";const RP: &str = "whatsapp.com";const CREDENTIAL: [u8; 16] = [7u8; 16];fn vmk() -> Vmk { Vmk::from_bytes([26u8; 32])}fn vault() -> OpenVault { OpenVault::from_vmk(vmk(), 1)}/// A synthetic WhatsApp passkey row, sealed under the synthetic VMK, used/// four times before.fn row() -> Map<String, Value> { let passkey = make_from(RP, &URL_SAFE_NO_PAD.encode(b"synthetic-user"), Algorithm::Es256, CREDENTIAL, Zeroizing::new([9u8; 32])).unwrap(); let mut columns = passkey_row::seal(&passkey, &vmk(), ROW, 1).unwrap().columns(); columns.insert("sign_count".into(), json!(4)); columns.insert("uses".into(), json!(4)); columns.insert("rp_name".into(), json!("WhatsApp")); columns}fn credential() -> String { URL_SAFE_NO_PAD.encode(CREDENTIAL)}/// WhatsApp's request, as the helper's `pair_status` hands it on.fn options(allow: &[String]) -> Value { json!({ "challenge": URL_SAFE_NO_PAD.encode([3u8; 32]), "timeout": 60000, "rpId": RP, "allowCredentials": allow.iter().map(|id| json!({ "id": id, "type": "public-key", "transports": ["internal", "hybrid"] })).collect::<Vec<_>>(), "userVerification": "required", "extensions": null })}/// What the Chrome page script answered in a run (synthetic bytes): the shape/// the helper reads as whatsmeow's `types.WebAuthnResponse`.fn chrome_answer() -> Value { json!({ "id": "Y3JlZGVudGlhbC1pZA", "rawId": "Y3JlZGVudGlhbC1pZA", "type": "public-key", "response": { "clientDataJSON": "eyJ0eXBlIjoid2ViYXV0aG4uZ2V0In0", "authenticatorData": "YXV0aA", "signature": "c2ln", "userHandle": "dXNlcg" } })}/// The JSON's shape: every key, nested, with its value's kind.fn shape(value: &Value) -> Value { match value { Value::Object(map) => Value::Object(map.iter().map(|(k, v)| (k.clone(), shape(v))).collect()), Value::String(_) => json!("string"), Value::Null => json!("null"), other => json!(format!("{other:?}")), }}fn b64(value: &Value) -> Vec<u8> { let text = value.as_str().unwrap(); assert!(!text.contains('=') && !text.contains('+') && !text.contains('/'), "{text} is not base64url"); URL_SAFE_NO_PAD.decode(text).unwrap()}// RULE: the vault signer answers WhatsApp's options in exactly the shape the// Chrome page script answers, over clientDataJSON for web.whatsapp.com and// authData for whatsapp.com with UP|UV and counter 0 (never counted, so devices// signing for one row never diverge), and the// signature verifies under the row's own public key (7 Nov 2026: Cotton Keys// signs WhatsApp's linked-device passkey without Chrome).#[test]fn a_vault_passkey_row_answers_whatsapp_in_chromes_shape() { let rows = vec![(ROW.to_string(), row())]; let signed = sign(&vault(), &rows, &options(&[credential()]), "2026-11-07").unwrap(); let answer = &signed.response; assert_eq!(shape(answer), shape(&chrome_answer()), "the answer's shape is the page script's"); assert_eq!(answer["id"], credential()); assert_eq!(answer["rawId"], credential()); assert_eq!(answer["type"], "public-key"); assert_eq!(b64(&answer["response"]["userHandle"]), b"synthetic-user"); let client_data = b64(&answer["response"]["clientDataJSON"]); assert_eq!( String::from_utf8(client_data.clone()).unwrap(), format!(r#"{{"type":"webauthn.get","challenge":"{}","origin":"https://web.whatsapp.com","crossOrigin":false}}"#, URL_SAFE_NO_PAD.encode([3u8; 32])) ); assert_eq!(ORIGIN, "https://web.whatsapp.com"); let auth = b64(&answer["response"]["authenticatorData"]); assert_eq!(auth.len(), 37); assert_eq!(&auth[..32], Sha256::digest(RP.as_bytes()).as_slice(), "rpIdHash is whatsapp.com's"); assert_eq!(auth[32], FLAG_UP | FLAG_UV, "flags are UP|UV"); assert_eq!(u32::from_be_bytes(auth[33..37].try_into().unwrap()), 0, "the counter is always 0"); let key = cose_public_key(row()["public_key"].as_str().unwrap()).unwrap(); let mut message = auth.clone(); message.extend_from_slice(&Sha256::digest(&client_data)); let signature = Signature::from_der(&b64(&answer["response"]["signature"])).unwrap(); key.verify(&message, &signature).expect("the signature verifies under the row's public key"); assert_eq!(signed.row_id, ROW); assert_eq!(signed.patch, json!({ "last_used_at": "2026-11-07", "uses": 5 }));}#[test]fn with_no_allowed_credentials_the_one_row_for_the_rp_answers() { let rows = vec![(ROW.to_string(), row())]; let signed = sign(&vault(), &rows, &options(&[]), "2026-11-07").unwrap(); assert_eq!(signed.response["id"], credential()); let mut other = row(); other.insert("rp_id".into(), json!("example.com")); // A row for another site is not WhatsApp's. assert!(matches!( sign(&vault(), &[("passkey-other".to_string(), other)], &options(&[]), "2026-11-07"), Err(Declined::NoRow(_)) ));}/// The object's passkey rows in memory, with the writes it was sent.#[derive(Default)]struct Rows { rows: Mutex<Vec<Row>>, writes: Mutex<Vec<(String, Value)>>,}impl PasskeyRows for Rows { fn passkeys(&self, rp_id: &str) -> Result<Vec<Row>, ObjectError> { Ok(self.rows.lock().unwrap().iter().filter(|(_, r)| r["rp_id"] == rp_id).cloned().collect()) } fn record_use(&self, id: &str, patch: &Value) -> Result<(), ObjectError> { self.writes.lock().unwrap().push((id.to_string(), patch.clone())); let mut rows = self.rows.lock().unwrap(); let (_, row) = rows.iter_mut().find(|(held, _)| held == id).unwrap(); for (k, v) in patch.as_object().unwrap() { row.insert(k.clone(), v.clone()); } Ok(()) }}/// The vault as a test opens it: open over `rows`, or locked.struct FakeKeys { rows: Arc<Rows>, locked: bool, vmk: [u8; 32],}impl Keys for FakeKeys { fn open(&self) -> Result<Opened, Declined> { if self.locked { return Err(Declined::Locked("this Mac is not approved yet (Keys › Devices on the phone)".to_string())); } Ok(Opened { vault: OpenVault::from_vmk(Vmk::from_bytes(self.vmk), 1), rows: self.rows.clone() }) }}#[derive(Default)]struct FakeChrome { asked: Mutex<Vec<String>>,}impl PasskeyBrowser for FakeChrome { fn assert(&self, pairing: &str, _options: &Value) -> Result<Value, String> { self.asked.lock().unwrap().push(pairing.to_string()); Ok(chrome_answer()) } fn close(&self, _pairing: &str) {}}fn signer(locked: bool, vmk: [u8; 32], dir: &std::path::Path) -> (VaultPasskey, Arc<Rows>, Arc<FakeChrome>) { let rows = Arc::new(Rows::default()); rows.rows.lock().unwrap().push((ROW.to_string(), row())); let chrome = Arc::new(FakeChrome::default()); let keys = Arc::new(FakeKeys { rows: rows.clone(), locked, vmk }); (VaultPasskey::new(keys, chrome.clone(), Some(dir.join("passkey.log"))), rows, chrome)}fn log(dir: &std::path::Path) -> String { std::fs::read_to_string(dir.join("passkey.log")).unwrap()}// RULE: with the vault open and a row for the rpId, the vault answers, its// use is written to the row as the object takes it, Chrome is never opened,// and the log and card name the vault; no credential id reaches the log.#[test]fn an_open_vault_signs_writes_the_use_and_says_so() { let dir = tempfile::tempdir().unwrap(); let (signer, rows, chrome) = signer(false, [26u8; 32], dir.path()); let first = signer.assert("p1", &options(&[credential()])).unwrap(); assert_eq!(first["id"], credential()); assert!(chrome.asked.lock().unwrap().is_empty(), "Chrome was not asked"); assert_eq!(signer.answered_by("p1").as_deref(), Some(SIGNED_BY_KEYS)); assert_eq!(signer.answered_by("p2"), None); let writes = rows.writes.lock().unwrap().clone(); assert_eq!(writes.len(), 1); assert_eq!(writes[0].0, ROW); let patch = writes[0].1.as_object().unwrap(); let mut keys: Vec<_> = patch.keys().cloned().collect(); keys.sort(); assert_eq!(keys, ["last_used_at", "uses"], "sign_count is never written: it stays 0"); assert_eq!(patch["uses"], 5); // The next assertion signs at 0 again; uses counts on from the written row. let second = signer.assert("p1", &options(&[credential()])).unwrap(); let auth = URL_SAFE_NO_PAD.decode(second["response"]["authenticatorData"].as_str().unwrap()).unwrap(); assert_eq!(u32::from_be_bytes(auth[33..37].try_into().unwrap()), 0); assert_eq!(rows.writes.lock().unwrap()[1].1["uses"], 6); let said = log(dir.path()); assert!(said.contains("passkey signer=vault rp=whatsapp.com"), "{said}"); assert!(!said.contains(&credential()) && !said.contains("synthetic"), "the log names no credential: {said}");}// RULE: a locked vault answers by Chrome, saying so (no silent fallback).#[test]fn a_locked_vault_answers_by_chrome_and_says_why() { let dir = tempfile::tempdir().unwrap(); let (signer, rows, chrome) = signer(true, [26u8; 32], dir.path()); assert_eq!(signer.assert("p1", &options(&[credential()])).unwrap(), chrome_answer()); assert_eq!(chrome.asked.lock().unwrap().clone(), ["p1"]); assert!(rows.writes.lock().unwrap().is_empty()); assert!(signer.answered_by("p1").unwrap().starts_with("Given in Chrome (vault locked: ")); assert!(log(dir.path()).contains("signer=chrome rp=whatsapp.com reason=\"vault locked: "));}// RULE: allowCredentials naming no Cotton Keys row answers by Chrome, the// reason said.#[test]fn allowed_credentials_naming_no_row_answer_by_chrome_with_the_reason() { let dir = tempfile::tempdir().unwrap(); let (signer, rows, chrome) = signer(false, [26u8; 32], dir.path()); let elsewhere = URL_SAFE_NO_PAD.encode([8u8; 16]); assert_eq!(signer.assert("p1", &options(&[elsewhere])).unwrap(), chrome_answer()); assert_eq!(chrome.asked.lock().unwrap().len(), 1); assert!(rows.writes.lock().unwrap().is_empty()); assert_eq!( signer.answered_by("p1").unwrap(), "Given in Chrome (no row: none of the 1 credentials WhatsApp allows is a Cotton Vault passkey for whatsapp.com)." );}// RULE: a row that does not open under the vault's key answers by Chrome as// "row refused", and nothing is written to it.#[test]fn a_row_that_does_not_open_answers_by_chrome_as_refused() { let dir = tempfile::tempdir().unwrap(); let (signer, rows, chrome) = signer(false, [27u8; 32], dir.path()); signer.assert("p1", &options(&[credential()])).unwrap(); assert_eq!(chrome.asked.lock().unwrap().len(), 1); assert!(rows.writes.lock().unwrap().is_empty()); assert!(signer.answered_by("p1").unwrap().starts_with("Given in Chrome (row refused: "));}