Cotton code
243 lines · 14.8 KB · RustRaw
//! `keys.*` on a Cotton Keys phone: every kind kept sealed, a login's//! history, favourites, one-time codes, the generator, Health, the breach//! check's two halves, AutoFill's answers, the bin and the exports. Every//! value is invented and none is printed.use serde_json::{json, Value};use cotton_core::keys::totp::Totp;use super::over;use crate::handle::CottonHandle;use crate::phone::passwords::tests::{exec, lent, phone, row, wrapped};fn answer(handle: &CottonHandle, method: &str, request: &Value) -> Result<Value, crate::methods::MethodError> {    if method.starts_with("password.") {        crate::phone::passwords::over(&handle.client(), method, request)    } else {        over(&handle.client(), method, request)    }}fn call(handle: &CottonHandle, method: &str, request: Value) -> Value {    answer(handle, method, &request).unwrap_or_else(|error| panic!("{method}: {} {}", error.code, error.message))}fn refused(handle: &CottonHandle, method: &str, request: Value) -> String {    answer(handle, method, &request).err().map(|error| error.code).unwrap_or_else(|| panic!("{method} answered"))}fn add(handle: &CottonHandle, mut request: Value) -> String {    request["privateKey"] = lent();    call(handle, "keys.add", request)["id"].as_str().unwrap().to_string()}fn login(handle: &CottonHandle, site: &str, user: &str, password: &str) -> String {    add(handle, json!({"kind": "login", "site": site, "username": user, "fields": {"password": password}}))}const RFC_SECRET: &str = "otpauth://totp/Invented:ada?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ&issuer=Invented";#[test]fn every_kind_is_kept_sealed_and_reveals_its_fields() {    let (_dir, handle) = phone();    wrapped(&handle);    let cases = [        json!({"kind": "login", "site": "https://mail.invented.test/", "username": "ada", "fields": {"password": "SYNTHETIC-1", "urls": "https://webmail.invented.test"}}),        json!({"kind": "code", "fields": {"secret": RFC_SECRET}}),        json!({"kind": "note", "name": "Invented note", "fields": {"body": "SYNTHETIC body"}}),        json!({"kind": "card", "name": "Invented card", "fields": {"number": "0000111122223333", "expiry": "04/29", "cvv": "000"}}),        json!({"kind": "identity", "name": "Invented passport", "fields": {"number": "X000", "id_type": "passport"}}),        json!({"kind": "wifi", "name": "invented-home", "fields": {"password": "SYNTHETIC-wifi", "security": "WPA3"}}),        json!({"kind": "address", "name": "Home", "fields": {"address": "1 Invented Lane", "full_name": "A Name"}}),    ];    for case in cases {        let kind = case["kind"].as_str().unwrap().to_string();        let id = add(&handle, case.clone());        let stored = row(&handle, &id);        assert_eq!(stored["kind"], kind);        assert!(stored["value_enc"].as_str().unwrap().starts_with("v2:"), "{kind} sealed v2");        assert!(stored["hint"].is_null());        let shown = call(&handle, "password.reveal", json!({"id": id, "privateKey": lent()}));        for (field, value) in case["fields"].as_object().unwrap() {            assert_eq!(&shown["payload"][field], value, "{kind}.{field} reads back");        }    }    let code = row(&handle, &call(&handle, "keys.codes", json!({"privateKey": lent()}))["codes"][0]["id"].as_str().unwrap().to_string());    assert_eq!(code["name"], "Invented", "a code with no name takes its issuer's");    assert_eq!(refused(&handle, "keys.add", json!({"kind": "card", "name": "x", "fields": {"number": "1", "pin": "0"}, "privateKey": lent()})), "bad_request", "a field the kind does not declare");    assert_eq!(refused(&handle, "keys.add", json!({"kind": "code", "name": "x", "fields": {"secret": "otpauth://hotp/x?secret=GEZD"}, "privateKey": lent()})), "bad_code");    assert_eq!(refused(&handle, "keys.add", json!({"kind": "wifi", "name": "x", "fields": {}, "privateKey": lent()})), "bad_request", "the primary field is required");    login(&handle, "dup.invented.test", "ada", "SYNTHETIC-a");    assert_eq!(refused(&handle, "keys.add", json!({"kind": "login", "site": "dup.invented.test", "username": "ada", "fields": {"password": "SYNTHETIC-b"}, "privateKey": lent()})), "password_held");}#[test]fn a_changed_password_goes_to_its_history_newest_first() {    let (_dir, handle) = phone();    wrapped(&handle);    let id = login(&handle, "bank.invented.test", "ada", "SYNTHETIC-0");    assert!(row(&handle, &id)["changed_at"].is_string());    for n in 1..=12 {        let answer = call(&handle, "keys.change", json!({"id": id, "fields": {"password": format!("SYNTHETIC-{n}")}, "privateKey": lent()}));        assert_eq!(answer["passwordChanged"], true);    }    let unchanged = call(&handle, "keys.change", json!({"id": id, "fields": {"notes": "SYNTHETIC note"}, "privateKey": lent()}));    assert_eq!(unchanged["passwordChanged"], false);    let history = call(&handle, "keys.history", json!({"id": id, "privateKey": lent()}))["history"].clone();    let passwords: Vec<&str> = history.as_array().unwrap().iter().map(|past| past["password"].as_str().unwrap()).collect();    assert_eq!(passwords.len(), 10);    assert_eq!(passwords[0], "SYNTHETIC-11");    assert_eq!(passwords[9], "SYNTHETIC-2");    let stored = row(&handle, &id);    assert!(stored["history_enc"].as_str().unwrap().starts_with("v2:") && !stored["history_enc"].as_str().unwrap().contains("SYNTHETIC"));    let shown = call(&handle, "password.reveal", json!({"id": id, "privateKey": lent()}));    assert_eq!(shown["payload"]["password"], "SYNTHETIC-12");    assert_eq!(shown["payload"]["notes"], "SYNTHETIC note");    // a plain change needs no vault    call(&handle, "keys.change", json!({"id": id, "name": "Invented Bank"}));    assert_eq!(row(&handle, &id)["name"], "Invented Bank");}#[test]fn favourites_codes_and_the_code_after_a_fill() {    let (_dir, handle) = phone();    wrapped(&handle);    let id = add(&handle, json!({"kind": "login", "site": "invented.test", "username": "ada", "fields": {"password": "SYNTHETIC-1", "totp": RFC_SECRET}}));    call(&handle, "keys.favourite", json!({"id": id, "on": true}));    assert!(row(&handle, &id)["favourite_at"].is_string());    call(&handle, "keys.favourite", json!({"id": id, "on": false}));    assert!(row(&handle, &id)["favourite_at"].is_null());    let totp = Totp::parse(RFC_SECRET).unwrap();    let now = handle.client().now().timestamp() as u64;    let code = call(&handle, "keys.code", json!({"id": id, "privateKey": lent()}));    let shown = code["code"].as_str().unwrap();    assert!(shown == totp.code_at(now) || shown == totp.code_at(now + 1), "the code for this second");    assert!((1..=30).contains(&code["secondsLeft"].as_u64().unwrap()));    assert_eq!(code["period"], 30);    let copied = call(&handle, "keys.afterFill", json!({"id": id, "privateKey": lent()}));    assert_eq!(copied["copies"].as_str().unwrap().len(), 6);    let plain = login(&handle, "plain.invented.test", "ada", "SYNTHETIC-2");    assert!(call(&handle, "keys.afterFill", json!({"id": plain, "privateKey": lent()}))["copies"].is_null());    assert_eq!(refused(&handle, "keys.code", json!({"id": plain, "privateKey": lent()})), "no_code");}#[test]fn generate_and_strength_are_answered_by_the_core() {    let (_dir, handle) = phone();    let made = call(&handle, "keys.generate", json!({}));    assert_eq!(made["password"].as_str().unwrap().chars().count(), 20);    assert_eq!(made["strength"]["word"], "strong");    let words = call(&handle, "keys.generate", json!({"recipe": {"words": {"count": 5, "separator": "-"}}}));    assert_eq!(words["password"].as_str().unwrap().split('-').count(), 5);    assert!(words["bits"].as_f64().unwrap() > 64.0);    assert_eq!(refused(&handle, "keys.generate", json!({"recipe": {"words": {"count": 1}}})), "bad_recipe");    assert_eq!(call(&handle, "keys.strength", json!({"password": "password"}))["word"], "very_weak");}#[test]fn health_names_weak_reused_and_old_and_the_breach_check_sends_five_characters() {    let (_dir, handle) = phone();    wrapped(&handle);    let weak = login(&handle, "a.invented.test", "ada", "password");    let one = login(&handle, "b.invented.test", "ada", "Gk7#qP2!xW9$mR4@tZ8&");    let two = login(&handle, "c.invented.test", "ada", "Gk7#qP2!xW9$mR4@tZ8&");    let old = login(&handle, "d.invented.test", "ada", "Hn3$wQ8!rT6@yU1#iO4%");    exec(&handle, "UPDATE cotton_secrets SET changed_at = '2024-01-01T00:00:00.000Z' WHERE id = ?", &[&old]);    let health = call(&handle, "keys.health", json!({"privateKey": lent()}));    let by_id = |id: &str| health["findings"].as_array().unwrap().iter().find(|finding| finding["id"] == id).cloned();    assert_eq!(by_id(&weak).unwrap()["weak"], true);    assert_eq!(by_id(&one).unwrap()["reused_with"], json!([two]));    assert_eq!(by_id(&old).unwrap()["old"], true);    assert_eq!(health["counts"], json!({"weak": 1, "reused": 2, "old": 1}));    let prefixes = call(&handle, "keys.breachPrefixes", json!({"privateKey": lent()}));    let list: Vec<&str> = prefixes["prefixes"].as_array().unwrap().iter().map(|p| p.as_str().unwrap()).collect();    assert!(list.contains(&"5BAA6") && list.iter().all(|prefix| prefix.len() == 5), "five characters each, nothing else");    assert_eq!(list.len(), 3, "a reused password is asked once");    assert!(prefixes["addresses"][0].as_str().unwrap().starts_with("https://api.pwnedpasswords.com/range/"));    let ranges = json!({"5BAA6": "1E4C9B93F3F0682250B6CF8331B7EE68FD8:52256179\r\n"});    let checked = call(&handle, "keys.breachCheck", json!({"ranges": ranges, "privateKey": lent()}));    assert_eq!(checked["breached"], json!([{"id": weak, "name": "a.invented.test", "count": 52256179}]));    assert_eq!(checked["unread"].as_array().unwrap().len(), 2, "the prefixes with no answer are named");}#[test]fn autofill_asks_the_core_which_logins_fill_and_what_to_offer() {    let (_dir, handle) = phone();    wrapped(&handle);    let exact = login(&handle, "login.invented.co.uk", "ada", "SYNTHETIC-1");    let site = login(&handle, "invented.co.uk", "bob", "SYNTHETIC-2");    login(&handle, "invented.co.uk.evil.test", "ada", "SYNTHETIC-3");    let found = call(&handle, "keys.forService", json!({"service": "https://login.invented.co.uk/x", "privateKey": lent()}));    let ids: Vec<&str> = found["logins"].as_array().unwrap().iter().map(|login| login["id"].as_str().unwrap()).collect();    assert_eq!(ids, [exact.as_str(), site.as_str()]);    assert_eq!(found["logins"][0]["match"], "exact");    assert_eq!(found["logins"][1]["match"], "same_site");    assert_eq!(found["logins"][0]["opens"], true);    // Credential Manager's allowed user names, and a fill that can hand the password over.    let only_bob = call(&handle, "keys.forService", json!({"service": "invented.co.uk", "users": ["bob"], "fillable": true}));    assert_eq!(only_bob["logins"].as_array().unwrap().iter().map(|login| login["id"].as_str().unwrap()).collect::<Vec<_>>(), [site.as_str()]);    // An Android app with no web domain asks by its application id, read back to front by the public suffix.    let app = call(&handle, "keys.forService", json!({"app": "uk.co.invented.bank"}));    assert_eq!(app["service"], "invented.co.uk");    assert_eq!(app["logins"].as_array().unwrap().len(), 2);    let refused = over(&handle.client(), "keys.forService", &json!({"app": "android"})).unwrap_err();    assert_eq!(refused.code, "bad_request");    let offer = |user: &str, password: &str| call(&handle, "keys.offerSave", json!({"site": "https://login.invented.co.uk/", "username": user, "password": password, "privateKey": lent()}));    assert_eq!(offer("ada", "SYNTHETIC-new"), json!({"offer": "update", "id": exact}));    assert_eq!(offer("ada", "SYNTHETIC-1"), json!({"offer": "nothing", "id": exact}));    assert_eq!(offer("cy", "SYNTHETIC-x"), json!({"offer": "save", "site": "login.invented.co.uk"}));    let used = call(&handle, "keys.used", json!({"id": exact}));    assert_eq!(used["uses"], 1);    assert_eq!(call(&handle, "keys.used", json!({"id": exact}))["uses"], 2);    assert!(row(&handle, &exact)["last_used_at"].is_string());    add(&handle, json!({"kind": "login", "site": "shop.invented.test", "username": "ada", "fields": {"password": "SYNTHETIC-4", "totp": RFC_SECRET}}));    let identities = call(&handle, "keys.identities", json!({"privateKey": lent()}));    assert_eq!(identities["passwords"].as_array().unwrap().len(), 4);    assert_eq!(identities["codes"], json!([{"id": identities["codes"][0]["id"], "service": "shop.invented.test", "label": "ada"}]));}#[test]fn the_bin_keeps_thirty_days_and_restores() {    let (_dir, handle) = phone();    wrapped(&handle);    let old = login(&handle, "old.invented.test", "ada", "SYNTHETIC-1");    let recent = login(&handle, "new.invented.test", "ada", "SYNTHETIC-2");    for id in [&old, &recent] {        call(&handle, "password.remove", json!({"id": id}));    }    exec(&handle, "UPDATE cotton_secrets SET trashed_at = '2026-01-01T00:00:00.000Z' WHERE id = ?", &[&old]);    assert_eq!(call(&handle, "keys.emptyBin", json!({}))["erased"], 1);    let gone = handle.client().with_writer(|replica| Ok(replica.driver.get("SELECT id FROM cotton_secrets WHERE id = ?", &[old.clone().into()]).unwrap().is_none())).unwrap();    assert!(gone, "past thirty days it is gone");    call(&handle, "keys.restore", json!({"id": recent}));    assert!(row(&handle, &recent)["trashed_at"].is_null());}#[test]fn the_exports_carry_everything_behind_the_unlock_with_the_warning() {    let (_dir, handle) = phone();    wrapped(&handle);    login(&handle, "mail.invented.test", "ada", "SYNTHETIC-1");    add(&handle, json!({"kind": "card", "name": "Invented card", "fields": {"number": "0000111122223333"}}));    let csv = call(&handle, "keys.exportCsv", json!({"privateKey": lent()}));    assert!(csv["text"].as_str().unwrap().starts_with("Title,URL,Username,Password,Notes,OTPAuth\n"));    assert_eq!(csv["leftOut"], 1);    assert!(csv["warning"].as_str().unwrap().contains("in the clear"));    let back = cotton_core::keys::password_import::read_csv(csv["text"].as_str().unwrap()).unwrap();    assert_eq!(back.passwords.len(), 1);    let cxf = call(&handle, "keys.exportCxf", json!({"privateKey": lent()}));    let read = cotton_core::keys::cxf::read(cxf["text"].as_str().unwrap()).unwrap();    assert_eq!(read.passwords.len(), 1);    assert_eq!(refused(&handle, "keys.exportCsv", json!({})), "vault_locked", "never without the unlock");    // AUDIT E (a borrowed phone): the vault held open is not enough; an export asks the phone's lock again.    crate::methods::dispatch(&handle, "vault.unlock", &json!({"privateKey": lent()})).expect("unlocked");    assert_eq!(refused(&handle, "keys.exportCsv", json!({})), "vault_locked", "an unlock held does not export");    assert_eq!(refused(&handle, "keys.exportCxf", json!({})), "vault_locked");    // (recovery.* take the same fresh unlock, `recovery::with_fresh_vmk`; this copy is signed out, so they refuse sooner.)}