Cotton code
597 lines · 33.0 KB · RustRaw
//! Cotton Secrets on two phones over one in-memory network of objects that//! keeps the routes CONTRACT.md "The Worker" names: notes, shares, the value//! counted at each fetch, take back, asks. Every number, name and key invented.//!//! The network is the executable half of the Worker's spec: it routes only//! ciphertext, and the last test reads everything it holds to show that no//! name, value or note of a secret is in it.use std::collections::HashMap;use std::io::Read;use std::sync::{Arc, Mutex};use cotton_client::transport::object::ObjectAddress;use cotton_client::transport::wire::Origin;use cotton_client::transport::{http1::Http1Request, Answer, Exchange};use serde_json::{json, Value};use super::call;use crate::handle::CottonHandle;use crate::phone::passwords::tests::{lent, phone, wrapped};use crate::phone::personal_object::ObjectDoor;const GIVER: &str = "+15550100001";const HOLDER: &str = "+15550100002";const STRANGER: &str = "+15550100009";const NOW: i64 = 1_764_072_000_000; // 25 Nov 2026, 12:00 UTC#[derive(Debug, Default)]struct Object {    key: Option<String>,    notes: HashMap<String, String>,    /// Shares this object's owner gave: share → (to, delivered_at, opens, last_open, until).    out: HashMap<String, Value>,    /// Shares held for this owner: share → { from, card, value, version, until, may_copy }.    held: HashMap<String, Value>,    asks_in: HashMap<String, Value>,    people: Vec<String>,}/// Every object on the network, by owner's number.#[derive(Debug, Default)]struct Net {    objects: Mutex<HashMap<String, Object>>,    /// The key the network hands out for a number, when a test makes it lie.    lie: Mutex<Option<(String, String)>>,}impl Net {    fn route(&self, me: &str, method: &str, path: &str, body: &Value) -> (u16, Value) {        let mut all = self.objects.lock().unwrap();        let (path, query) = path.split_once('?').unwrap_or((path, ""));        let path = &path[path.find("/v1/").unwrap_or(0)..];        match (method, path) {            ("POST", "/v1/send/key") => {                all.entry(me.into()).or_default().key = body["key"].as_str().map(str::to_string);                (200, json!({ "ok": true }))            }            ("GET", "/v1/send/key") => {                let number = query.trim_start_matches("number=").replace("%2B", "+");                if let Some((lied_for, key)) = self.lie.lock().unwrap().clone() {                    if lied_for == number {                        return (200, json!({ "key": key, "me": me }));                    }                }                let accepted = all.get(me).is_some_and(|o| o.people.contains(&number)) && all.get(&number).is_some_and(|o| o.people.contains(&me.to_string()));                let key = if accepted { all.get(&number).and_then(|o| o.key.clone()) } else { None };                (200, json!({ "key": key.unwrap_or_else(|| cotton_core::seal::share::key_text(&[9u8; 32])), "me": me }))            }            // `waiting`: they have not added this person back (src/chat/chat.ts peopleOf), as the object says it.            ("GET", "/v1/send/people") => (200, json!({ "people": all.get(me).map(|o| o.people.iter().map(|n| json!({ "number": n, "waiting": !all.get(n).is_some_and(|them| them.people.iter().any(|back| back == me)) })).collect::<Vec<_>>()).unwrap_or_default() })),            ("GET", "/v1/secret/note") => (200, json!({ "notes": all.get(me).map(|o| o.notes.iter().map(|(k, b)| json!({ "key": k, "box": b })).collect::<Vec<_>>()).unwrap_or_default() })),            ("PUT", "/v1/secret/note") => {                all.entry(me.into()).or_default().notes.insert(body["key"].as_str().unwrap().into(), body["box"].as_str().unwrap().into());                (200, json!({ "ok": true }))            }            ("POST", "/v1/secret/share") => {                let to = body["to"].as_str().unwrap().to_string();                let share = body["share"].as_str().unwrap().to_string();                all.entry(me.into()).or_default().out.insert(share.clone(), json!({ "share": share, "to": to, "delivered_at": NOW, "opens": 0, "until": body["until"] }));                all.entry(to).or_default().held.insert(share, json!({ "from": me, "card": body["card"], "value": body["value"], "version": body["version"], "until": body["until"], "may_copy": body["may_copy"] }));                (200, json!({ "ok": true }))            }            ("POST", "/v1/secret/share/update") => {                let share = body["share"].as_str().unwrap();                let to = all[me].out[share]["to"].as_str().unwrap().to_string();                if let Some(held) = all.get_mut(&to).and_then(|o| o.held.get_mut(share)) {                    held["value"] = body["value"].clone();                    held["version"] = body["version"].clone();                }                (200, json!({ "ok": true }))            }            ("POST", "/v1/secret/share/take") => {                let share = body["share"].as_str().unwrap();                let to = all[me].out[share]["to"].as_str().unwrap().to_string();                all.get_mut(&to).unwrap().held.remove(share);                all.get_mut(me).unwrap().out.get_mut(share).unwrap()["state"] = json!("taken");                (200, json!({ "ok": true }))            }            ("GET", "/v1/secret/share/out") => (200, json!({ "shares": all.get(me).map(|o| o.out.values().cloned().collect::<Vec<_>>()).unwrap_or_default() })),            ("GET", "/v1/secret/share/in") => (200, json!({ "shares": all.get(me).map(|o| o.held.iter().map(|(s, h)| json!({ "share": s, "from": h["from"], "card": h["card"], "until": h["until"], "may_copy": h["may_copy"] })).collect::<Vec<_>>()).unwrap_or_default() })),            ("POST", "/v1/secret/share/value") => {                let share = body["share"].as_str().unwrap();                let Some(held) = all.get(me).and_then(|o| o.held.get(share)).cloned() else { return (404, json!({ "code": "share_gone", "message": "gone" })) };                let from = held["from"].as_str().unwrap().to_string();                if let Some(out) = all.get_mut(&from).and_then(|o| o.out.get_mut(share)) {                    out["opens"] = json!(out["opens"].as_u64().unwrap_or(0) + 1);                    out["last_open"] = json!(NOW);                }                (200, json!({ "value": held["value"], "version": held["version"] }))            }            ("POST", "/v1/secret/share/drop") => {                all.get_mut(me).unwrap().held.remove(body["share"].as_str().unwrap());                (200, json!({ "ok": true }))            }            ("POST", "/v1/secret/ask") => {                let to = body["to"].as_str().unwrap().to_string();                all.entry(to).or_default().asks_in.insert(body["ask"].as_str().unwrap().into(), json!({ "ask": body["ask"], "from": me, "box": body["box"], "state": "waiting" }));                (200, json!({ "ok": true }))            }            ("GET", "/v1/secret/ask/in") => (200, json!({ "asks": all.get(me).map(|o| o.asks_in.values().cloned().collect::<Vec<_>>()).unwrap_or_default() })),            ("POST", "/v1/secret/ask/answer") => {                if let Some(ask) = all.get_mut(me).and_then(|o| o.asks_in.get_mut(body["ask"].as_str().unwrap())) {                    ask["state"] = body["state"].clone();                }                (200, json!({ "ok": true }))            }            ("POST", "/v1/secret/ask/withdraw") => {                let id = body["ask"].as_str().unwrap().to_string();                for object in all.values_mut() {                    if object.asks_in.get(&id).is_some_and(|ask| ask["from"] == me) {                        object.asks_in.get_mut(&id).unwrap()["state"] = json!("withdrawn");                    }                }                (200, json!({ "ok": true }))            }            ("GET", "/v1/secret/ask/out") => (200, json!({ "asks": all.values().flat_map(|o| o.asks_in.values()).filter(|ask| ask["from"] == me).map(|ask| json!({ "ask": ask["ask"], "state": ask["state"] })).collect::<Vec<_>>() })),            other => (404, json!({ "code": "no_route", "message": format!("{other:?}") })),        }    }    /// Everything the network holds, as text: what a server could read.    fn everything(&self) -> String {        format!("{:?}", self.objects.lock().unwrap())    }}#[derive(Debug)]struct Door {    net: Arc<Net>,    me: String,}struct Answered {    status: u16,    body: std::io::Cursor<Vec<u8>>,}impl Read for Answered {    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {        self.body.read(buf)    }}impl Answer for Answered {    fn status(&self) -> u16 {        self.status    }    fn header(&self, name: &str) -> Option<String> {        name.eq_ignore_ascii_case("content-type").then(|| "application/json".into())    }    fn content_length(&self) -> Option<u64> {        Some(self.body.get_ref().len() as u64)    }    fn set_read_timeout(&mut self, _: std::time::Duration) -> std::io::Result<()> {        Ok(())    }}impl Exchange for Door {    fn send(&self, _: &Origin, request: &Http1Request<'_>, _: std::time::Duration) -> Result<Box<dyn Answer>, String> {        let body: Value = request.body.and_then(|b| serde_json::from_slice(b).ok()).unwrap_or(Value::Null);        let (status, answer) = self.net.route(&self.me, request.method, request.path, &body);        Ok(Box::new(Answered { status, body: std::io::Cursor::new(answer.to_string().into_bytes()) }))    }    fn send_stream(&self, origin: &Origin, request: &Http1Request<'_>, body: &mut dyn Read, length: u64, ceiling: std::time::Duration) -> Result<Box<dyn Answer>, String> {        let mut bytes = Vec::new();        body.take(length).read_to_end(&mut bytes).map_err(|e| e.to_string())?;        self.send(origin, &Http1Request { body: Some(&bytes), headers: request.headers.clone(), ..*request }, ceiling)    }}struct Two {    net: Arc<Net>,    _dirs: (tempfile::TempDir, tempfile::TempDir),    giver: CottonHandle,    holder: CottonHandle,}fn on_net(handle: &CottonHandle, net: &Arc<Net>, number: &str) {    let door = ObjectDoor { address: ObjectAddress::open("https://cottondb.example.test").unwrap(), exchange: Arc::new(Door { net: net.clone(), me: number.into() }), credential: "ctd_11111111-1111-4111-8111-111111111111_test-credential".into() };    handle.client().set_object_door(Some(Arc::new(door)));    let mut bytes = [0u8; 32];    rand::RngCore::fill_bytes(&mut rand::rngs::OsRng, &mut bytes);    let client = handle.client();    client.data_keys().hold(&client.current_database().unwrap(), &cotton_core::seal::DataKey::from_bytes(bytes));}/// Two people who accepted each other in Comms, each with a phone on the network.fn two() -> Two {    let net = Arc::new(Net::default());    let (gd, giver) = phone();    let (hd, holder) = phone();    wrapped(&giver);    on_net(&giver, &net, GIVER);    on_net(&holder, &net, HOLDER);    {        let mut all = net.objects.lock().unwrap();        all.entry(GIVER.into()).or_default().people = vec![HOLDER.into()];        all.entry(HOLDER.into()).or_default().people = vec![GIVER.into()];        all.entry(STRANGER.into()).or_default();    }    // Each phone posts its sharing key the first time it needs it.    ask(&giver, "secrets.people", json!({}));    ask(&holder, "secrets.people", json!({}));    Two { net, _dirs: (gd, hd), giver, holder }}fn ask(handle: &CottonHandle, method: &str, request: Value) -> Value {    call(&handle.client(), method, &request).unwrap_or_else(|error| panic!("{method}: {} {}", error.code, error.message))}fn refused(handle: &CottonHandle, method: &str, request: Value) -> String {    call(&handle.client(), method, &request).expect_err(method).code}fn add(handle: &CottonHandle, mut request: Value) -> String {    request["privateKey"] = lent();    crate::phone::keys::over(&handle.client(), "keys.add", &request).expect("keys.add")["id"].as_str().unwrap().to_string()}fn token(two: &Two) -> String {    add(&two.giver, json!({"kind": "api_key", "name": "Invented deploy key", "fields": {"key": "sk_test_SYNTHETIC00000004f2a"}}))}fn checked(two: &Two) {    ask(&two.giver, "secrets.check.confirm", json!({ "number": HOLDER }));}fn share(two: &Two, id: &str, may: &str) -> String {    ask(&two.giver, "secrets.share", json!({ "id": id, "number": HOLDER, "may": may, "until": "week", "privateKey": lent() }))["share"].as_str().unwrap().to_string()}// RULE: Secrets opens only on a phone with a passcode (DECISIONS.md question 14), said in words.#[test]fn the_gate_opens_only_with_a_passcode() {    let open = call(&phone().1.client(), "secrets.gate", &json!({ "passcode": true })).unwrap();    assert_eq!(open["open"], true);    let shut = call(&phone().1.client(), "secrets.gate", &json!({ "passcode": false })).unwrap();    assert_eq!(shut["open"], false);    assert_eq!(shut["title"], "Set a screen lock first");    assert_eq!(shut["act"]["platform"], "screen_lock_settings");}// RULE (S1): both phones show the same six words; a share waits for the check, and a key that changes after it pauses every share.#[test]fn a_person_is_checked_once_and_a_changed_key_pauses_sharing() {    let two = two();    let id = token(&two);    let mine = ask(&two.giver, "secrets.check", json!({ "number": HOLDER }));    let theirs = ask(&two.holder, "secrets.check", json!({ "number": GIVER }));    assert_eq!(mine["words"], theirs["words"], "the same six words on both phones");    assert_eq!(mine["square"]["text"], mine["qr"], "the square code carries the check code");    assert_eq!(mine["square"]["rows"].as_array().unwrap().len() as u64, mine["square"]["size"].as_u64().unwrap());    assert_eq!(mine["checked"], false);    assert_eq!(refused(&two.giver, "secrets.share", json!({ "id": id, "number": HOLDER, "privateKey": lent() })), "not_checked");    // Scanning their code pins the key the network answers for them.    let scanned = ask(&two.giver, "secrets.check.scan", json!({ "code": theirs["qr"] }));    assert_eq!(scanned["checked"], true);    assert_eq!(ask(&two.giver, "secrets.check", json!({ "number": HOLDER }))["checked"], true);    // The network starts handing out another key for them.    *two.net.lie.lock().unwrap() = Some((HOLDER.into(), cotton_core::seal::share::key_text(&[44u8; 32])));    let after = ask(&two.giver, "secrets.check", json!({ "number": HOLDER }));    assert_eq!(after["changed"], true);    assert!(after["changedLine"].as_str().unwrap().contains("paused"));    assert_eq!(refused(&two.giver, "secrets.share", json!({ "id": id, "number": HOLDER, "privateKey": lent() })), "key_changed", "a lying server gets nothing");    // And a code scanned from the real phone does not match the lie.    let mismatch = ask(&two.giver, "secrets.check.scan", json!({ "code": theirs["qr"] }));    assert_eq!(mismatch["checked"], false);}// RULE: only your people, and never a passkey.#[test]fn a_share_goes_only_to_your_people() {    let two = two();    let id = token(&two);    checked(&two);    assert_eq!(refused(&two.giver, "secrets.share", json!({ "id": id, "number": STRANGER, "privateKey": lent() })), "not_your_people");    assert_eq!(refused(&two.giver, "secrets.share", json!({ "id": id, "number": HOLDER, "may": "pass_on", "privateKey": lent() })), "bad_request", "no passing on");}// RULE (the Android Secrets walk, 26 Nov 2026): one who has not added this person back in Comms is on People saying// so, is not offered in Share, and a share or an ask to them is refused in words; the object would have dropped it// and answered ok, so the giver's share reached no one and said nothing.#[test]fn one_who_has_not_added_you_back_waits_and_nothing_goes_to_them() {    let two = two();    two.net.objects.lock().unwrap().entry(HOLDER.into()).or_default().people.clear();    let id = token(&two);    let people = ask(&two.giver, "secrets.people", json!({}));    let row = &people["people"][0];    assert_eq!(row["accepted"], false, "{row}");    assert!(row["line"].as_str().unwrap().starts_with("Waiting for "), "{row}");    let plan = ask(&two.giver, "secrets.share.plan", json!({ "id": id }));    assert_eq!(plan["people"], json!([]), "not offered in Share");    let err = crate::methods::dispatch(&two.giver, "secrets.share", &json!({ "id": id, "number": HOLDER, "privateKey": lent() })).expect_err("refused");    assert_eq!(err.code, "not_accepted");    assert!(err.message.contains("hasn't added you back in Comms yet"), "{}", err.message);    assert_eq!(refused(&two.giver, "secrets.ask", json!({ "number": HOLDER, "text": "the invented wifi password" })), "not_accepted");    // Once they add back, all of it stands again.    two.net.objects.lock().unwrap().entry(HOLDER.into()).or_default().people = vec![GIVER.into()];    assert_eq!(ask(&two.giver, "secrets.people", json!({}))["people"][0]["accepted"], true);}// RULE: the holder sees only the fields the giver's secret holds, with its user name and site (launch-ios's walk,// 25 Nov 2026: a login with a password alone showed Notes, One-time code and Other websites sealed, all empty).#[test]fn a_shared_login_names_only_the_fields_it_holds() {    let two = two();    let id = add(&two.giver, json!({"kind": "login", "name": "Invented Mail", "site": "mail.invented.test", "username": "ada@invented.test", "fields": {"password": "SYNTHETIC-pass-0001"}}));    checked(&two);    let made = share(&two, &id, "see");    let one = ask(&two.holder, "secrets.shared", json!({ "share": made }));    let keys: Vec<&str> = one["fields"].as_array().unwrap().iter().filter_map(|f| f["key"].as_str()).collect();    assert_eq!(keys, vec!["password"], "only the password is named");    assert_eq!(one["username"], "ada@invented.test");    assert_eq!(one["site"], "mail.invented.test");    assert_eq!(one["plain"][0]["label"], "User name");    assert_eq!(one["plain"][0]["value"], "ada@invented.test");    assert_eq!(one["plain"][1]["label"], "Website");}// RULE: the holder sees the card at once and the value only at a fetch the server counts; the giver sees each open.#[test]fn a_shared_secret_opens_on_the_holders_phone_and_each_open_is_counted() {    let two = two();    let id = token(&two);    checked(&two);    let made = share(&two, &id, "copy");    let holders = ask(&two.giver, "secrets.holders", json!({ "id": id }));    assert_eq!(holders["holders"][0]["state"], "holds");    assert!(holders["holders"][0]["line"].as_str().unwrap().contains("received, not opened"));    let inbox = ask(&two.holder, "secrets.inbox", json!({}));    assert_eq!(inbox["rows"][0]["title"], "Invented deploy key");    assert_eq!(inbox["rows"][0]["group"], "developer");    let one = ask(&two.holder, "secrets.shared", json!({ "share": made }));    assert_eq!(one["mayCopy"], true);    assert!(!one.to_string().contains("SYNTHETIC"), "the card holds no value");    assert_eq!(one["fields"][0]["label"], "API key", "each field named as the secret's own page names it");    let field = ask(&two.holder, "secrets.shared.field", json!({ "share": made, "field": "key" }));    assert_eq!(field["value"], "sk_test_SYNTHETIC00000004f2a");    assert_eq!(field["clearAfter"], 30);    ask(&two.holder, "secrets.shared.field", json!({ "share": made, "field": "key" }));    let holders = ask(&two.giver, "secrets.holders", json!({ "id": id }));    assert_eq!(holders["holders"][0]["opens"], 2);    assert!(holders["holders"][0]["line"].as_str().unwrap().contains("opened 2 times"));    let people = ask(&two.giver, "secrets.people", json!({}));    assert_eq!(people["people"][0]["line"], "Holds 1 of yours");    assert_eq!(ask(&two.holder, "secrets.people", json!({}))["people"][0]["line"], "Shares 1 with you");}// RULE: See it means no copy: the holder's answer says so and asks for a secure screen.#[test]fn see_only_answers_no_copy_and_a_secure_screen() {    let two = two();    let id = token(&two);    checked(&two);    let made = share(&two, &id, "see");    let one = ask(&two.holder, "secrets.shared", json!({ "share": made }));    assert_eq!((one["mayCopy"].as_bool(), one["secure"].as_bool()), (Some(false), Some(true)));    assert_eq!(ask(&two.holder, "secrets.shared.field", json!({ "share": made, "field": "key" }))["clearAfter"], 0);}// RULE (S5): a take back says only what the server saw; after a seen value it stays "still known" until it is changed, and a change reaches the holders who still may see it.#[test]fn take_back_is_honest_and_a_change_reaches_who_still_holds_it() {    let two = two();    let id = token(&two);    checked(&two);    let made = share(&two, &id, "copy");    let before = ask(&two.giver, "secrets.take.plan", json!({ "id": id, "number": HOLDER }));    assert!(before["after"].as_str().unwrap().contains("received it, but they haven't opened it"), "{}", before["after"]);    ask(&two.holder, "secrets.shared.field", json!({ "share": made, "field": "key" }));    let before = ask(&two.giver, "secrets.take.plan", json!({ "id": id, "number": HOLDER, "privateKey": lent() }));    assert!(before["after"].as_str().unwrap().contains("opened it once"));    assert!(before["after"].as_str().unwrap().contains("Stripe"), "the provider the token's prefix names");    let taken = ask(&two.giver, "secrets.take", json!({ "id": id, "numbers": [HOLDER] }));    assert_eq!(taken["taken"], 1);    assert_eq!(ask(&two.holder, "secrets.inbox", json!({}))["rows"].as_array().unwrap().len(), 0, "gone from the holder's list");    assert_eq!(refused(&two.holder, "secrets.shared.field", json!({ "share": made, "field": "key" })), "share_gone");    let holders = ask(&two.giver, "secrets.holders", json!({ "id": id, "privateKey": lent() }));    assert_eq!(holders["holders"][0]["state"], "still_known");    assert!(holders["stillKnown"]["title"].as_str().unwrap().starts_with("Still known to"));    assert_eq!(holders["stillKnown"]["steps"][0]["url"], "https://dashboard.stripe.com/apikeys");    let needs = ask(&two.giver, "secrets.needs", json!({}));    assert_eq!(needs["rows"][0]["kind"], "still_known");    let done = ask(&two.giver, "secrets.changed", json!({ "id": id }));    assert_eq!(done["changed"], 1);    assert_eq!(ask(&two.giver, "secrets.holders", json!({ "id": id }))["holders"][0]["state"], "changed");    assert_eq!(ask(&two.giver, "secrets.needs", json!({}))["rows"].as_array().unwrap().len(), 0);}// AUDIT D: Remove and Block read what they take back from the shares by number (`secrets.held` names holders by// first name, so Remove found nothing and every secret stayed readable by the person removed).#[test]fn remove_finds_every_secret_a_person_holds_by_number_and_takes_it_back() {    let two = two();    let id = token(&two);    checked(&two);    let made = share(&two, &id, "copy");    assert!(super::held_by(&two.giver.client(), &[STRANGER.to_string()]).unwrap().is_empty());    let held = super::held_by(&two.giver.client(), &[HOLDER.to_string()]).unwrap();    assert_eq!(held.iter().map(|h| (h.number.as_str(), h.secret_id.as_str(), h.opened)).collect::<Vec<_>>(), vec![(HOLDER, id.as_str(), false)]);    // What Remove does with it (circle.rs `Shares::end`): every secret this number holds is taken.    ask(&two.giver, "secrets.take", json!({ "number": held[0].number, "all": true }));    assert_eq!(refused(&two.holder, "secrets.shared.field", json!({ "share": made, "field": "key" })), "share_gone");    assert!(super::held_by(&two.giver.client(), &[HOLDER.to_string()]).unwrap().is_empty());}#[test]fn a_changed_value_reaches_a_live_holder_at_the_next_version() {    let two = two();    let id = token(&two);    checked(&two);    let made = share(&two, &id, "copy");    crate::phone::keys::over(&two.giver.client(), "keys.change", &json!({ "id": id, "fields": { "key": "sk_test_SYNTHETIC0000000NEW1" }, "privateKey": lent() })).expect("keys.change");    let sent = ask(&two.giver, "secrets.reshare", json!({ "id": id, "privateKey": lent() }));    assert_eq!(sent["sent"].as_array().unwrap().len(), 1);    let line = sent["line"].as_str().unwrap();    assert!(line.contains(" still has access, so their copy now holds the new one."), "one holder: {line}");    assert_eq!(ask(&two.holder, "secrets.shared.field", json!({ "share": made, "field": "key" }))["value"], "sk_test_SYNTHETIC0000000NEW1");}// RULE: saving a secret someone holds asks whether the new one goes to them (`ask`, answered by secrets.reshare);// saving one nobody holds asks nothing.#[test]fn saving_a_held_secret_asks_to_send_the_new_one() {    let two = two();    let id = add(&two.giver, json!({"kind": "login", "name": "Invented Mail", "site": "mail.invented.test", "username": "ada@invented.test", "fields": {"password": "SYNTHETIC-pass-0001"}}));    let alone = crate::phone::vault_app::call(&two.giver.client(), "vault.save", &json!({ "id": id, "fields": { "password": "SYNTHETIC-pass-0002" }, "privateKey": lent() }), None).expect("vault.save");    assert!(alone.get("ask").is_none(), "nobody holds it: nothing to ask");    checked(&two);    share(&two, &id, "see");    let saved = crate::phone::vault_app::call(&two.giver.client(), "vault.save", &json!({ "id": id, "fields": { "password": "SYNTHETIC-pass-0003" }, "privateKey": lent() }), None).expect("vault.save");    assert_eq!(saved["ask"]["id"], json!(id));    assert!(saved["ask"]["line"].as_str().unwrap().starts_with("Send the new one to "), "{}", saved["ask"]);    assert_eq!(saved["ask"]["yes"], "Send it");}// RULE: a person asks from Secrets; the giver sees the ask with the secret it probably means and answers with a share, or a no.#[test]fn an_ask_is_answered_from_the_app() {    let two = two();    let id = token(&two);    ask(&two.holder, "secrets.check.confirm", json!({ "number": GIVER }));    checked(&two);    let asked = ask(&two.holder, "secrets.ask", json!({ "number": GIVER, "text": "the deploy key for staging", "why": "to ship the build" }));    assert_eq!(asked["line"], format!("Waiting for {GIVER}."));    let asks = ask(&two.giver, "secrets.asks", json!({}));    let row = &asks["rows"][0];    assert_eq!(row["what"], "the deploy key for staging");    assert_eq!(row["suggest"]["id"], id.as_str(), "the secret its words name");    assert_eq!(ask(&two.giver, "secrets.needs", json!({}))["rows"][0]["kind"], "ask");    ask(&two.giver, "secrets.ask.answer", json!({ "ask": row["ask"], "id": id, "may": "copy", "privateKey": lent() }));    assert_eq!(ask(&two.holder, "secrets.inbox", json!({}))["rows"].as_array().unwrap().len(), 1);    assert_eq!(ask(&two.giver, "secrets.asks", json!({}))["rows"].as_array().unwrap().len(), 0, "answered");    let again = ask(&two.holder, "secrets.ask", json!({ "number": GIVER, "text": "the wifi" }));    assert!(again["ask"].is_string());    let row = ask(&two.giver, "secrets.asks", json!({}))["rows"][0].clone();    ask(&two.giver, "secrets.ask.no", json!({ "ask": row["ask"] }));    assert_eq!(ask(&two.giver, "secrets.asks", json!({}))["rows"].as_array().unwrap().len(), 0);}// RULE: the network holds only ciphertext: no secret's name, value, ask or note reads in anything it keeps.#[test]fn the_server_reads_none_of_it() {    let two = two();    let id = token(&two);    checked(&two);    let made = share(&two, &id, "copy");    ask(&two.holder, "secrets.shared.field", json!({ "share": made, "field": "key" }));    ask(&two.holder, "secrets.check.confirm", json!({ "number": GIVER }));    ask(&two.holder, "secrets.ask", json!({ "number": GIVER, "text": "the staging database password" }));    ask(&two.giver, "secrets.take", json!({ "id": id, "numbers": [HOLDER] }));    let held = two.net.everything();    for plain in ["SYNTHETIC", "Invented deploy key", "staging database", "secret_id", "api_key", id.as_str()] {        assert!(!held.contains(plain), "the network reads {plain}");    }}// RULE: a whole invented Dashlane export is planned by kind, says what does not come across, and lands sealed.#[test]fn a_dashlane_export_is_planned_then_brought_in_sealed() {    let (_dir, handle) = phone();    wrapped(&handle);    let files: Vec<Value> = cotton_core::keys::dashlane::tests_export().into_iter().map(|(name, csv)| json!({ "name": name, "csv": csv })).collect();    let plan = ask(&handle, "secrets.import.plan", json!({ "files": files }));    assert_eq!(plan["found"], "Found 6 to bring in");    assert_eq!(plan["lost"], "Passkeys and files attached to notes do not come across.");    assert_eq!(plan["unknown"], json!(["personalInfo.csv"]));    // Counted by the list's groups, each named once, the largest first.    let kinds = plan["kinds"].as_array().unwrap();    let labels: Vec<&str> = kinds.iter().map(|k| k["label"].as_str().unwrap()).collect();    assert_eq!(labels.len(), labels.iter().collect::<std::collections::BTreeSet<_>>().len(), "each group once: {labels:?}");    assert_eq!(kinds.iter().map(|k| k["count"].as_u64().unwrap()).sum::<u64>(), 6);    assert!(kinds.windows(2).all(|w| w[0]["count"].as_u64() >= w[1]["count"].as_u64()));    let done = ask(&handle, "secrets.import", json!({ "files": files, "privateKey": lent() }));    assert_eq!(done["imported"], 6);    let items = crate::phone::vault_app::call(&handle.client(), "vault.items", &json!({}), None).unwrap();    assert_eq!(items["total"], 6);    assert!(!items.to_string().contains("SYNTHETIC"), "nothing of a value in the list");    let bad = call(&handle.client(), "secrets.import", &json!({ "files": [{ "name": "a.txt", "csv": "hello" }], "privateKey": lent() })).unwrap_err();    assert_eq!(bad.code, "not_dashlane");}// RULE: a server that cannot be reached, or has no Secrets routes yet, is said in the secrets words, never the transport's.#[test]fn an_unreachable_or_unready_server_is_said_in_words() {    use cotton_client::transport::object::ObjectRefusal;    let said = |status: u16, code: &str| super::refused(ObjectRefusal { status, code: code.into(), message: "nothing answers GET /v1/secret/note".into() });    for (status, code, want) in [(404, "not_found", "not_ready"), (0, "offline", "offline"), (0, "not_connected", "not_connected"), (503, "refused", "server_busy"), (409, "conflict", "refused"), (404, "share_gone", "share_gone")] {        let error = said(status, code);        assert_eq!(error.code, want);        assert!(!error.message.contains("/v1/") && !error.message.contains("nothing answers"), "{}", error.message);    }}// RULE (launch-ios on dev, 25 Nov 2026): a phone standing on a local copy nothing founded (as after Sign out, when// the shell's publish ran before the copy stood) founds its vault at Unlock, so Unlock opens it; the gate is open.#[test]fn a_signed_out_phone_founds_its_own_vault_at_unlock() {    let (_dir, handle) = phone();    let client = handle.client();    assert!(!client.signed_in());    let opened = crate::phone::vault::over(&client, "vault.unlock", &json!({ "privateKey": lent() })).expect("Unlock opens a vault nothing founded");    assert_eq!(opened["unlocked"], true);    let gate = call(&client, "secrets.gate", &json!({ "passcode": true })).unwrap();    assert_eq!(gate, json!({ "open": true }), "nothing stuck once it holds its key");}// RULE (launch-ios's shape, 25 Nov 2026): a waiting ask shows on both people's pages: the asker's says "You asked for"// with Withdraw, the holder's "<Name> asked for" with Answer; a withdrawn ask waits on neither.#[test]fn a_waiting_ask_shows_on_both_person_pages_and_withdraws() {    let two = two();    ask(&two.holder, "secrets.check.confirm", json!({ "number": GIVER }));    let asked = ask(&two.holder, "secrets.ask", json!({ "number": GIVER, "text": "the staging deploy key" }));    let id = asked["ask"].as_str().unwrap().to_string();    let mine = ask(&two.holder, "secrets.person", json!({ "number": GIVER }));    assert_eq!(mine["asks"][0]["id"], id.as_str());    assert_eq!(mine["asks"][0]["line"], "You asked for the staging deploy key");    assert_eq!(mine["asks"][0]["act"]["label"], "Withdraw");    assert_eq!(mine["asks"][0]["act"]["request"], json!({ "ask": id }));    let theirs = ask(&two.giver, "secrets.person", json!({ "number": HOLDER }));    assert!(theirs["asks"][0]["line"].as_str().unwrap().ends_with("asked for the staging deploy key"), "{}", theirs["asks"][0]["line"]);    assert_eq!(theirs["asks"][0]["act"]["method"], "secrets.asks");    assert_eq!(theirs["asks"][0]["act"]["request"], json!({ "ask": id }));    let done = ask(&two.holder, mine["asks"][0]["act"]["method"].as_str().unwrap(), mine["asks"][0]["act"]["request"].clone());    assert_eq!(done["withdrawn"], true);    assert!(done["line"].as_str().unwrap().starts_with("Withdrawn."));    assert_eq!(ask(&two.holder, "secrets.person", json!({ "number": GIVER }))["asks"].as_array().unwrap().len(), 0);    assert_eq!(ask(&two.giver, "secrets.person", json!({ "number": HOLDER }))["asks"].as_array().unwrap().len(), 0);    assert_eq!(ask(&two.giver, "secrets.asks", json!({}))["rows"].as_array().unwrap().len(), 0, "gone from the holder's asks");}// RULE (iPhone walk, 25 Nov 2026): the after line agrees with how many still hold it.#[test]fn still_has_access_for_one_and_still_have_for_many() {    let one = super::sf("take.after_others", &[("names", "Arjun"), ("n", "1")]);    let many = super::sf("take.after_others", &[("names", "Arjun, Neha"), ("n", "2")]);    assert_eq!(one, "Arjun still has access, so their copy now holds the new one.");    assert_eq!(many, "Arjun, Neha still have access, so their copies now hold the new one.");}