Cotton code
233 lines · 12.3 KB · RustRaw
//! PERSON B OF THE ANDROID SECRETS WALK (coordinator, 26 Nov 2026): the two-person walk by hand on an emulator (person//! A) needs a second person, and the box's walk lock runs one emulator at a time under load. Person B is a Secrets phone//! through the C ABI against the dev Worker (the core the phones load), doing B's half through the calls the screens//! use, each step waiting for what A does by hand, and printing each as it happens. Every number, name and value is//! invented.//!//! SKIPPED unless COTTON_WALK_SERVER (dev), COTTON_WALK_CODE_FILE (read, never printed), COTTON_WALK_A and//! COTTON_WALK_B (the two invented numbers) are set. Run with --ignored --nocapture.use std::ffi::{c_char, CStr, CString};use std::path::PathBuf;use std::time::{Duration, Instant};use base64::engine::general_purpose::URL_SAFE_NO_PAD;use base64::Engine as _;use cotton_ffi::{cotton_call, cotton_close, cotton_open, cotton_string_free, CottonHandle};use serde_json::{json, Value};use sha2::{Digest, Sha256};const APP_VERSION: &str = "walk-person-b";const FLAVOUR: &str = "keys";const WAIT: Duration = Duration::from_secs(1500);const VALUE: &str = "sk_test_SYNTHETIC_PROOF_0000004f2a";const CHANGED: &str = "sk_test_SYNTHETIC_PROOF_000000NEW1";struct Walk {    server: String,    code: String,    run: String,}impl Walk {    fn from_env() -> Option<Walk> {        let var = |name: &str| std::env::var(name).ok().map(|v| v.trim().to_string()).filter(|v| !v.is_empty());        let (server, file) = (var("COTTON_WALK_SERVER")?, var("COTTON_WALK_CODE_FILE")?);        assert!(server.contains("-dev") || server.contains("localhost") || server.contains("127.0.0.1"), "Secrets is proven on the dev server only, not {server}");        let file = match file.strip_prefix("~/") {            Some(rest) => PathBuf::from(std::env::var("HOME").expect("HOME")).join(rest),            None => PathBuf::from(file),        };        let code = std::fs::read_to_string(&file).unwrap_or_else(|e| panic!("the dev code file {} could not be read: {e}", file.display())).trim().to_string();        let run = var("COTTON_WALK_RUN").unwrap_or_else(|| format!("{:03}", (std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_millis() % 900) + 100));        Some(Walk { server, code, run })    }    fn number(&self, slot: u32) -> String {        format!("+1555019{}{slot}", self.run)    }}struct Phone {    handle: *mut CottonHandle,    _container: tempfile::TempDir,    number: String,    name: &'static str,    private_key: String,}impl Phone {    fn open(walk: &Walk, number: &str, name: &'static str) -> Phone {        let container = tempfile::tempdir().expect("a tempdir");        std::fs::create_dir_all(container.path().join("cotton")).expect("the container");        let seed = format!("cotton headless secrets {number} {:?}", std::time::SystemTime::now());        let config = json!({            "containerPath": container.path().join("cotton").to_string_lossy(),            "appVersion": APP_VERSION,            "timeZone": "Asia/Kolkata",            "deviceSecret": URL_SAFE_NO_PAD.encode(Sha256::digest(seed.as_bytes())),            "flavor": "dev",            "manifest": manifest(&walk.server),        });        let text = CString::new(config.to_string()).expect("no NUL");        let mut error: *mut c_char = std::ptr::null_mut();        // SAFETY: a NUL-terminated config and a writable error slot, as the JNI hands them.        let handle = unsafe { cotton_open(text.as_ptr(), &mut error) };        assert!(!handle.is_null(), "cotton_open refused: {}", take(error));        let private_key = URL_SAFE_NO_PAD.encode(Sha256::digest(format!("vault {seed}").as_bytes()));        Phone { handle, _container: container, number: number.into(), name, private_key }    }    fn call(&self, method: &str, request: Value) -> Result<Value, String> {        let method_c = CString::new(method).expect("no NUL");        let request_c = CString::new(request.to_string()).expect("no NUL");        // SAFETY: a live handle and NUL-terminated strings; the answer is owned and freed by `take`.        let answer = take(unsafe { cotton_call(self.handle, method_c.as_ptr(), request_c.as_ptr()) });        let answer: Value = serde_json::from_str(&answer).map_err(|e| format!("{method}: the answer is not JSON ({e})"))?;        if answer["ok"] == json!(true) {            return Ok(answer["data"].clone());        }        let error = &answer["error"];        Err(format!("{} {method}: {} {}", self.name, error["code"].as_str().unwrap_or("?"), error["message"].as_str().unwrap_or("?")))    }    fn must(&self, method: &str, request: Value) -> Value {        self.call(method, request).unwrap_or_else(|e| panic!("{e}"))    }    /// The call with this phone's vault key lent, as the shell lends it after Face ID.    fn lent(&self, method: &str, mut request: Value) -> Value {        request["privateKey"] = json!(self.private_key);        self.must(method, request)    }    fn sign_in(&self, walk: &Walk) {        self.must("personal.standLocal", json!({ "signedOut": true }));        let challenge = self.must("personal.code", json!({ "server": walk.server, "phone": self.number }));        let mut ask = json!({ "server": walk.server, "challengeId": challenge["challengeId"], "code": walk.code });        if let Some(database) = challenge.get("databaseId").filter(|d| !d.is_null()) {            ask["databaseId"] = database.clone();        }        let answer = self.must("personal.signIn", ask);        let database = answer["databaseId"].as_str().or(challenge["databaseId"].as_str()).expect("a database").to_string();        let credential = answer["credential"].as_str().expect("a credential");        self.must("personal.connect", json!({ "server": walk.server, "databaseId": database, "credential": credential, "deviceName": format!("headless secrets {}", self.name), "appVersion": APP_VERSION }));    }    /// The account's key founded on this, its first phone, so its data key and vault are held.    fn found_key(&self) {        for _ in 0..20 {            let status = self.must("seal.status", json!({}));            if status["keyHeld"] == json!(true) {                return;            }            if status["needsKey"] == json!(true) && status["founds"] == json!(true) {                let _ = self.call("vault.unlock", json!({ "privateKey": self.private_key, "name": format!("headless secrets {}", self.name) }));            }            let _ = self.call("sync.now", json!({}));            std::thread::sleep(Duration::from_secs(1));        }        panic!("{}: the account's key was never held", self.name);    }    /// Asked until `until` holds of the answer, or WAIT passes: a share crosses from one object to another.    fn until(&self, method: &str, request: Value, what: &str, until: impl Fn(&Value) -> bool) -> Value {        let started = Instant::now();        loop {            if let Ok(answer) = self.call(method, request.clone()) {                if until(&answer) {                    return answer;                }            }            assert!(started.elapsed() < WAIT, "{}: {what} did not happen in {}s", self.name, WAIT.as_secs());            std::thread::sleep(Duration::from_secs(2));        }    }}impl Drop for Phone {    fn drop(&mut self) {        // SAFETY: the pointer cotton_open answered, closed once.        unsafe { cotton_close(self.handle) };    }}fn take(text: *mut c_char) -> String {    if text.is_null() {        return String::new();    }    // SAFETY: a string the core allocated, read once and freed by the core.    let owned = unsafe { CStr::from_ptr(text) }.to_string_lossy().into_owned();    unsafe { cotton_string_free(text) };    owned}fn manifest(server: &str) -> Value {    let path = cotton_store::manifest_dir().join("../../apps/cotton/App/Flavours").join(FLAVOUR).join("flavour.json");    let mut whole: Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap_or_else(|error| panic!("{} reads: {error}", path.display()))).expect("JSON");    if whole["business"]["server"].is_object() {        whole["business"]["server"] = json!(server);    }    whole}fn say(what: &str, started: Instant) {    println!("WALK B {what} ({:.0} s)", started.elapsed().as_secs_f64());}#[test]#[ignore = "person B of a walk by hand: run with --ignored beside the emulator"]fn person_b_of_the_android_secrets_walk() {    let Some(walk) = Walk::from_env() else {        eprintln!("skipped: COTTON_WALK_SERVER and COTTON_WALK_CODE_FILE are not set");        return;    };    let a = std::env::var("COTTON_WALK_A").expect("COTTON_WALK_A, person A's invented number");    let b = std::env::var("COTTON_WALK_B").expect("COTTON_WALK_B, person B's invented number");    let started = Instant::now();    let me = Phone::open(&walk, &b, "B");    me.sign_in(&walk);    me.found_key();    say("signed in and founded its vault", started);    // 1. People: B adds A; A adds B by hand (People, Add, B's number).    me.must("people.add", json!({ "number": a }));    say("asked to add A: waiting for A to add B on the emulator", started);    me.until("secrets.people", json!({}), "A in B's people", |answer| answer["people"].as_array().is_some_and(|p| p.iter().any(|row| row["number"] == a.as_str())));    say("A is in B's people", started);    // Accepted both ways before anything is shared or asked: the object drops a share or an ask to one who has not    // added you back (send/secrets.ts WHO), so B waits for A's Accept.    me.until("secrets.people", json!({}), "A accepted B", |answer| answer["people"].as_array().is_some_and(|p| p.iter().any(|row| row["number"] == a.as_str() && row["accepted"] != json!(false))) && answer["people"].as_array().is_some_and(|p| p.iter().any(|row| row["accepted"] == json!(true))));    say("A accepted B", started);    // 2. Check: B confirms A's sharing key on its side; A checks B's by hand.    let check = me.must("secrets.check", json!({ "number": a }));    println!("WALK B check words for A: {}", check["words"].as_array().map(|w| w.iter().filter_map(|x| x.as_str()).collect::<Vec<_>>().join(" ")).unwrap_or_default());    me.must("secrets.check.confirm", json!({ "number": a }));    say("B confirmed A's key", started);    // 3. Share: B shares an invented key with A, so A's list shows it under Shared with you.    let id = me.lent("keys.add", json!({ "kind": "api_key", "name": "Invented walk key", "fields": { "key": "sk_test_SYNTHETIC_WALK_00000b" } }))["id"].as_str().expect("an id").to_string();    let share = me.lent("secrets.share", json!({ "id": id, "number": a, "may": "copy", "until": "week" }));    say(&format!("shared 'Invented walk key' with A ({})", share["share"].as_str().unwrap_or("?")), started);    // 4. Ask on person: B asks A for something; A's person page shows it with Answer.    me.must("secrets.ask", json!({ "number": a, "text": "the invented wifi password", "why": "for the walk" }));    say("asked A for 'the invented wifi password': A's person page should say B asked, with Answer", started);    // 5. A asks B by hand (B's person page, Ask): it arrives here; B leaves it waiting, so A sees it with Withdraw.    let asks = me.until("secrets.asks", json!({}), "A's ask arriving", |answer| answer["rows"].as_array().is_some_and(|rows| !rows.is_empty()));    say(&format!("A's ask arrived: {}", asks["rows"][0]), started);    // 6. A shares something with B by hand, or answers B's ask: it lands in B's inbox.    let inbox = me.until("secrets.inbox", json!({}), "a share from A", |answer| answer["rows"].as_array().is_some_and(|rows| !rows.is_empty()));    say(&format!("A's share arrived: {}", inbox["rows"][0]["line"].as_str().or(inbox["rows"][0]["name"].as_str()).unwrap_or("?")), started);    // 7. A withdraws its waiting ask by hand: it leaves B's asks.    me.until("secrets.asks", json!({}), "A's ask withdrawn", |answer| answer["rows"].as_array().is_some_and(|rows| rows.is_empty()));    say("A's ask was withdrawn: gone from B", started);    // 8. A deletes its account by hand (You, Delete account): A leaves B's people, or says it is gone.    let people = me.until("secrets.people", json!({}), "A gone after Delete account", |answer| !answer["people"].as_array().is_some_and(|p| p.iter().any(|row| row["number"] == a.as_str() && row["gone"] != json!(true))));    say(&format!("after A deleted its account, B's people: {}", people["people"]), started);    say("DONE", started);}