Cotton code
110 lines · 6.0 KB · RustRaw
//! The passkey's rules against a scripted Worker: what each side sends, and//! what the Account list says. Every number, key and name is invented.use std::sync::Arc;use cotton_client::transport::object::ObjectAddress;use cotton_client::transport::scripted::{Reply, ScriptedExchange};use cotton_client::DeviceIdentity;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 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 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")}fn door_of(replies: impl IntoIterator<Item = Reply>) -> (ObjectDoor, Arc<ScriptedExchange>) {    let exchange = ScriptedExchange::new(replies);    (ObjectDoor { address: address(), exchange: exchange.clone(), credential: CREDENTIAL.to_string() }, exchange)}const SHEET: &str = r#"{"id":"AAEC","rawId":"AAEC","type":"public-key","response":{"clientDataJSON":"e30","authenticatorData":"AA","signature":"AA","userHandle":"AA"}}"#;// RULE: begin hands the sheet the Worker's request as it is, and carries no credential.#[test]fn begin_hands_the_sheet_the_workers_request() {    let exchange = ScriptedExchange::new([Reply::ok(r#"{"challenge_id":"ctp_1","request":{"challenge":"abc","rpId":"cottondb.example.test","userVerification":"required","allowCredentials":[]}}"#)]);    let begun = begin(&address(), exchange.as_ref()).expect("begun");    assert_eq!(begun["challengeId"], "ctp_1");    let request: Value = serde_json::from_str(begun["requestJson"].as_str().unwrap()).unwrap();    assert_eq!(request["rpId"], "cottondb.example.test");    let sent = exchange.only();    assert_eq!((sent.method.as_str(), sent.path.as_str()), ("POST", BEGIN));    assert_eq!(sent.header("authorization"), None);}// RULE: a sign-in sends the sheet's answer for this device's key, and hands over the credential and the number as a code sign-in does.#[test]fn a_sign_in_names_this_device_and_hands_over_the_credential() {    let me = Key(DeviceIdentity::from_secret(&[7u8; 32]).unwrap());    let exchange = ScriptedExchange::new([Reply::ok(&json!({"credential": "ctd_new", "person": {"phone": "+919000007001"}, "expires_in": 7776000, "database_id": DB, "host": SERVER}).to_string())]);    let signed = sign_in(&address(), exchange.as_ref(), &me, &json!({"challengeId": "ctp_1", "responseJson": SHEET})).expect("signed in");    assert_eq!((signed["credential"].clone(), signed["databaseId"].clone(), signed["phone"].clone()), (json!("ctd_new"), json!(DB), json!("+919000007001")));    let sent = body(&exchange.only());    assert_eq!(sent["challenge_id"], "ctp_1");    assert_eq!(sent["device_id"], me.device_id());    assert_eq!(sent["response"]["id"], "AAEC");    assert_eq!(credential_id(&sent["response"]), Some(vec![0, 1, 2]));}// RULE: a refused passkey reaches the shell by its code, and an answer that is not the sheet's JSON is refused before anything is sent.#[test]fn a_refusal_is_said_by_its_code() {    let me = Key(DeviceIdentity::from_secret(&[7u8; 32]).unwrap());    let exchange = ScriptedExchange::new([Reply::json(401, r#"{"code":"passkey_refused","message":"That passkey did not sign in here. Try another way."}"#)]);    assert_eq!(sign_in(&address(), exchange.as_ref(), &me, &json!({"challengeId": "ctp_1", "responseJson": SHEET})).expect_err("refused").code, "passkey_refused");    assert_eq!(sign_in(&address(), exchange.as_ref(), &me, &json!({"challengeId": "ctp_1", "responseJson": "not json"})).expect_err("refused").code, "bad_request");}// RULE: Account lists each passkey by its name and when it was last used, never its key, and says how many there are.#[test]fn the_list_says_each_passkey_and_when_it_was_used() {    let now = 1_800_000_000;    let listed = json!({"passkeys": [        {"id": "pk1", "name": "Pixel walk", "created_at": now - 10 * 86_400, "last_used_at": now - 86_400},        {"id": "pk2", "name": null, "created_at": now - 100, "last_used_at": null}    ]});    let (door, exchange) = door_of([Reply::ok(&listed.to_string())]);    let card = over(&door, "signin.passkeys", &json!({}), now).expect("a card");    assert_eq!(exchange.only().header("authorization"), Some(format!("Bearer {CREDENTIAL}").as_str()));    assert_eq!(card["line"], "2 passkeys sign you in on a new phone.");    assert_eq!(card["passkeys"][0]["when"], "Used 1 day ago");    assert_eq!(card["passkeys"][1]["name"], "A passkey");    assert_eq!(card["passkeys"][1]["when"], "Made today");    assert_eq!(card["passkeys"][0]["confirm"], "Pixel walk will no longer sign you in.");    let (door, _) = door_of([Reply::ok(r#"{"passkeys":[]}"#)]);    assert_eq!(over(&door, "signin.passkeys", &json!({}), now).unwrap()["line"], "Add a passkey to sign in on a new phone without a text.");}// RULE: Add sends the sheet's answer with the name; Remove sends the id; each says what happened.#[test]fn add_and_remove_send_what_the_object_needs() {    let (door, exchange) = door_of([Reply::ok(r#"{"id":"pk1"}"#), Reply::ok(r#"{"ok":true}"#)]);    let added = over(&door, "signin.passkeyAdd", &json!({"responseJson": SHEET, "name": "Pixel walk"}), 0).expect("added");    assert_eq!(added["said"], "Passkey added. A new phone can sign in with it.");    let removed = over(&door, "signin.passkeyRemove", &json!({"id": "pk1"}), 0).expect("removed");    assert_eq!(removed["said"], "Passkey removed.");    let seen = exchange.seen();    assert_eq!((seen[0].path.as_str(), body(&seen[0])["name"].clone(), body(&seen[0])["response"]["id"].clone()), (PASSKEYS, json!("Pixel walk"), json!("AAEC")));    assert_eq!((seen[1].path.as_str(), body(&seen[1])), (REMOVE, json!({"id": "pk1"})));}