Cotton code
384 lines · 14.7 KB · RustRaw
//! WhatsApp's passkey step, answered from a Cotton Keys row: no browser.//!//! ```text//! WhatsApp's options ─┬─ vault open, a passkey row for rpId among allowCredentials//!                     │     open private_key_enc under the VMK, build clientDataJSON,//!                     │     sign authData(rpIdHash, UP|UV, counter 0)      → the assertion//!                     │     write last_used_at, uses on the row (sign_count stays 0)//!                     └─ otherwise (vault locked / no row / row refused)//!                           Chrome, as before, the reason in the log and on the card//! ```//!//! The answer is byte for byte the shape the Chrome page script answers//! (`whatsapp_passkey::ASSERT_JS`, read by the helper as whatsmeow's//! `types.WebAuthnResponse`): `id`, `rawId`, `type`, `response {//! clientDataJSON, authenticatorData, signature, userHandle }`, base64url with//! no padding. Signing is `cotton_core::keys::passkey::assert`; nothing here//! writes WebAuthn of its own beyond clientDataJSON.//!//! Compiles everywhere: the VMK comes in as an [`OpenVault`], the rows through//! [`PasskeyRows`]. Only [`ImporterKeys`] touches the Keychain, through the//! [`Keyring`] it is handed. No key, credential id or user handle is ever//! logged; the log line names the path taken and the reason.use std::io::Write as _;use std::path::PathBuf;use std::sync::{Arc, Mutex};use base64::engine::general_purpose::URL_SAFE_NO_PAD;use base64::Engine as _;use cotton_core::keys::passkey::assert;use serde_json::{json, Map, Value};use sha2::{Digest, Sha256};use crate::object::{Act, ObjectClient, ObjectError};use crate::vault::{ImporterVault, Keyring, OpenVault};use crate::whatsapp_passkey::{PasskeyBrowser, ORIGIN};/// The object table Cotton Keys keeps passkeys in.pub const PASSKEY_TABLE: &str = "passkey";/// What the card says once the vault signed.pub const SIGNED_BY_KEYS: &str = "Signed by Cotton Vault on this Mac.";/// A `passkey` row: its id and its data.pub type Row = (String, Map<String, Value>);/// The object's passkey rows, as the signer reads and writes them.pub trait PasskeyRows: Send + Sync {    /// Every `passkey` row for `rp_id`, with its id.    fn passkeys(&self, rp_id: &str) -> Result<Vec<Row>, ObjectError>;    /// A use: `sign_count`, `last_used_at` and `uses`, merged into the row.    fn record_use(&self, id: &str, patch: &Value) -> Result<(), ObjectError>;}impl PasskeyRows for ObjectClient {    fn passkeys(&self, rp_id: &str) -> Result<Vec<Row>, ObjectError> {        // A device reads its passkey rows over sync and opens them here: the table is sealed, rp_id with it.        if let Some(rows) = self.device_rows(PASSKEY_TABLE) {            return Ok(rows?                .into_iter()                .filter_map(|row| Some((row.get("id")?.as_str()?.to_string(), row.get("data")?.as_object()?.clone())))                .filter(|(_, data)| data.get("rp_id").and_then(Value::as_str) == Some(rp_id) && data.get("trashed_at").is_none_or(Value::is_null))                .collect());        }        let page = self.tool(            "list_records",            &json!({ "table": PASSKEY_TABLE, "where": { "rp_id": rp_id }, "limit": 100 }),        )?;        Ok(page            .get("records")            .and_then(Value::as_array)            .map(|records| {                records                    .iter()                    .filter_map(|record| {                        Some((record.get("id")?.as_str()?.to_string(), record.get("data")?.as_object()?.clone()))                    })                    .collect()            })            .unwrap_or_default())    }    fn record_use(&self, id: &str, patch: &Value) -> Result<(), ObjectError> {        self.act(Act::Update, PASSKEY_TABLE, id, patch).map(|_| ())    }}/// Why the vault did not answer: the reason the Chrome path is taken.#[derive(Debug, Clone, PartialEq, Eq)]pub enum Declined {    /// The vault is not open on this Mac (no key, not approved, no object).    Locked(String),    /// No passkey row answers WhatsApp's request.    NoRow(String),    /// A row was found and refused (does not open, bad options, a write refused).    Refused(String),}impl Declined {    /// The log's and card's words: `vault locked: …`, `no row: …`, `row refused: …`.    pub fn sentence(&self) -> String {        match self {            Declined::Locked(why) => format!("vault locked: {why}"),            Declined::NoRow(why) => format!("no row: {why}"),            Declined::Refused(why) => format!("row refused: {why}"),        }    }}/// A signed assertion and the write it owes its row.#[derive(Debug, Clone, PartialEq)]pub struct Signed {    /// The assertion, in the page script's shape.    pub response: Value,    /// The row that signed.    pub row_id: String,    /// `sign_count`, `last_used_at`, `uses`, as the row now stands.    pub patch: Value,}/// base64url (padded or not, or plain base64) back to bytes.fn bytes_of(text: &str) -> Option<Vec<u8>> {    let text = text.trim_end_matches('=').replace('+', "-").replace('/', "_");    URL_SAFE_NO_PAD.decode(text).ok()}/// A number column as a whole count; absent or null is 0.fn count(row: &Map<String, Value>, key: &str) -> u64 {    row.get(key)        .and_then(|n| n.as_u64().or_else(|| n.as_f64().filter(|n| *n >= 0.0).map(|n| n as u64)))        .unwrap_or(0)}/// The clientDataJSON a browser at [`ORIGIN`] writes for a `get`: its member/// order (type, challenge, origin, crossOrigin) is the browser's.pub fn client_data_json(challenge: &[u8]) -> String {    format!(        r#"{{"type":"webauthn.get","challenge":"{}","origin":"{ORIGIN}","crossOrigin":false}}"#,        URL_SAFE_NO_PAD.encode(challenge)    )}/// The row that answers `options` among `rows`: the one whose credential is/// in `allowCredentials`, or the only row for the rpId when it lists none.fn choose<'a>(    rows: &'a [Row],    rp_id: &str,    options: &Value,) -> Result<&'a Row, Declined> {    let for_rp: Vec<_> = rows        .iter()        .filter(|(_, row)| row.get("rp_id").and_then(Value::as_str) == Some(rp_id))        .collect();    let allowed: Vec<Vec<u8>> = options        .get("allowCredentials")        .and_then(Value::as_array)        .map(|list| {            list.iter()                .filter_map(|c| c.get("id").and_then(Value::as_str).and_then(bytes_of))                .collect()        })        .unwrap_or_default();    if allowed.is_empty() {        return match for_rp.as_slice() {            [one] => Ok(one),            [] => Err(Declined::NoRow(format!("Cotton Vault holds no passkey for {rp_id}"))),            many => Err(Declined::NoRow(format!(                "Cotton Vault holds {} passkeys for {rp_id} and WhatsApp named none of them",                many.len()            ))),        };    }    for_rp        .into_iter()        .find(|(_, row)| {            row.get("credential_id")                .and_then(Value::as_str)                .and_then(bytes_of)                .is_some_and(|id| allowed.contains(&id))        })        .ok_or_else(|| {            Declined::NoRow(format!(                "none of the {} credentials WhatsApp allows is a Cotton Vault passkey for {rp_id}",                allowed.len()            ))        })}/// Answer WhatsApp's `options` from `rows`, opened under `vault`, on `today`/// (`YYYY-MM-DD`, the `last_used_at` written). Pure: the write is the caller's.pub fn sign(    vault: &OpenVault,    rows: &[Row],    options: &Value,    today: &str,) -> Result<Signed, Declined> {    let rp_id = options        .get("rpId")        .and_then(Value::as_str)        .filter(|rp| !rp.is_empty())        .ok_or_else(|| Declined::Refused("WhatsApp's request names no rpId".to_string()))?;    let challenge = options        .get("challenge")        .and_then(Value::as_str)        .and_then(bytes_of)        .filter(|c| !c.is_empty())        .ok_or_else(|| Declined::Refused("WhatsApp's challenge is not base64url".to_string()))?;    let (row_id, row) = choose(rows, rp_id, options)?;    let passkey = vault        .passkey(row_id, row)        .map_err(|e| Declined::Refused(e.to_string()))?;    // ALWAYS 0, on the phone and on the Mac, as iCloud Keychain passkeys do:    // several devices sign for one row, and a counter each kept would diverge    // (WebAuthn lets an authenticator without a counter send 0; RPs accept it).    let counter = 0;    let client_data = client_data_json(&challenge);    let hash = Sha256::digest(client_data.as_bytes());    let signed = assert(&passkey, rp_id, &hash, counter).map_err(|e| Declined::Refused(e.to_string()))?;    let id = URL_SAFE_NO_PAD.encode(&signed.credential_id);    let user_handle = bytes_of(&signed.user_handle).map(|b| URL_SAFE_NO_PAD.encode(b));    let response = json!({        "id": id,        "rawId": id,        "type": "public-key",        "response": {            "clientDataJSON": URL_SAFE_NO_PAD.encode(client_data.as_bytes()),            "authenticatorData": URL_SAFE_NO_PAD.encode(&signed.authenticator_data),            "signature": URL_SAFE_NO_PAD.encode(&signed.signature),            "userHandle": user_handle,        },    });    let patch = json!({        "last_used_at": today,        "uses": count(row, "uses") + 1,    });    Ok(Signed { response, row_id: row_id.clone(), patch })}/// The vault and the rows, opened for one assertion.pub struct Opened {    pub vault: OpenVault,    pub rows: Arc<dyn PasskeyRows>,}/// Where the signer opens the vault for one ask. The Mac's is [`ImporterKeys`].pub trait Keys: Send + Sync {    /// The vault open now, or why not.    fn open(&self) -> Result<Opened, Declined>;    /// The importer's current object client, handed in as it changes (sign-in).    fn see_object(&self, _object: &ObjectClient) {}}/// This Mac's vault key (its keyring) over the importer's object: opened for/// one assertion with [`ImporterVault::open_only`], never minted or published here.pub struct ImporterKeys {    keyring: Box<dyn Keyring>,    device_id: String,    device_name: String,    object: Mutex<Option<ObjectClient>>,}impl ImporterKeys {    pub fn new(keyring: Box<dyn Keyring>, device_id: impl Into<String>, device_name: impl Into<String>) -> ImporterKeys {        ImporterKeys {            keyring,            device_id: device_id.into(),            device_name: device_name.into(),            object: Mutex::new(None),        }    }}impl Keys for ImporterKeys {    fn open(&self) -> Result<Opened, Declined> {        let object = self            .object            .lock()            .unwrap_or_else(|p| p.into_inner())            .clone()            .filter(ObjectClient::signed_in)            .ok_or_else(|| Declined::Locked("the importer is not signed in to the object".to_string()))?;        let vault = ImporterVault::new(self.keyring.as_ref(), &self.device_id, &self.device_name)            .open_only(&object)            .map_err(|e| Declined::Locked(e.to_string()))?            .ok_or_else(|| {                Declined::Locked("this Mac is not approved yet (Keys › Devices on the phone)".to_string())            })?;        Ok(Opened { vault, rows: Arc::new(object) })    }    fn see_object(&self, object: &ObjectClient) {        *self.object.lock().unwrap_or_else(|p| p.into_inner()) = Some(object.clone());    }}/// The signer the WhatsApp importer asks: Cotton Keys first, Chrome when the/// vault cannot answer, the path taken in the log and on the card.pub struct VaultPasskey {    keys: Arc<dyn Keys>,    chrome: Arc<dyn PasskeyBrowser>,    /// `<data dir>/whatsapp-link/passkey.log`; `None` writes no log.    log: Option<PathBuf>,    /// The pairing last answered and the card's words for who answered.    answered: Mutex<Option<(String, String)>>,}impl VaultPasskey {    pub fn new(keys: Arc<dyn Keys>, chrome: Arc<dyn PasskeyBrowser>, log: Option<PathBuf>) -> VaultPasskey {        VaultPasskey { keys, chrome, log, answered: Mutex::new(None) }    }    /// The vault's answer, its row written, or why the vault did not answer.    pub fn sign_from_vault(&self, options: &Value) -> Result<Value, Declined> {        let opened = self.keys.open()?;        let rp_id = options.get("rpId").and_then(Value::as_str).unwrap_or_default();        let rows = opened            .rows            .passkeys(rp_id)            .map_err(|e| Declined::Locked(format!("the object did not list passkeys: {e}")))?;        let today = chrono::Utc::now().format("%Y-%m-%d").to_string();        let signed = sign(&opened.vault, &rows, options, &today)?;        // The use is written before the answer leaves: a counter WhatsApp saw        // that the row does not hold would make the next one look cloned.        opened            .rows            .record_use(&signed.row_id, &signed.patch)            .map_err(|e| Declined::Refused(format!("the use was not written: {e}")))?;        Ok(signed.response)    }    fn say(&self, pairing: &str, line: &str, card: String) {        *self.answered.lock().unwrap_or_else(|p| p.into_inner()) = Some((pairing.to_string(), card));        let Some(path) = &self.log else { return };        if let Some(dir) = path.parent() {            let _ = std::fs::create_dir_all(dir);        }        if let Ok(mut file) = std::fs::OpenOptions::new().create(true).append(true).open(path) {            let at = chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ");            let _ = writeln!(file, "{at} passkey {line}");        }    }}impl PasskeyBrowser for VaultPasskey {    fn assert(&self, pairing: &str, options: &Value) -> Result<Value, String> {        let rp_id = options.get("rpId").and_then(Value::as_str).unwrap_or("?").to_string();        match self.sign_from_vault(options) {            Ok(response) => {                self.say(pairing, &format!("signer=vault rp={rp_id}"), SIGNED_BY_KEYS.to_string());                Ok(response)            }            Err(declined) => {                let why = declined.sentence();                self.say(                    pairing,                    &format!("signer=chrome rp={rp_id} reason=\"{why}\""),                    format!("Given in Chrome ({why})."),                );                self.chrome.assert(pairing, options)            }        }    }    fn close(&self, pairing: &str) {        self.chrome.close(pairing);    }    fn answered_by(&self, pairing: &str) -> Option<String> {        self.answered            .lock()            .unwrap_or_else(|p| p.into_inner())            .as_ref()            .filter(|(held, _)| held == pairing)            .map(|(_, said)| said.clone())    }    fn see_object(&self, object: &ObjectClient) {        self.keys.see_object(object);    }}#[cfg(test)]#[path = "vault_passkey_tests.rs"]mod tests;