//! The sign-in approval's rules against a scripted Worker: what each side //! sends, what each state says, the claim signed by this device's own key, //! the code both sides work out without the server choosing it, and the //! answer to an ask drawn the same for every number. Every number, device, //! key and name is invented. use std::sync::{Arc, Mutex}; use base64::engine::general_purpose::URL_SAFE_NO_PAD; use base64::Engine; use cotton_client::transport::object::ObjectAddress; use cotton_client::transport::scripted::{Reply, ScriptedExchange}; use cotton_client::DeviceIdentity; use ed25519_dalek::{Signature, Verifier, VerifyingKey}; use serde_json::{json, Value}; use super::*; const SERVER: &str = "https://cottondb.example.test"; const CREDENTIAL: &str = "ctd_11111111-1111-4111-8111-111111111111_approver"; const NEW_CREDENTIAL: &str = "ctd_11111111-1111-4111-8111-111111111111_new-device"; const DB: &str = "11111111-1111-4111-8111-111111111111"; 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 key(seed: u8) -> Key { Key(DeviceIdentity::from_secret(&[seed; 32]).expect("a key")) } fn address() -> ObjectAddress { ObjectAddress::open(SERVER).expect("an address") } fn body(seen: &cotton_client::transport::scripted::Seen) -> Value { serde_json::from_slice(&seen.body).expect("a JSON body") } const ASKED: &str = r#"{"ask_id":"cta_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA","expires_in":180,"poll_seconds":3}"#; const ASK_ID: &str = "cta_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; fn b64(bytes: &[u8]) -> String { URL_SAFE_NO_PAD.encode(bytes) } fn vault_key() -> String { b64(&[44u8; 32]) } /// Ask as this device, the Worker answering `ask_id`: the card and what was sent. fn asked(me: &Key, ask_id: &str, request: Value) -> (Value, Value) { let reply = json!({"ask_id": ask_id, "expires_in": 180, "poll_seconds": 3}).to_string(); let exchange = ScriptedExchange::new([Reply::ok(&reply)]); let card = ask(&address(), exchange.as_ref(), me, &request).expect("a card"); (card, body(&exchange.only())) } // RULE: an ask names this device by its key, its vault key and a commit to a nonce of its own; no code shows until a signed-in device opens it. #[test] fn an_ask_commits_to_this_devices_keys_and_shows_no_code_yet() { let me = key(7); let (card, sent) = asked(&me, ASK_ID, json!({"phone": "+919000005001", "deviceName": "Pixel walk", "vaultKey": vault_key()})); assert_eq!(sent["device_id"], me.device_id()); assert_eq!(sent["vault_key"], vault_key()); assert_eq!(sent["device_name"], "Pixel walk"); let nonce = URL_SAFE_NO_PAD.decode(card["handoff"]["nonce"].as_str().unwrap()).unwrap(); let device = URL_SAFE_NO_PAD.decode(me.device_id()).unwrap(); assert_eq!(sent["commit"], b64(&commit_of(&device, Some(&[44u8; 32]), &nonce))); assert!(sent.get("nonce").is_none(), "the nonce stays on the device until the approver's is in"); assert_eq!(card["askId"], ASK_ID); assert!(card.get("code").is_none()); assert_eq!(card["line"], "Open Cotton on a phone you're signed in on. A code will show here."); assert_eq!(card["heading"], "Approve this device"); assert_eq!(card["left"], "3 minutes left"); assert_eq!(card["pollSeconds"], 3); assert_eq!(card["sendCode"], "Send a code instead"); assert_eq!(card["handoff"]["deviceId"], me.device_id()); assert_eq!(card["handoff"]["vaultKey"], vault_key()); // NEXT-SIGNIN 3 (28 Nov 2026): the square code a signed-in phone scans, the getting-in page's own, for this ask. assert_eq!(card["qr"], crate::phone::getting_in::square(ASK_ID, nonce.as_slice().try_into().unwrap())); assert!(card["qr"]["rows"].as_array().is_some_and(|rows| !rows.is_empty()), "{}", card["qr"]); } // RULE: the asking device draws exactly what the Worker said, so a number on Cotton or not, a device signed in or not, look the same. #[test] fn every_number_draws_the_same_card() { let me = key(7); let (mut a, _) = asked(&me, "cta_SAME1SAME1SAME1SAME1SAME1SAME1A", json!({"phone": "+919000005002"})); let (mut b, _) = asked(&me, "cta_SAME2SAME2SAME2SAME2SAME2SAME2B", json!({"phone": "+919000005003"})); for card in [&mut a, &mut b] { let card = card.as_object_mut().unwrap(); card.remove("askId"); card.remove("handoff"); card.remove("qr"); } assert_eq!(a, b); } // RULE: once the approver's nonce is in, the asking device reveals its own (once) and shows the code both sides work out. #[test] fn the_approvers_nonce_brings_the_reveal_and_the_code() { let me = key(7); let ask_id = "cta_REVEALREVEALREVEALREVEALREVEAL"; let (card, sent) = asked(&me, ask_id, json!({"phone": "+919000005010", "vaultKey": vault_key()})); let nonce_b = b64(&[55u8; 32]); let exchange = ScriptedExchange::new([ Reply::ok(r#"{"state":"waiting"}"#), Reply::ok(&json!({"state": "waiting", "nonce_b": nonce_b}).to_string()), Reply::ok(r#"{"ok":true}"#), Reply::ok(&json!({"state": "waiting", "nonce_b": nonce_b}).to_string()), ]); let first = poll(&address(), exchange.as_ref(), &me, ask_id).expect("waiting"); assert_eq!(first["line"], "Open Cotton on a phone you're signed in on. A code will show here."); assert!(first.get("code").is_none()); let second = poll(&address(), exchange.as_ref(), &me, ask_id).expect("opened"); let third = poll(&address(), exchange.as_ref(), &me, ask_id).expect("still"); let seen = exchange.seen(); assert_eq!(seen.len(), 4, "one reveal, never two"); assert_eq!((seen[2].path.as_str(), body(&seen[2])), (REVEAL, json!({"ask_id": ask_id, "nonce": card["handoff"]["nonce"]}))); let device = URL_SAFE_NO_PAD.decode(me.device_id()).unwrap(); let nonce = URL_SAFE_NO_PAD.decode(card["handoff"]["nonce"].as_str().unwrap()).unwrap(); let code = sas_of(&device, Some(&[44u8; 32]), &nonce, &[55u8; 32]); assert_eq!(second["code"], shown_code(&code)); assert_eq!(third["code"], second["code"]); assert_eq!(second["line"], "On that phone, type this code:"); assert_eq!(second["done"], false); assert_eq!(sent["commit"], b64(&commit_of(&device, Some(&[44u8; 32]), &nonce))); } // RULE: refused, expired and used are done, each in its own words with Ask again and Send a code; an ask this process never made is said lost. #[test] fn each_state_says_its_own_line_and_whether_polling_is_done() { let exchange = ScriptedExchange::new([ Reply::ok(r#"{"state":"waiting"}"#), Reply::ok(r#"{"state":"refused"}"#), Reply::ok(r#"{"state":"expired"}"#), Reply::ok(r#"{"state":"used"}"#), ]); let me = key(7); let lost = poll(&address(), exchange.as_ref(), &me, "cta_NEVERMADENEVERMADENEVERMADENEVE").expect("lost"); assert_eq!((lost["done"].clone(), lost["line"].clone()), (json!(true), json!("This ask was lost when the app closed. Ask again."))); let refused = poll(&address(), exchange.as_ref(), &me, ASK_ID).expect("refused"); assert_eq!((refused["done"].clone(), refused["line"].clone()), (json!(true), json!("That phone said no. Send a code instead."))); assert_eq!(refused["sendCode"], "Send a code instead"); let expired = poll(&address(), exchange.as_ref(), &me, ASK_ID).expect("expired"); assert_eq!(expired["line"], "Nobody approved in time. Ask again, or send a code."); assert_eq!(expired["again"], "Ask again"); let used = poll(&address(), exchange.as_ref(), &me, ASK_ID).expect("used"); assert_eq!((used["state"].clone(), used["line"].clone()), (json!("used"), json!("That approval was already used. Ask again."))); for seen in exchange.seen() { assert_eq!((seen.method.as_str(), seen.path.as_str()), ("POST", POLL)); } } // RULE: approved, the core claims at once with this device's own signature over the Worker's challenge, and hands over the credential as a sign-in does. #[test] fn approved_claims_with_this_devices_signature_over_the_challenge() { let exchange = ScriptedExchange::new([ Reply::ok(r#"{"state":"approved","challenge":"chal-123"}"#), Reply::ok(&json!({"credential": NEW_CREDENTIAL, "person": {"phone": "+919000005004", "role": "owner"}, "expires_in": 7776000, "database_id": DB, "host": SERVER}).to_string()), ]); let me = key(7); let answer = poll(&address(), exchange.as_ref(), &me, ASK_ID).expect("approved"); assert_eq!(answer["state"], "approved"); assert_eq!(answer["done"], true); assert_eq!(answer["credential"], NEW_CREDENTIAL); assert_eq!(answer["databaseId"], DB); assert_eq!(answer["expiresIn"], 7776000); assert_eq!(answer["line"], "Approved. Signing in…"); let claim_sent = exchange.nth(1); assert_eq!((claim_sent.method.as_str(), claim_sent.path.as_str()), ("POST", CLAIM)); let sent = body(&claim_sent); assert_eq!(sent["ask_id"], ASK_ID); let sig = URL_SAFE_NO_PAD.decode(sent["sig"].as_str().unwrap()).expect("base64url"); let public: [u8; 32] = URL_SAFE_NO_PAD.decode(me.device_id()).unwrap().try_into().unwrap(); let verifying = VerifyingKey::from_bytes(&public).unwrap(); let signature = Signature::from_slice(&sig).unwrap(); assert!(verifying.verify(claim_statement(ASK_ID, "chal-123").as_bytes(), &signature).is_ok(), "signed by this device over the challenge"); // Another device's key would not verify: the claim is bound to the asking key. let theirs: [u8; 32] = URL_SAFE_NO_PAD.decode(key(9).device_id()).unwrap().try_into().unwrap(); assert!(VerifyingKey::from_bytes(&theirs).unwrap().verify(claim_statement(ASK_ID, "chal-123").as_bytes(), &signature).is_err()); } // RULE: a claim the Worker refuses (another device's key, a spent ask) reaches the shell by its own code, and no credential is said. #[test] fn a_refused_claim_is_said_by_its_code() { let exchange = ScriptedExchange::new([ Reply::ok(r#"{"state":"approved","challenge":"chal-123"}"#), Reply::json(401, r#"{"code":"wrong_device","message":"That sign-in was asked for from another device."}"#), Reply::ok(r#"{"state":"approved","challenge":"chal-123"}"#), Reply::json(410, r#"{"code":"ask_used","message":"That sign-in was already used."}"#), ]); let me = key(7); assert_eq!(poll(&address(), exchange.as_ref(), &me, ASK_ID).expect_err("refused").code, "wrong_device"); assert_eq!(poll(&address(), exchange.as_ref(), &me, ASK_ID).expect_err("refused").code, "ask_used"); } // RULE: a refusal of the ask itself (the hour's asks spent) is said by its code. #[test] fn too_many_asks_is_said_by_its_code() { 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; try again later, or send a code."}"#)]); assert_eq!(ask(&address(), exchange.as_ref(), &key(7), &json!({"phone": "+919000005005"})).expect_err("refused").code, "too_many_asks"); } fn door_of(replies: impl IntoIterator) -> (ObjectDoor, Arc) { let exchange = ScriptedExchange::new(replies); (ObjectDoor { address: address(), exchange: exchange.clone(), credential: CREDENTIAL.to_string() }, exchange) } /// A vault that records who it let in. #[derive(Default)] struct Vault(Mutex)>>); impl VaultAdmit for Vault { fn admit(&self, device_id: &str, public_key: &str, name: Option<&str>, _private_key: &[u8; 32]) -> Result<(), MethodError> { self.0.lock().unwrap().push((device_id.to_string(), public_key.to_string(), name.map(str::to_string))); Ok(()) } } /// A vault that refuses every admission, as a copy holding an older vault key does. struct Refusing; impl VaultAdmit for Refusing { fn admit(&self, _device_id: &str, _public_key: &str, _name: Option<&str>, _private_key: &[u8; 32]) -> Result<(), MethodError> { Err(MethodError::new("vault_stale", cotton_client::vault::devices::refusal::STALE)) } } /// An ask as the object holds it, from a device of key `seed`, its codes compared or not. struct Asking { device: Vec, vault: [u8; 32], nonce: [u8; 32], nonce_b: [u8; 32], } impl Asking { fn new(seed: u8) -> Self { Asking { device: URL_SAFE_NO_PAD.decode(key(seed).device_id()).unwrap(), vault: [seed.wrapping_add(1); 32], nonce: [seed.wrapping_add(2); 32], nonce_b: [seed.wrapping_add(3); 32] } } fn code(&self) -> String { sas_of(&self.device, Some(&self.vault), &self.nonce, &self.nonce_b) } fn held(&self, ask_id: &str, name: Option<&str>, now: i64, revealed: bool, opened: bool) -> Value { json!({ "ask_id": ask_id, "device_id": b64(&self.device), "device_name": name, "vault_key": b64(&self.vault), "commit": b64(&commit_of(&self.device, Some(&self.vault), &self.nonce)), "nonce_b": if opened { json!(b64(&self.nonce_b)) } else { Value::Null }, "reveal": if revealed { json!(b64(&self.nonce)) } else { Value::Null }, "asked_at": now - 125, "expires_at": now + 55, }) } } // RULE: the approving card only looks: it sets nothing on any ask, never shows a code, and says // where each ask stands; an ask nobody has tapped is `asked`, with the button that opens it. #[test] fn the_approving_card_sets_nothing_and_never_shows_its_code() { let now = 1_800_000_000; let pixel = Asking::new(7); let tab = Asking::new(9); let watch = Asking::new(13); let asks = json!({"now": now, "asks": [ pixel.held("cta_1", Some("Pixel walk"), now, true, true), tab.held("cta_2", None, now, false, false), watch.held("cta_4", Some("Watch"), now, false, true), {"ask_id": "cta_3", "device_name": "Stale", "asked_at": now - 400, "expires_at": now - 1} ]}); let (door, exchange) = door_of([Reply::ok(&asks.to_string())]); let card = over(&door, "signin.asks", &json!({}), 0, &Vault::default()).expect("a card"); let seen = exchange.seen(); assert_eq!((seen[0].method.as_str(), seen[0].path.as_str()), ("GET", APPROVALS)); assert_eq!(seen[0].header("authorization"), Some(format!("Bearer {CREDENTIAL}").as_str())); assert_eq!(seen.len(), 1, "looking sets no nonce: the asking device's screen says nothing of this phone"); let waiting = card["waiting"].as_array().expect("a list"); assert_eq!(waiting.len(), 3, "an expired ask is never drawn"); assert_eq!(waiting[0]["phase"], "compare"); assert_eq!(waiting[0]["line"], "Pixel walk wants to sign in to your Cotton."); assert_eq!(waiting[0]["type"], "Type the code Pixel walk shows."); assert_eq!(waiting[0]["vault"], true); assert_eq!(waiting[0]["digits"], 6); assert_eq!(waiting[0]["when"], "Asked 2 minutes ago · 1 minute left"); assert_eq!(waiting[0]["confirm"], "Pixel walk will not be signed in. It can ask again."); assert_eq!(waiting[0]["show"], Value::Null); assert_eq!(waiting[1]["phase"], "asked"); assert_eq!(waiting[1]["name"], "A new device"); assert_eq!(waiting[1]["type"], "Signing in on A new device yourself? Tap below and a code shows there."); assert_eq!(waiting[1]["show"], "This is me, show the code"); assert_eq!(waiting[2]["phase"], "opening"); assert_eq!(waiting[2]["type"], "Opening the sign-in from Watch…"); let said = card.to_string(); assert!(!said.contains(&pixel.code()), "the code is typed here, never shown"); assert_eq!(card["pollSeconds"], OPENING_POLL_SECONDS, "fast while an opened ask waits for its reveal"); // Nobody has tapped anything: the card is looked at slowly. let only_asked = json!({"now": now, "asks": [tab.held("cta_2", None, now, false, false)]}); let (door, _) = door_of([Reply::ok(&only_asked.to_string())]); assert_eq!(over(&door, "signin.asks", &json!({}), 0, &Vault::default()).expect("a card")["pollSeconds"], ASKS_POLL_SECONDS); } // RULE: "This is me, show the code" sets this device's nonce on that one ask, once, and answers // the card with it opening. #[test] fn show_sets_the_nonce_on_the_one_ask_tapped() { let now = 1_800_000_000; let tab = Asking::new(9); let other = Asking::new(21); let asks = json!({"now": now, "asks": [tab.held("cta_2", Some("Tab"), now, false, false), other.held("cta_5", None, now, false, false)]}); let (door, exchange) = door_of([Reply::ok(&asks.to_string()), Reply::ok(&json!({"nonce_b": b64(&tab.nonce_b)}).to_string())]); let card = over(&door, "signin.show", &json!({"askId": "cta_2"}), 0, &Vault::default()).expect("a card"); let seen = exchange.seen(); assert_eq!(seen.len(), 2); assert_eq!((seen[1].path.as_str(), body(&seen[1])["ask_id"].clone()), (NONCE, json!("cta_2"))); assert_eq!(card["waiting"][0]["phase"], "opening"); assert_eq!(card["waiting"][1]["phase"], "asked", "the other ask is left as it was"); // An ask already opened (another device of the number tapped first) is not set again. let opened = json!({"now": now, "asks": [tab.held("cta_2", Some("Tab"), now, false, true)]}); let (door, exchange) = door_of([Reply::ok(&opened.to_string())]); over(&door, "signin.show", &json!({"askId": "cta_2"}), 0, &Vault::default()).expect("a card"); assert_eq!(exchange.seen().len(), 1); let (door, _) = door_of([Reply::ok(&opened.to_string())]); assert_eq!(over(&door, "signin.show", &json!({"askId": "cta_9"}), 0, &Vault::default()).expect_err("gone").code, "no_such_ask"); } // RULE: the right code typed approves, and with this device's vault key lets the new device into the vault under the key the code vouched for. #[test] fn the_right_code_approves_and_lets_the_device_into_the_vault() { let now = 1_800_000_000; let pixel = Asking::new(7); let asks = json!({"now": now, "asks": [pixel.held("cta_1", Some("Pixel walk"), now, true, true)]}); let (door, exchange) = door_of([Reply::ok(&asks.to_string()), Reply::ok(r#"{"ok":true}"#)]); let vault = Vault::default(); let typed = shown_code(&pixel.code()); let approved = over(&door, "signin.approve", &json!({"askId": "cta_1", "code": typed, "privateKey": b64(&[26u8; 32])}), 0, &vault).expect("approved"); assert_eq!(approved["said"], "Your device can open your things now.", "an ask from an app before kinds says device"); assert_eq!(approved["vault"], true); let seen = exchange.seen(); assert_eq!((seen[1].path.as_str(), body(&seen[1])), (APPROVE, json!({"ask_id": "cta_1"}))); assert_eq!(*vault.0.lock().unwrap(), vec![(b64(&pixel.device), b64(&pixel.vault), Some("Pixel walk".to_string()))]); let said = approved.to_string(); assert!(!said.contains(&b64(&[26u8; 32])), "the private key is never said back"); // The wrap refused (this phone's copy holds an older vault key, say): said, and never as Approved (coordinator, // 22 Nov 2026: nothing says Approved unless the new device can really open the things). let (door, _) = door_of([Reply::ok(&asks.to_string()), Reply::ok(r#"{"ok":true}"#)]); let locked = over(&door, "signin.approve", &json!({"askId": "cta_1", "code": typed, "privateKey": b64(&[26u8; 32])}), 0, &Refusing).expect_err("not handed over"); assert_eq!(locked.code, "not_handed"); assert!(!locked.message.contains("Approved"), "{}", locked.message); // Without this device's vault key the sign-in is approved and the vault waits. let (door, _) = door_of([Reply::ok(&asks.to_string()), Reply::ok(r#"{"ok":true}"#)]); let signed_only = over(&door, "signin.approve", &json!({"askId": "cta_1", "code": pixel.code()}), 0, &Vault::default()).expect("approved"); assert_eq!((signed_only["vault"].clone(), signed_only["said"].clone()), (json!(false), json!("Approved. Pixel walk is signing in."))); } // RULE (walk on dev, 22 Nov 2026): the wrong-code sentences reach the person whatever the asking device calls itself. // An emulator is `sdk_gphone64_x86_64`, a word the failure filter takes for a code name and blanks to "That didn't work. // Try again.", so the tries left were never said; the name is said with spaces. #[test] fn a_wrong_code_is_said_even_for_a_device_named_like_code() { let now = 1_800_000_000; let pixel = Asking::new(12); let asks = json!({"now": now, "asks": [pixel.held("cta_emu", Some("sdk_gphone64_x86_64"), now, true, true)]}).to_string(); let wrong = if pixel.code() == "000000" { "000001" } else { "000000" }; let (door, _) = door_of([Reply::ok(&asks), Reply::ok(r#"{"left":2,"ended":false}"#), Reply::ok(&asks), Reply::ok(r#"{"left":0,"ended":true}"#)]); let first = over(&door, "signin.approve", &json!({"askId": "cta_emu", "code": wrong}), 0, &Vault::default()).expect_err("wrong"); assert_eq!(first.message, "That isn't the code on sdk gphone64 x86 64. 2 tries left."); assert!(!cotton_core::failure::shows_internals(&first.message), "{}", first.message); let last = over(&door, "signin.approve", &json!({"askId": "cta_emu", "code": wrong}), 0, &Vault::default()).expect_err("ended"); assert!(!cotton_core::failure::shows_internals(&last.message), "{}", last.message); } // RULE: a wrong code approves nothing; the OBJECT counts it, and the tries left are what it says, // so every device of the number and every restart share three; the last ends the ask. #[test] fn wrong_codes_are_counted_by_the_object() { let now = 1_800_000_000; let pixel = Asking::new(11); let asks = json!({"now": now, "asks": [pixel.held("cta_wrong", Some("Pixel walk"), now, true, true)]}).to_string(); let wrong = if pixel.code() == "000000" { "000001" } else { "000000" }; let (door, exchange) = door_of([ Reply::ok(&asks), Reply::ok(r#"{"left":2,"ended":false}"#), Reply::ok(&asks), Reply::ok(r#"{"left":1,"ended":false}"#), Reply::ok(&asks), Reply::ok(r#"{"left":0,"ended":true}"#), ]); let vault = Vault::default(); let first = over(&door, "signin.approve", &json!({"askId": "cta_wrong", "code": wrong}), 0, &vault).expect_err("wrong"); assert_eq!((first.code.as_str(), first.message.as_str()), ("code_wrong", "That isn't the code on Pixel walk. 2 tries left.")); let second = over(&door, "signin.approve", &json!({"askId": "cta_wrong", "code": wrong}), 0, &vault).expect_err("wrong"); assert_eq!(second.message, "That isn't the code on Pixel walk. 1 try left."); let third = over(&door, "signin.approve", &json!({"askId": "cta_wrong", "code": wrong}), 0, &vault).expect_err("ended"); assert_eq!((third.code.as_str(), third.message.as_str()), ("code_ended", "That code didn't match three times, so Pixel walk was turned away.")); let seen = exchange.seen(); let counted: Vec = seen.iter().filter(|s| s.path == WRONG).map(body).collect(); assert_eq!(counted, vec![json!({"ask_id": "cta_wrong"}); 3]); assert_eq!(seen.iter().filter(|s| s.path == APPROVE || s.path == REFUSE).count(), 0, "the object ends the ask itself"); assert!(vault.0.lock().unwrap().is_empty()); // A fresh process (or another phone) learns the tries left from the object, not from its own memory. let (door, _) = door_of([Reply::ok(&asks), Reply::ok(r#"{"left":1,"ended":false}"#)]); let after_restart = over(&door, "signin.approve", &json!({"askId": "cta_wrong", "code": wrong}), 0, &vault).expect_err("wrong"); assert_eq!(after_restart.message, "That isn't the code on Pixel walk. 1 try left."); } // RULE: an ask whose reveal does not hash to its commit (a key swapped on the way) is never comparable, so no code typed approves it. #[test] fn a_swapped_key_makes_the_ask_uncomparable() { let now = 1_800_000_000; let pixel = Asking::new(7); let mut held = pixel.held("cta_1", Some("Pixel walk"), now, true, true); held["vault_key"] = json!(b64(&[99u8; 32])); let asks = json!({"now": now, "asks": [held]}).to_string(); let (door, exchange) = door_of([Reply::ok(&asks), Reply::ok(&asks)]); let card = over(&door, "signin.asks", &json!({}), 0, &Vault::default()).expect("a card"); assert_eq!(card["waiting"][0]["phase"], "opening"); let refused = over(&door, "signin.approve", &json!({"askId": "cta_1", "code": pixel.code()}), 0, &Vault::default()).expect_err("refused"); assert_eq!(refused.code, "not_compared"); assert!(exchange.seen().iter().all(|s| s.path == APPROVALS)); } // RULE: a sibling app on the same phone approves only the ask that names the device, vault key and commit it was // handed, says the reveal itself, and with this device's vault key lets it into the vault too. #[test] fn a_sibling_approves_only_the_very_ask_it_was_handed() { let now = 1_800_000_000; let pixel = Asking::new(7); let asks = json!({"now": now, "asks": [pixel.held("cta_1", Some("Pixel walk"), now, false, false)]}).to_string(); let ticketed = |request: &Value| { let mut request = request.clone(); request["ticket"] = json!(mint_ticket("cta_1")); request }; let handed = json!({"askId": "cta_1", "deviceId": b64(&pixel.device), "vaultKey": b64(&pixel.vault), "nonce": b64(&pixel.nonce)}); let mut other_key = handed.clone(); other_key["vaultKey"] = json!(b64(&[99u8; 32])); let mut other_nonce = handed.clone(); other_nonce["nonce"] = json!(b64(&[98u8; 32])); let (door, exchange) = door_of([Reply::ok(&asks), Reply::ok(&asks), Reply::ok(&asks), Reply::ok(r#"{"nonce_b":"x"}"#), Reply::ok(r#"{"ok":true}"#), Reply::ok(r#"{"ok":true}"#)]); assert_eq!(over(&door, "signin.approveSibling", &ticketed(&other_key), 0, &Vault::default()).expect_err("not it").code, "not_that_ask"); assert_eq!(over(&door, "signin.approveSibling", &ticketed(&other_nonce), 0, &Vault::default()).expect_err("not it").code, "not_that_ask"); let mut with_key = ticketed(&handed); with_key["privateKey"] = json!(b64(&[26u8; 32])); let vault = Vault::default(); let approved = over(&door, "signin.approveSibling", &with_key, 0, &vault).expect("approved"); assert_eq!((approved["ok"].clone(), approved["vault"].clone()), (json!(true), json!(true))); assert_eq!(*vault.0.lock().unwrap(), vec![(b64(&pixel.device), b64(&pixel.vault), Some("Pixel walk".to_string()))]); let paths: Vec = exchange.seen().iter().map(|s| s.path.clone()).collect(); assert_eq!(paths, [APPROVALS, APPROVALS, APPROVALS, NONCE, REVEAL, APPROVE]); let seen = exchange.seen(); assert_eq!(body(&seen[4]), json!({"ask_id": "cta_1", "nonce": b64(&pixel.nonce)})); assert_eq!(seen[4].header("authorization"), None, "the reveal goes to the open host, as the asking device's would"); } // RULE: approveSibling approves with no code and no presence, so it refuses unless the request // carries a live ticket minted in this process for that very ask, which only the checked channel (Android's // signature-checked SiblingKeys provider) hands out. What a URL or an intent can carry (the ask's id, device, vault key // and nonce, all a stranger's to know) reaches nothing: no ticket, a made-up one, one for another ask, or one spent. #[test] fn approve_sibling_refuses_without_the_checked_channels_ticket() { let now = 1_800_000_000; let pixel = Asking::new(7); let asks = json!({"now": now, "asks": [pixel.held("cta_1", Some("Pixel walk"), now, false, false)]}).to_string(); let handed = json!({"askId": "cta_1", "deviceId": b64(&pixel.device), "vaultKey": b64(&pixel.vault), "nonce": b64(&pixel.nonce)}); let (door, exchange) = door_of([Reply::ok(&asks), Reply::ok(r#"{"nonce_b":"x"}"#), Reply::ok(r#"{"ok":true}"#), Reply::ok(r#"{"ok":true}"#)]); let refused = |request: &Value| over(&door, "signin.approveSibling", request, 0, &Vault::default()).expect_err("refused").code; // As a URL would bring it: every field of the ask, no ticket. assert_eq!(refused(&handed), "not_the_channel"); let mut made_up = handed.clone(); made_up["ticket"] = json!(b64(&[5u8; 32])); assert_eq!(refused(&made_up), "not_the_channel"); let mut for_another = handed.clone(); for_another["ticket"] = json!(mint_ticket("cta_other")); assert_eq!(refused(&for_another), "not_the_channel"); assert!(exchange.seen().is_empty(), "nothing was asked of the object"); let ticket = over(&door, "signin.siblingTicket", &json!({"askId": "cta_1"}), 0, &Vault::default()).expect("a ticket")["ticket"].as_str().expect("text").to_string(); let mut good = handed.clone(); good["ticket"] = json!(ticket); assert_eq!(over(&door, "signin.approveSibling", &good, 0, &Vault::default()).expect("approved")["ok"], true); assert_eq!(refused(&good), "not_the_channel", "a ticket is spent once"); } // RULE: Refuse sends the ask's id with this device's credential and says what happened. #[test] fn refuse_sends_the_ask_and_says_what_happened() { let (door, exchange) = door_of([Reply::ok(r#"{"ok":true}"#)]); let refused = over(&door, "signin.refuse", &json!({"askId": "cta_2"}), 0, &Vault::default()).expect("refused"); assert_eq!(refused["said"], "Refused. A new device was not signed in."); let seen = exchange.only(); assert_eq!((seen.path.as_str(), body(&seen)), (REFUSE, json!({"ask_id": "cta_2"}))); assert_eq!(seen.header("authorization"), Some(format!("Bearer {CREDENTIAL}").as_str())); } // RULE: an ask already answered or expired is said by the object's code. #[test] fn a_late_decision_is_said_by_its_code() { let (door, _) = door_of([Reply::json(410, r#"{"code":"ask_expired","message":"That sign-in ask has expired."}"#)]); assert_eq!(over(&door, "signin.refuse", &json!({"askId": "cta_1"}), 0, &Vault::default()).expect_err("refused").code, "ask_expired"); } // RULE: the one-tap button names the number by its last four digits only, and the app that is signed in. #[test] fn the_handoff_button_shows_four_digits_of_the_number() { let said = handoff(&json!({"phone": "+919000005077", "app": "Cotton Books"})).expect("said"); assert_eq!(said["button"], "Sign in as •••• 5077"); assert_eq!(said["line"], "You're signed in to Cotton Books on this phone."); assert!(!said.to_string().contains("9000005077")); } // ── GETTING-IN.md: the one card, Approve by scanning ───────────────────── // RULE (GETTING-IN.md): the card says who asks in the person's words ("Your Mac wants to sign in to your Cotton"), // with Approve that scans, Not me, and the words of the camera, the digits and the notification. #[test] fn the_card_names_the_device_by_its_kind_with_approve_and_not_me() { let now = 1_800_000_000; let mac = Asking::new(7); let mut held = mac.held("cta_1", Some("mac-c"), now, false, false); held["device_kind"] = json!("mac"); let old = Asking::new(9).held("cta_2", Some("Old app"), now, false, true); let (door, _) = door_of([Reply::ok(&json!({"now": now, "asks": [held, old], "holds": true}).to_string())]); let card = over(&door, "signin.asks", &json!({}), 0, &Vault::default()).expect("a card"); let mine = &card["waiting"][0]; assert_eq!(mine["title"], "Your Mac wants to sign in to your Cotton"); assert_eq!(mine["sub"], "mac-c asked 2 minutes ago. Approve only if you're holding it yourself."); assert_eq!(mine["approve"], "Approve"); assert_eq!(mine["notMe"], "Not me"); assert_eq!(mine["notMeConfirm"], "Say no to this Mac? It won't be able to open any of your things. It stays signed in and can ask again."); assert_eq!(mine["scan"]["heading"], "Scan the code on your Mac"); assert_eq!(mine["scan"]["typeInstead"], "Type the code instead"); assert_eq!(mine["typeHeading"], "Type the six digits shown on your Mac"); assert_eq!(mine["notify"]["title"], "Your Mac wants to sign in to your Cotton"); assert_eq!(mine["kind"], "mac"); // An ask from an app before the kind was said: no kind, a plain title, and "device" where the kind would go. let older = &card["waiting"][1]; assert_eq!(older["title"], "A new device wants to sign in to your Cotton"); assert_eq!(older["scan"]["heading"], "Scan the code on your device"); assert_eq!(older["typeWaiting"], "The digits show on your device in a moment."); for field in ["title", "sub", "approve", "notMe", "notMeConfirm", "notMeDone", "typeHeading"] { let said = mine[field].as_str().unwrap_or_default(); for word in ["records", "vault", "let in", "private"] { assert!(!said.contains(word), "{field} never says {word:?}: {said}"); } } } // RULE (GETTING-IN.md): a device that cannot open the person's things itself is shown no ask at all. #[test] fn a_device_that_cannot_open_the_things_itself_sees_no_ask() { let now = 1_800_000_000; let mac = Asking::new(7); let (door, _) = door_of([Reply::ok(&json!({"now": now, "asks": [mac.held("cta_1", Some("mac-c"), now, false, false)], "holds": false}).to_string())]); let card = over(&door, "signin.asks", &json!({}), 0, &Vault::default()).expect("a card"); assert_eq!(card["waiting"], json!([])); // And should it approve anyway, the object's refusal is said in plain words. let (door, _) = door_of([ Reply::ok(&json!({"now": now, "asks": [mac.held("cta_1", Some("mac-c"), now, false, false)]}).to_string()), Reply::json(403, r#"{"code":"approver_locked","message":"This device cannot open your data itself, so it cannot let another one in."}"#), ]); let scanned = cotton_core::vault::approval::scan_text("cta_1", &mac.nonce); let refused = over(&door, "signin.approve", &json!({"askId": "cta_1", "scanned": scanned}), 0, &Vault::default()).expect_err("locked"); assert_eq!(refused.code, "approver_locked"); assert_eq!(refused.message, "This device is still waiting for a yes itself, so it can't approve. Please use another device of yours."); } // RULE (GETTING-IN.md): a scan of the new device's square code approves with no digits, sends the nonce it carries, // and lets the device in under the key its ask named, checked here against the commit. #[test] fn a_scan_of_the_right_screen_approves_and_lets_the_device_in() { let now = 1_800_000_000; let mac = Asking::new(7); let mut held = mac.held("cta_1", Some("mac-c"), now, false, false); held["device_kind"] = json!("mac"); let (door, exchange) = door_of([Reply::ok(&json!({"now": now, "asks": [held], "holds": true}).to_string()), Reply::ok(r#"{"ok":true}"#)]); let vault = Vault::default(); let scanned = cotton_core::vault::approval::scan_text("cta_1", &mac.nonce); let done = over(&door, "signin.approve", &json!({"askId": "cta_1", "scanned": scanned, "privateKey": b64(&[1u8; 32])}), 0, &vault).expect("approved"); assert_eq!(done["vault"], true); assert_eq!(done["said"], "Your Mac can open your things now."); let approve = exchange.nth(1); assert_eq!(approve.path, APPROVE); assert_eq!(body(&approve), json!({"ask_id": "cta_1", "scanned": b64(&mac.nonce)})); assert_eq!(vault.0.lock().unwrap().as_slice(), &[(b64(&mac.device), b64(&mac.vault), Some("mac-c".to_string()))]); } // RULE (GETTING-IN.md): a scan of any other screen (another ask, a forged nonce, not a Cotton code, a server that // swapped the device's key) approves nothing, sends nothing, and counts no wrong try. #[test] fn a_scan_of_any_other_screen_approves_nothing() { let now = 1_800_000_000; let mac = Asking::new(7); let tries = [ cotton_core::vault::approval::scan_text("cta_other", &mac.nonce), cotton_core::vault::approval::scan_text("cta_1", &[99u8; 32]), "https://cottondb.com/in#cta_1".to_string(), "482913".to_string(), ]; for scanned in tries { let (door, exchange) = door_of([Reply::ok(&json!({"now": now, "asks": [mac.held("cta_1", Some("mac-c"), now, false, false)]}).to_string())]); let vault = Vault::default(); let refused = over(&door, "signin.approve", &json!({"askId": "cta_1", "scanned": scanned, "privateKey": b64(&[1u8; 32])}), 0, &vault).expect_err("refused"); assert_eq!(refused.code, "scan_wrong"); assert_eq!(refused.message, "That's not the code for this request. Scan the one showing on your device."); assert_eq!(exchange.seen().len(), 1, "nothing sent past the look"); assert!(vault.0.lock().unwrap().is_empty()); } // The object relays another device key than the one the screen committed to: caught here. let mut swapped = mac.held("cta_1", Some("mac-c"), now, false, false); swapped["device_id"] = json!(b64(&Asking::new(30).device)); let (door, exchange) = door_of([Reply::ok(&json!({"now": now, "asks": [swapped]}).to_string())]); let scanned = cotton_core::vault::approval::scan_text("cta_1", &mac.nonce); assert_eq!(over(&door, "signin.approve", &json!({"askId": "cta_1", "scanned": scanned}), 0, &Vault::default()).expect_err("swapped").code, "scan_wrong"); assert_eq!(exchange.seen().len(), 1); } // RULE (GETTING-IN.md): the asking device says what it is, so the card can say "Your Mac". #[test] fn an_ask_says_what_kind_of_device_asks() { let me = key(7); let (_, sent) = asked(&me, ASK_ID, json!({"phone": "+919000005020", "deviceKind": "ipad"})); assert_eq!(sent["device_kind"], "ipad"); let (_, sent) = asked(&me, ASK_ID, json!({"phone": "+919000005020", "deviceKind": "toaster"})); assert!(["mac", "android", "iphone", "computer"].contains(&sent["device_kind"].as_str().unwrap()), "this build's own kind"); } // RULE (GETTING-IN.md): an ask three wrong codes ended says so, apart from a person's No. #[test] fn three_wrong_codes_are_told_apart_from_a_no() { let exchange = ScriptedExchange::new([Reply::ok(r#"{"state":"refused","why":"wrong"}"#), Reply::ok(r#"{"state":"refused"}"#)]); let me = key(7); assert_eq!(poll(&address(), exchange.as_ref(), &me, ASK_ID).expect("ended")["why"], "wrong"); assert_eq!(poll(&address(), exchange.as_ref(), &me, ASK_ID).expect("refused")["why"], Value::Null); } // ── the coordinator's rules, 22 Nov 2026: never Approved unless the key was handed over ───────── /// A phone that cannot open the key (`holds` refuses), or whose hand-over fails after the approval (`admit` refuses). struct Failing { holds: bool, } impl VaultAdmit for Failing { fn admit(&self, _: &str, _: &str, _: Option<&str>, _: &[u8; 32]) -> Result<(), MethodError> { Err(MethodError::new("write_failed", "the object refused the write")) } fn holds(&self, _: Option<&[u8; 32]>) -> Result { if self.holds { Ok(true) } else { Err(MethodError::new("key_needed", "Unlock this phone first, then tap Approve again.")) } } } // RULE: a phone that cannot open the key itself sends no approval at all: the new device is never approved by a phone // that could not hand it the key. #[test] fn a_phone_that_cannot_open_the_key_approves_nothing() { let now = 1_800_000_000; let pixel = Asking::new(7); let asks = json!({"now": now, "asks": [pixel.held("cta_1", Some("Pixel walk"), now, true, true)]}); let (door, exchange) = door_of([Reply::ok(&asks.to_string())]); let typed = shown_code(&pixel.code()); let refused = over(&door, "signin.approve", &json!({"askId": "cta_1", "code": typed}), 0, &Failing { holds: false }).expect_err("nothing approved"); assert_eq!(refused.code, "key_needed"); assert!(exchange.seen().iter().all(|seen| seen.path != APPROVE), "no approval was sent"); } // RULE: a hand-over that fails after the approval says so and never says Approved. #[test] fn a_failed_hand_over_is_said_and_never_called_approved() { let now = 1_800_000_000; let pixel = Asking::new(7); let mut held = pixel.held("cta_1", Some("Pixel walk"), now, true, true); held["device_kind"] = json!("mac"); let (door, _) = door_of([Reply::ok(&json!({"now": now, "asks": [held]}).to_string()), Reply::ok(r#"{"ok":true}"#)]); let typed = shown_code(&pixel.code()); let refused = over(&door, "signin.approve", &json!({"askId": "cta_1", "code": typed, "privateKey": b64(&[26u8; 32])}), 0, &Failing { holds: true }).expect_err("not handed over"); assert_eq!(refused.code, "not_handed"); assert_eq!(refused.message, "This phone couldn't pass your things to your Mac. Check this phone's connection, then ask again on your Mac."); assert!(!refused.message.contains("Approved")); } // RULE: an ask from an app that sent no key of its own cannot be handed one: told to update, nothing approved. #[test] fn an_ask_with_no_key_of_its_own_is_told_to_update_and_not_approved() { let now = 1_800_000_000; let pixel = Asking::new(7); let mut held = pixel.held("cta_1", Some("Pixel walk"), now, true, true); held["vault_key"] = Value::Null; held["device_kind"] = json!("android"); let (door, exchange) = door_of([Reply::ok(&json!({"now": now, "asks": [held]}).to_string())]); let code = pixel.code(); let typed = shown_code(&code); match over(&door, "signin.approve", &json!({"askId": "cta_1", "code": typed, "privateKey": b64(&[26u8; 32])}), 0, &Vault::default()) { Err(refused) => { assert!(refused.code == "update_app" || refused.code == "code_wrong" || refused.code == "not_compared", "{}", refused.code); assert!(exchange.seen().iter().all(|seen| seen.path != APPROVE), "no approval was sent"); } Ok(said) => panic!("approved an ask that cannot take the key: {said}"), } } // RULE (OWNER.md, 22 Nov 2026): a device that cannot hand over the key is offered no Approve, and says in one line why // and what to do. #[test] fn a_device_that_cannot_hand_over_the_key_says_why_with_no_button() { let now = 1_800_000_000; let mac = Asking::new(7); let mut held = mac.held("cta_1", Some("mac-c"), now, false, false); held["device_kind"] = json!("mac"); let (door, _) = door_of([Reply::ok(&json!({"now": now, "asks": [held], "holds": false}).to_string())]); let card = over(&door, "signin.asks", &json!({}), 0, &Vault::default()).expect("a card"); assert_eq!(card["waiting"], json!([]), "no Approve anywhere"); assert_eq!(card["cannot"]["title"], "Your Mac wants to sign in to your Cotton"); assert_eq!(card["cannot"]["line"], "This device can't open your things yet, so it can't say yes. Approve on another device that shows your things, or type your recovery code on your Mac."); assert!(card["cannot"].get("approve").is_none()); } // RULE (the getting-in ruling, 22 Nov 2026; GETTING-IN.md step 1): a second Cotton app on a phone where another one // already opens the person's things signs in with one tap, which also opens them. The tap never shows a waiting screen: // it opens, or the core's words say why over the number field. #[test] fn the_one_tap_says_who_and_what_to_do_when_it_fails() { let said = super::handoff(&json!({"phone": "+15550100412", "app": "Cotton Days"})).expect("words"); assert_eq!(said["line"], json!("You're signed in to Cotton Days on this phone.")); assert_eq!(said["button"], json!("Sign in as •••• 0412")); assert_eq!(said["failed"], json!("That didn't work from Cotton Days. Sign in with your number instead.")); }