Cotton code
252 lines · 13.3 KB · RustRaw
//! COTTON POST, PROVEN ON DEV (assets/design/mail/CONTRACT.md row 19): an invented person, a Post phone through the//! C ABI against the dev Worker, hands a mailbox to Cotton fetches, reads its state and log, forgets the password and//! removes the account, through the calls the screens use. Every number, name, address and password is invented.//! The Post proof script runs it.//!//! Part one needs no mailbox: the account is invented (`imap.invented.example` answers nothing), so the object//! takes the password, finds nothing to read, and says so in the account's state and log.//!//! Part two runs when COTTON_POST_MAILBOX names a file of three lines (host, address, app password) for a TEST//! mailbox the coordinator made (never his own): the object reads it, the mail lands on the phone, an Archive is done//! on the server through `/v1/mail/fetch/act`, a mail is sent from it to itself, and the account is let go.//!//! SKIPPED unless COTTON_WALK_SERVER (the dev Worker) and COTTON_WALK_CODE_FILE (the dev sign-in code's file: read,//! never printed) are set. COTTON_WALK_RUN picks the invented number (+1555019<run><slot>). Never the live server.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 = "headless-post";const FLAVOUR: &str = "mail";const WAIT: Duration = Duration::from_secs(45);/// Cotton fetches reads on the object's alarm: a real mailbox's first mail may take a round of it.const ROUND_WAIT: Duration = Duration::from_secs(420);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"), "Post 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 {    private_key: String,    handle: *mut CottonHandle,    _container: tempfile::TempDir,    number: String,    name: &'static str,}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 post {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));        Phone { handle, _container: container, number: number.into(), name, private_key: URL_SAFE_NO_PAD.encode(Sha256::digest(format!("vault {seed}").as_bytes())) }    }    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}"))    }    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 post {}", 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 post {}", 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 step(name: &str, started: Instant) {    println!("POST PROOF {name} ({:.1} s)", started.elapsed().as_secs_f64());}/// The test mailbox the coordinator made, when there is one: host, address, app password.fn test_mailbox() -> Option<(String, String, String)> {    let file = std::env::var("COTTON_POST_MAILBOX").ok().filter(|f| !f.trim().is_empty())?;    let text = std::fs::read_to_string(file.trim()).unwrap_or_else(|e| panic!("the test mailbox file could not be read: {e}"));    let mut lines = text.lines().map(str::trim).filter(|l| !l.is_empty());    let (host, address, password) = (lines.next()?, lines.next()?, lines.next()?);    Some((host.to_string(), address.to_lowercase(), password.to_string()))}#[test]fn an_invented_person_hands_a_mailbox_to_cotton_fetches() {    let Some(walk) = Walk::from_env() else {        eprintln!("skipped: COTTON_WALK_SERVER and COTTON_WALK_CODE_FILE are not set");        return;    };    let started = Instant::now();    let phone = Phone::open(&walk, &walk.number(1), "mira");    phone.sign_in(&walk);    phone.found_key();    step("signed in, key founded", started);    // Part one: an invented mailbox nobody answers for.    let plan = phone.must("mail.account.plan", json!({ "kind": "imap" }));    assert!(plan["ways"].as_array().is_some_and(|w| w.iter().any(|way| way["id"] == "cotton")), "Cotton fetches is offered: {plan}");    let address = format!("mira.proof{}@invented.example", walk.run);    let added = phone.must("mail.account.add", json!({ "kind": "imap", "address": address, "way": "cotton", "host": "imap.invented.example", "password": "invented-proof-password" }));    let id = added["id"].as_str().expect("an account id").to_string();    assert_eq!(added["way"], "cotton", "{added}");    assert!(added["log"].is_object(), "the account shows its log: {added}");    step("the object took the password", started);    let seen = phone.must("mail.account", json!({ "id": id }));    println!("POST PROOF state: {} · {}", seen["status"]["state"], seen["status"]["line"]);    assert_ne!(seen["status"]["state"], "live", "nothing has been fetched from a server that does not exist: {}", seen["status"]);    step("the account's state came from the object", started);    let forgot = phone.must("mail.account.forget", json!({ "id": id }));    assert_eq!(forgot["next"]["account"]["status"]["state"], "stopped", "nobody fetches until he picks again: {forgot}");    let asked = phone.must("mail.account.remove", json!({ "id": id }));    let removed = phone.must("mail.account.remove", json!({ "id": id, "count": asked["ask"]["count"] }));    assert!(removed["line"].is_string(), "{removed}");    step("password forgotten, account removed", started);    // Part two: a real test mailbox, when the coordinator gave one.    if let Some((host, address, password)) = test_mailbox() {        let added = phone.must("mail.account.add", json!({ "kind": "imap", "address": address, "way": "cotton", "host": host, "password": password }));        let id = added["id"].as_str().expect("an account id").to_string();        step("the test mailbox handed to Cotton fetches", started);        let wait_started = Instant::now();        let inbox = loop {            let _ = phone.call("sync.now", json!({}));            let list = phone.must("mail.list", json!({ "place": "inbox" }));            if list["rows"].as_array().is_some_and(|r| !r.is_empty()) {                break list;            }            assert!(wait_started.elapsed() < ROUND_WAIT, "no mail from the test mailbox in {} s: {}", ROUND_WAIT.as_secs(), phone.must("mail.account", json!({ "id": id })));            std::thread::sleep(Duration::from_secs(5));        };        step(&format!("its mail landed ({} in the Inbox)", inbox["rows"].as_array().map_or(0, Vec::len)), started);        let first = &inbox["rows"][0];        let done = phone.must("mail.archive", json!({ "scope": "thread", "thread": first["thread"] }));        println!("POST PROOF archive: {} · {}", done["line"], done["mailbox"]);        assert!(!done["mailbox"].to_string().contains("failed"), "the server did the Archive: {done}");        step("archived on the server", started);        phone.must("mail.set", json!({ "name": "undo_send", "value": 0 }));        let saved = phone.must("mail.save", json!({ "to": [address], "from": address, "subject": format!("Post proof {}", walk.run), "body": "An invented line from the Post proof." }));        let sent = phone.must("mail.send", json!({ "draft": saved["draft"] }));        println!("POST PROOF send: {} · {}", sent["state"], sent["line"]);        assert_ne!(sent["state"], "failed", "{sent}");        step("sent from the test mailbox", started);        phone.must("mail.account.forget", json!({ "id": id }));        step("the test mailbox let go", started);    } else {        println!("POST PROOF part two skipped: COTTON_POST_MAILBOX names no test mailbox");    }    println!("POST PROOF PASSED ({:.1} s)", started.elapsed().as_secs_f64());}