Cotton code
204 lines · 9.9 KB · RustRaw
//! This Mac approved from the person's phone (src/approval.rs) against a fake//! open host that checks what the Worker checks (apps/business/src/approval.ts)://! the ask names the Mac's device key and vault key with a commit, the reveal//! hashes to that commit, the code is the one both screens work out, and the//! claim is the device key's signature over the challenge. A credential kept//! from before the Mac had its device key signs it out with words.mod support;use std::sync::{Arc, Mutex};use base64::engine::general_purpose::URL_SAFE_NO_PAD;use base64::Engine as _;use cotton_core::vault::approval::{claim_statement, commit_of, sas_of, shown_code};use cotton_mac::app::{App, Config, NOTE_NEW_IDENTITY};use cotton_mac::approval::DeviceKey;use cotton_mac::vault::MemoryKeyring;use ed25519_dalek::{Signature, Verifier as _, VerifyingKey};use serde_json::{json, Value};use support::{Answer, TestServer};const DB: &str = "00000000-0000-4000-8000-000000000001";const PHONE: &str = "+15550190001";#[derive(Default)]struct Ask {    device_id: String,    vault_key: Option<String>,    commit: String,    polls: usize,    revealed: Option<String>,    claimed: bool,}const NONCE_B: [u8; 32] = [55u8; 32];fn bytes32(text: &str) -> [u8; 32] {    URL_SAFE_NO_PAD.decode(text).unwrap().try_into().unwrap()}fn host(ask: Arc<Mutex<Ask>>) -> TestServer {    TestServer::start(move |request| {        let mut held = ask.lock().unwrap();        match request.path.split('?').next().unwrap_or("") {            "/v1/approval/ask" => {                let body = request.json();                assert_eq!(body["phone"], PHONE);                held.device_id = body["device_id"].as_str().unwrap().to_string();                held.vault_key = body["vault_key"].as_str().map(str::to_string);                held.commit = body["commit"].as_str().unwrap().to_string();                assert_eq!(body["device_name"], "Test Mac");                assert_eq!(body["device_kind"], "mac", "the phone's card says Your Mac");                Answer::json(200, json!({ "ask_id": "ask_0123456789abcdef", "expires_in": 180, "poll_seconds": 3 }))            }            "/v1/approval/poll" => {                held.polls += 1;                match held.polls {                    1 => Answer::json(200, json!({ "state": "waiting" })),                    2 | 3 => Answer::json(200, json!({ "state": "waiting", "nonce_b": URL_SAFE_NO_PAD.encode(NONCE_B) })),                    _ => Answer::json(200, json!({ "state": "approved", "challenge": "chal-1" })),                }            }            "/v1/approval/reveal" => {                let nonce = request.json()["nonce"].as_str().unwrap().to_string();                let vault = held.vault_key.as_deref().map(bytes32);                let commit = commit_of(&bytes32(&held.device_id), vault.as_ref().map(|k| k.as_slice()), &bytes32(&nonce));                assert_eq!(URL_SAFE_NO_PAD.encode(commit), held.commit, "the reveal hashes to the ask's commit");                assert!(held.revealed.is_none(), "revealed once");                held.revealed = Some(nonce);                Answer::json(200, json!({ "ok": true }))            }            "/v1/approval/claim" => {                let sig: [u8; 64] = URL_SAFE_NO_PAD.decode(request.json()["sig"].as_str().unwrap()).unwrap().try_into().unwrap();                let key = VerifyingKey::from_bytes(&bytes32(&held.device_id)).unwrap();                key.verify(claim_statement("ask_0123456789abcdef", "chal-1").as_bytes(), &Signature::from_bytes(&sig)).expect("the claim is the device key's signature");                held.claimed = true;                Answer::json(200, json!({ "credential": format!("ctd_{DB}_approved"), "database_id": DB, "person": { "phone": PHONE }, "expires_in": 100 }))            }            _ => Answer::json(404, json!({ "code": "not_found", "message": request.path })),        }    })}fn open(server: &TestServer, dir: &std::path::Path, device: Option<DeviceKey>) -> App {    let config = Config {        data_dir: dir.to_path_buf(),        object_url: server.url.clone(),        device_id: "install-uuid".into(),        machine: "test".into(),        device_name: "Test Mac".into(),        app_version: "0.0.0".into(),        home: dir.to_path_buf(),        helpers_dir: None,    };    App::open_as(config, Vec::new(), Box::new(MemoryKeyring::default()), device).unwrap()}#[test]fn the_mac_is_approved_from_a_phone_by_the_code_it_shows_and_claims_with_its_device_key() {    let ask = Arc::new(Mutex::new(Ask::default()));    let server = host(Arc::clone(&ask));    let dir = tempfile::tempdir().unwrap();    let device = DeviceKey::from_seed(&[9u8; 32]);    let device_id = device.id();    let app = open(&server, dir.path(), Some(device));    assert_eq!(app.config().device_id, device_id, "the device key's public half is this Mac's device id");    assert_eq!(app.call("status", &json!({}))["askButton"], "Show a code to scan");    let asked = app.call("askApproval", &json!({ "phone": PHONE }));    assert_eq!(asked["ok"], true, "{asked}");    assert_eq!(asked["state"], "waiting");    assert!(asked["code"].is_null(), "no digits until the phone opens the ask");    {        let held = ask.lock().unwrap();        assert_eq!(held.device_id, device_id);        assert!(held.vault_key.is_some(), "the ask names this Mac's vault key, so the phone lets it in at once");    }    // Nobody opened it yet: no code.    let first = app.call("askPoll", &json!({}));    assert_eq!(first["state"], "waiting");    assert!(first["code"].is_null(), "{first}");    assert_eq!(first["line"], "Open any Cotton app on another device that has your things, and scan the code on this Mac.");    assert!(first["qr"]["text"].as_str().unwrap().starts_with("COTTON-IN:1:"), "the square code at once: {first}");    assert_eq!(first["signOut"], "Sign out");    // A phone opened it: the Mac reveals once and shows the code both screens work out.    let second = app.call("askPoll", &json!({}));    let (vault, nonce) = {        let held = ask.lock().unwrap();        (bytes32(held.vault_key.as_deref().unwrap()), bytes32(held.revealed.as_deref().expect("revealed")))    };    let code = sas_of(&bytes32(&device_id), Some(&vault), &nonce, &NONCE_B);    assert_eq!(second["code"], shown_code(&code), "{second}");    assert_eq!(second["codeLine"], "Or type these digits on your other device.");    assert_eq!(second["qr"], first["qr"], "the square code stands beside the digits");    assert_eq!(app.call("askPoll", &json!({}))["code"], shown_code(&code), "the same code, no second reveal");    // Approved: the credential is claimed and handed over; the sign-in is this device's.    let approved = app.call("askPoll", &json!({}));    assert_eq!(approved["state"], "approved", "{approved}");    assert_eq!(approved["credential"], format!("ctd_{DB}_approved"));    assert_eq!(approved["phone"], PHONE);    assert!(ask.lock().unwrap().claimed);    assert_eq!(app.call("askPoll", &json!({}))["state"], "expired", "the ask is spent");    let started = app.call("start", &json!({ "token": format!("ctd_{DB}_approved"), "phone": PHONE }));    assert_eq!(started["ok"], true, "a credential this device claimed starts: {started}");    assert_eq!(app.call("status", &json!({}))["signInNote"], Value::Null);    // Signed in but not let in (signed in by a code, say): the panel asks again with no number typed, the number    // this Mac signed in with.    let again = app.call("askApproval", &json!({}));    assert_eq!(again["ok"], true, "{again}");    assert_eq!(again["state"], "waiting");    app.stop();}/// RULE (owner at the Mac, 22 Nov 2026): a Mac signed in but not let in to the person's data is never stuck: its/// waiting line offers Approve on another device and Sign out right there, and says the recovery code is the other way.#[test]fn the_not_let_in_line_offers_approval_and_sign_out() {    let line = serde_json::to_value(cotton_mac::vault::Pass::Waiting { fingerprint: "ABCD-EFGH".into() }.line("ABCD-EFGH")).unwrap();    assert_eq!(line["state"], "waiting");    assert_eq!(line["ask"], "Show a code to scan");    assert_eq!(line["signOut"], "Sign out");    assert!(line["detail"].as_str().unwrap().contains("scan the code on this Mac"));    assert!(!line["detail"].as_str().unwrap().contains("let in"));    assert!(line["detail"].as_str().unwrap().contains("recovery code"));}#[test]fn a_credential_kept_from_before_the_device_key_signs_the_mac_out_and_says_why() {    let server = host(Arc::new(Mutex::new(Ask::default())));    let dir = tempfile::tempdir().unwrap();    let app = open(&server, dir.path(), Some(DeviceKey::from_seed(&[9u8; 32])));    let started = app.call("start", &json!({ "token": format!("ctd_{DB}_old"), "phone": PHONE }));    assert_eq!(started["ok"], false);    assert_eq!(started["code"], "signed_out");    let status = app.call("status", &json!({}));    assert_eq!(status["signedOut"], true, "Swift drops the kept credential and shows sign-in");    assert_eq!(status["signedIn"], false);    assert_eq!(status["signInNote"], NOTE_NEW_IDENTITY);    assert!(server.requests().is_empty(), "nothing went out with the old credential");}#[test]fn a_tool_or_test_with_no_device_key_starts_as_before() {    let server = host(Arc::new(Mutex::new(Ask::default())));    let dir = tempfile::tempdir().unwrap();    let app = open(&server, dir.path(), None);    assert_eq!(app.config().device_id, "install-uuid");    assert_eq!(app.call("status", &json!({}))["askButton"], Value::Null);    assert_eq!(app.call("askApproval", &json!({ "phone": PHONE }))["code"], "device_key_unreadable");    app.stop();}#[test]fn the_device_key_is_minted_once_and_kept() {    let keyring = MemoryKeyring::default();    let first = DeviceKey::load_or_mint(&keyring).unwrap();    let again = DeviceKey::load_or_mint(&keyring).unwrap();    assert_eq!(first.id(), again.id());    assert_eq!(first.id().len(), 43, "32 bytes of base64url, as the Worker's DEVICE_KEY wants");}