Cotton code
232 lines · 12.7 KB · RustRaw
//! The new device's waiting page (GETTING-IN.md) against a scripted Worker: it asks by itself, shows the square code//! at once and the digits once the other device opened the ask, and says each way it ends. Every number, device,//! key and name is invented.use std::sync::Mutex;use base64::engine::general_purpose::URL_SAFE_NO_PAD;use base64::Engine as _;use cotton_client::transport::object::ObjectAddress;use cotton_client::transport::scripted::{Reply, ScriptedExchange};use cotton_client::vault::devices::DeviceKey;use cotton_client::DeviceIdentity;use serde_json::{json, Value};use super::*;use crate::phone::signin_approval::{ASK, POLL, REVEAL};const SERVER: &str = "https://cottondb.example.test";struct Key(DeviceIdentity);impl DeviceSigner for Key {    fn device_id(&self) -> String {        self.0.device_id()    }    fn sign(&self, message: &[u8]) -> Result<[u8; 64], String> {        Ok(self.0.sign(message))    }}fn me() -> Key {    Key(DeviceIdentity::from_secret(&[7u8; 32]).expect("a key"))}fn address() -> ObjectAddress {    ObjectAddress::open(SERVER).expect("an address")}fn request() -> Value {    json!({"server": SERVER, "phone": "+919000006001", "deviceName": "Pixel walk", "deviceKind": "android", "vaultKey": URL_SAFE_NO_PAD.encode([44u8; 32])})}fn asked(id: &str) -> Reply {    Reply::ok(&json!({"ask_id": id, "expires_in": 180, "poll_seconds": 3}).to_string())}fn body(seen: &cotton_client::transport::scripted::Seen) -> Value {    serde_json::from_slice(&seen.body).expect("a JSON body")}fn key_row(device: &str, wrapped: bool) -> DeviceKey {    DeviceKey { id: format!("row-{device}"), device_id: device.into(), name: None, fingerprint: None, public_key: None, wrapped, vmk_version: 1, created_at: None }}// RULE: a device waits only when its own key is published and unwrapped and another device holds the key.#[test]fn a_device_waits_only_when_another_holds_the_key_and_it_does_not() {    assert!(waits(Some("new"), &[key_row("new", false), key_row("old", true)]));    assert!(!waits(Some("new"), &[key_row("new", true), key_row("old", true)]), "it holds the key");    assert!(!waits(Some("new"), &[key_row("new", false)]), "nobody holds it: this device founds, it waits on nobody");    assert!(waits(Some("new"), &[key_row("old", true)]), "its key is not published yet: it still waits, so the page asks");    assert!(!waits(None, &[key_row("old", true)]));}// RULE: the page asks by itself, names this device's kind and vault key, and shows the square code at once, carrying// the ask and the nonce it committed to; the digits wait for the other device.#[test]fn the_page_asks_by_itself_and_shows_the_square_code_at_once() {    let slot = Mutex::new(None);    let exchange = ScriptedExchange::new([asked("cta_FIRSTFIRSTFIRSTFIRSTFIRSTFIRST1")]);    let page = screen(&slot, &address(), exchange.as_ref(), &me(), &request(), false).expect("a page");    let sent = body(&exchange.only());    assert_eq!(exchange.only().path, ASK);    assert_eq!(sent["device_kind"], "android");    assert_eq!(sent["vault_key"], URL_SAFE_NO_PAD.encode([44u8; 32]));    assert_eq!(page["show"], true);    assert_eq!(page["state"], "waiting");    assert_eq!(page["heading"], "One more step: open another device of yours");    assert_eq!(page["codeLine"], "Look for a notification or a card on your other device, then tap Approve there.");    assert_eq!(page["code"], Value::Null);    assert_eq!(page["signOut"], "Sign out");    assert_eq!(page["noDevice"], "No other device?");    assert_eq!(page["later"], "Do this later");    let text = page["qr"]["text"].as_str().expect("the square code's text");    let (ask_id, nonce) = cotton_core::vault::approval::read_scan(text).expect("a Cotton code");    assert_eq!(ask_id, "cta_FIRSTFIRSTFIRSTFIRSTFIRSTFIRST1");    let device = URL_SAFE_NO_PAD.decode(me().device_id()).unwrap();    assert_eq!(sent["commit"], URL_SAFE_NO_PAD.encode(cotton_core::vault::approval::commit_of(&device, Some(&[44u8; 32]), &nonce)), "the code carries the very nonce the ask committed to");    let size = page["qr"]["size"].as_u64().unwrap() as usize;    let rows = page["qr"]["rows"].as_array().unwrap();    assert_eq!(rows.len(), size);    assert!(rows.iter().all(|row| row.as_str().unwrap().len() == size && row.as_str().unwrap().chars().all(|c| c == '0' || c == '1')));    assert_eq!(&rows[0].as_str().unwrap()[..7], "1111111", "a finder pattern in the corner");    let said = page.to_string();    for word in ["records", "vault", "let in", "Approve on another device"] {        assert!(!said.contains(word), "the page never says {word:?}");    }}// RULE: once the other device opens the ask, the page reveals and shows the six digits beside the square code.#[test]fn the_digits_come_once_the_other_device_opens_the_ask() {    let slot = Mutex::new(None);    let exchange = ScriptedExchange::new([        asked("cta_DIGITSDIGITSDIGITSDIGITSDIGITS"),        Reply::ok(r#"{"state":"waiting"}"#),        Reply::ok(&json!({"state": "waiting", "nonce_b": URL_SAFE_NO_PAD.encode([55u8; 32])}).to_string()),        Reply::ok(r#"{"ok":true}"#),    ]);    screen(&slot, &address(), exchange.as_ref(), &me(), &request(), false).expect("asked");    let before = screen(&slot, &address(), exchange.as_ref(), &me(), &request(), false).expect("waiting");    assert_eq!(before["code"], Value::Null);    assert_eq!(before["left"], "3 minutes left");    let after = screen(&slot, &address(), exchange.as_ref(), &me(), &request(), false).expect("opened");    assert!(after["code"].as_str().unwrap().len() == 7, "six digits in two threes");    assert_eq!(after["codeLine"], "Or type these digits on your other device.");    assert_eq!(after["qr"], before["qr"], "the square code stands beside them");    assert_eq!(exchange.nth(3).path, REVEAL);    assert_eq!(exchange.nth(1).path, POLL);}// RULE: approved, the claim is made, a pass is asked for, and the page says the things are loading until the key lands.#[test]fn approved_asks_for_a_pass_and_says_the_things_are_loading() {    let slot = Mutex::new(None);    let exchange = ScriptedExchange::new([        asked("cta_APPROVEDAPPROVEDAPPROVEDAPPRO"),        Reply::ok(r#"{"state":"approved","challenge":"chal-1"}"#),        Reply::ok(r#"{"credential":"ctd_11111111-1111-4111-8111-111111111111_x","person":{},"database_id":"11111111-1111-4111-8111-111111111111"}"#),        Reply::ok(r#"{"state":"used"}"#),    ]);    screen(&slot, &address(), exchange.as_ref(), &me(), &request(), false).expect("asked");    let approved = screen(&slot, &address(), exchange.as_ref(), &me(), &request(), false).expect("approved");    assert_eq!(approved["state"], "approved");    assert_eq!(approved["sync"], true);    assert_eq!(approved["line"], "Your other device said yes. Bringing your things here now.");    assert!(!approved.to_string().contains("Approved"), "never Approved before the key is here (coordinator, 22 Nov 2026)");    assert_eq!(approved["qr"], Value::Null);    assert!(approved.get("credential").is_none(), "this device is signed in already: the claim's credential is dropped");    let still = screen(&slot, &address(), exchange.as_ref(), &me(), &request(), false).expect("still loading");    assert_eq!(still["state"], "approved");}// RULE: a No, three wrong codes and no answer in time each end the ask in their own words with Ask again, and stay// ended (no more polling) until the person asks again; again makes a fresh ask.#[test]fn each_end_is_said_and_waits_for_ask_again() {    for (reply, state, line) in [        (r#"{"state":"refused"}"#, "refused", "Your other device said no, so this device can't open your things. You're still signed in and can ask again."),        (r#"{"state":"refused","why":"wrong"}"#, "ended", "The digits were typed wrong three times, so this request has ended. You can ask again."),        (r#"{"state":"expired"}"#, "timed_out", "This request ran out of time. You can ask again."),    ] {        let slot = Mutex::new(None);        let exchange = ScriptedExchange::new([asked("cta_ENDENDENDENDENDENDENDENDENDENDEN"), Reply::ok(reply), asked("cta_AGAINAGAINAGAINAGAINAGAINAGAIN")]);        screen(&slot, &address(), exchange.as_ref(), &me(), &request(), false).expect("asked");        let ended = screen(&slot, &address(), exchange.as_ref(), &me(), &request(), false).expect("ended");        assert_eq!((ended["state"].as_str(), ended["line"].as_str()), (Some(state), Some(line)));        assert_eq!(ended["again"], "Ask again");        assert_eq!(ended["qr"], Value::Null);        assert_eq!(ended["signOut"], "Sign out", "never a dead end");        let same = screen(&slot, &address(), exchange.as_ref(), &me(), &request(), false).expect("still ended");        assert_eq!(same["state"], state);        assert_eq!(exchange.seen().len(), 2, "an ended ask is not polled");        let fresh = screen(&slot, &address(), exchange.as_ref(), &me(), &request(), true).expect("again");        assert_eq!(fresh["state"], "waiting");        assert_eq!(exchange.nth(2).path, ASK);        assert!(fresh["qr"]["text"].as_str().unwrap().contains("cta_AGAINAGAINAGAINAGAINAGAINAGAIN"));    }}// RULE: too many asks this hour, or no network: said plainly, Sign out still there, and the next look tries again.#[test]fn too_many_asks_and_no_network_are_said_and_tried_again() {    let slot = Mutex::new(None);    let exchange = ScriptedExchange::new([        Reply::json(429, r#"{"code":"too_many_asks","message":"Too many sign-in asks for this number in the last hour"}"#),        asked("cta_LATERLATERLATERLATERLATERLATER"),    ]);    let busy = screen(&slot, &address(), exchange.as_ref(), &me(), &request(), false).expect("busy");    assert_eq!(busy["state"], "busy");    assert_eq!(busy["line"], "There have been a lot of requests in the last hour. Please wait a little, then ask again.");    assert_eq!(busy["signOut"], "Sign out");    let later = screen(&slot, &address(), exchange.as_ref(), &me(), &request(), false).expect("asked later");    assert_eq!(later["state"], "waiting");}// RULE (coordinator, 22 Nov 2026): approved but the key never arrives: after about two minutes the page says so, with// Ask again, and never claims Approved.#[test]fn an_approval_whose_key_never_comes_says_so_with_ask_again() {    let slot = Mutex::new(None);    let mut replies = vec![asked("cta_STALLSTALLSTALLSTALLSTALLSTALL1"), Reply::ok(r#"{"state":"approved","challenge":"chal-1"}"#), Reply::ok(r#"{"credential":"ctd_11111111-1111-4111-8111-111111111111_x","person":{},"database_id":"11111111-1111-4111-8111-111111111111"}"#)];    for _ in 0..STALL_LOOKS + 2 {        replies.push(Reply::ok(r#"{"state":"used"}"#));    }    let exchange = ScriptedExchange::new(replies);    screen(&slot, &address(), exchange.as_ref(), &me(), &request(), false).expect("asked");    let mut last = Value::Null;    for _ in 0..=STALL_LOOKS {        last = screen(&slot, &address(), exchange.as_ref(), &me(), &request(), false).expect("a look");    }    assert_eq!(last["state"], "stalled");    assert_eq!(last["line"], "Your other device said yes, but your things haven't arrived here. Ask again, and keep Cotton open on that device until this one opens.");    assert_eq!(last["again"], "Ask again");    assert_eq!(last["signOut"], "Sign out");}// RULE (iPhone walk, 23 Nov 2026): a wait belongs to one sign-in. Signed out and in again (another number, or this// device's key published anew), the page asks afresh and never says the other device said yes from the approval// before.#[test]fn a_wait_of_another_sign_in_is_never_shown() {    let slot = Mutex::new(None);    let exchange = ScriptedExchange::new([        asked("cta_BEFOREBEFOREBEFOREBEFOREBEFORE1"),        Reply::ok(r#"{"state":"approved","challenge":"chal-1"}"#),        Reply::ok(r#"{"credential":"ctd_11111111-1111-4111-8111-111111111111_x","person":{},"database_id":"11111111-1111-4111-8111-111111111111"}"#),        asked("cta_AFTERAFTERAFTERAFTERAFTERAFTER"),    ]);    screen(&slot, &address(), exchange.as_ref(), &me(), &request(), false).expect("asked");    let approved = screen(&slot, &address(), exchange.as_ref(), &me(), &request(), false).expect("approved");    assert_eq!(approved["state"], "approved");    assert_eq!(approved["heading"], "Almost there");    assert!(approved.get("later").is_none() && approved.get("noDevice").is_none(), "nothing to choose once said yes: {approved}");    assert_eq!(approved["signOut"], "Sign out");    let mut other = request();    other["phone"] = json!("+919000006002");    let fresh = screen(&slot, &address(), exchange.as_ref(), &me(), &other, false).expect("a fresh ask");    assert_eq!(fresh["state"], "waiting", "{fresh}");    assert!(fresh["qr"]["text"].as_str().unwrap().contains("cta_AFTERAFTERAFTERAFTERAFTERAFTER"));    assert_eq!(fresh["lost"]["code"], "Use recovery code");}