Cotton code
190 lines · 10.9 KB · RustRaw
//! Restore an earlier day, end to end against the real Worker under `wrangler dev`: run in this order by//! `apps/business/scripts/__tests__/e2e-restore.ts`, which starts the Worker on its own port with its own storage,//! onboards an invented owner, signs in a member and a second owner device, mints an owner key, keeps a weekly full and//! a daily of invented to-dos, damages them, and hands this test the address and credentials (`COTTON_E2E_*`).//! Ignored otherwise; it never dials anything but the address it is handed.use std::sync::Arc;use cotton_client::transport::object::{bearer, ObjectAddress};use cotton_client::transport::{Exchange, SocketExchange};use serde_json::{json, Value};use super::*;use crate::handle::CottonHandle;fn given(name: &str) -> String {    std::env::var(name).unwrap_or_else(|_| panic!("{name} is set by e2e-restore.ts"))}fn door(credential: &str) -> ObjectDoor {    ObjectDoor { address: ObjectAddress::open(&given("COTTON_E2E_BASE")).expect("the address"), exchange: Arc::new(SocketExchange) as Arc<dyn Exchange>, credential: credential.to_string() }}/// A phone in `dir`, opened as Cotton opens (the same folder again is the app started again).fn phone_in(dir: &tempfile::TempDir) -> CottonHandle {    CottonHandle::open(crate::handle::OpenConfig {        mode: crate::handle::OpenMode::Phone { container_path: dir.path().to_string_lossy().to_string(), previous_container_path: None },        app_version: None,        time_zone: Some("Asia/Kolkata".to_string()),        device_secret: Some(crate::fixture::paired_secret()),        vault_secret: None,        flavor: cotton_core::flavor::Flavor::Real,        manifest: Some(serde_json::from_str(include_str!("../../../../apps/cotton/App/CottonManifest/flavour.json")).expect("Cotton's manifest")),    })    .expect("an open core")}fn connect(handle: &CottonHandle) {    let ask = json!({"server": given("COTTON_E2E_BASE"), "databaseId": given("COTTON_E2E_DATABASE"), "credential": given("COTTON_E2E_CREDENTIAL"), "windows": {"message": 90}});    crate::phone::personal_object::call(handle, "personal.connect", &ask).expect("connected");}/// Passes until one ends level; a pass that met the restore (the copy set aside and made again) is followed by more.fn level(handle: &CottonHandle) {    let mut last = Value::Null;    // A copy being made again after the restore answers "being checked and unpacked" until it opens: waited for.    for _ in 0..120 {        match handle.client().sync_now_until_level() {            Ok(pass) if pass["behind"] != json!(true) => return,            Ok(pass) => last = pass,            Err(error) => last = json!(format!("{error:?}")),        }        std::thread::sleep(std::time::Duration::from_millis(1000));    }    panic!("never level: {last}");}fn titles(handle: &CottonHandle) -> Vec<String> {    let listed = crate::methods::dispatch(handle, "records.list", &json!({"table": "todo"})).expect("the to-dos");    let mut out = Vec::new();    fn walk(value: &Value, out: &mut Vec<String>) {        match value {            Value::Object(map) => {                if let Some(Value::String(title)) = map.get("title") {                    out.push(title.clone());                }                map.values().for_each(|v| walk(v, out));            }            Value::Array(items) => items.iter().for_each(|v| walk(v, out)),            _ => {}        }    }    walk(&listed, &mut out);    out.sort();    out.dedup();    out}/// RULE: only the owner's own phone, signed in, restores the account: another person's phone and an assistant's key/// are refused in the set's words; the owner's phone lists the days.#[test]#[ignore = "run by apps/business/scripts/__tests__/e2e-restore.ts against wrangler dev"]fn restore_refuses_a_device_that_is_not_the_owners() {    for (who, credential) in [("a member's phone", given("COTTON_E2E_MEMBER")), ("an assistant's key", given("COTTON_E2E_TOKEN"))] {        let refused = points(&door(&credential), "Asia/Kolkata").expect_err(who);        assert_eq!((refused.code.as_str(), refused.message.as_str()), ("owner_device_only", say("refused.owner_only", &[]).as_str()), "{who}");        let refused = begin(&door(&credential), &json!({"id": "any"}), "Asia/Kolkata").expect_err(who);        assert_eq!(refused.code, "owner_device_only", "{who}");    }    let listed = points(&door(&given("COTTON_E2E_CREDENTIAL")), "Asia/Kolkata").expect("the owner's phone lists");    assert_eq!(listed["available"], json!(true), "{listed}");    println!("E2E-RESTORE-WHO {}", json!({"days": listed["days"].as_array().map(Vec::len)}));}/// RULE: a restore begun on the owner's phone and interrupted at its worst moment (the rows emptied, the app gone)/// is resumed when the app opens again: the restore reaches its end, the account is back as the kept day held it,/// and this phone's copy is set aside and made again from it (the to-do written after the day is gone, the damaged/// ones are back), and `restore.after` says the day.#[test]#[ignore = "run by apps/business/scripts/__tests__/e2e-restore.ts against wrangler dev"]fn a_restore_interrupted_and_resumed_puts_the_phone_back() {    let dir = tempfile::tempdir().expect("a container");    let handle = phone_in(&dir);    connect(&handle);    level(&handle);    let damaged = titles(&handle);    assert!(!damaged.iter().any(|t| t.starts_with("Kept ")), "the damage reached the phone: {damaged:?}");    // A write after the kept day (planted with the owner's key: todo is sealed on dev), which the phone pulls.    let token = door(&given("COTTON_E2E_TOKEN"));    token        .address        .send(token.exchange.as_ref(), "POST", "/v1/admin/import", bearer(&token.credential), Some(&json!({"rows": [{"table": "todo", "id": "after-the-day", "data": {"title": "Written after the kept day", "status": "open"}}]})))        .expect("planted");    level(&handle);    assert!(titles(&handle).iter().any(|t| t == "Written after the kept day"), "the phone holds the write after the day");    let listed = crate::methods::dispatch(&handle, "restore.points", &json!({})).expect("the days");    assert_eq!(listed["available"], json!(true), "{listed}");    let day = listed["days"][0].clone();    let id = day["id"].as_str().unwrap_or_else(|| panic!("a day to restore: {listed}")).to_string();    assert!(day["label"].as_str().is_some_and(|l| !l.is_empty()) && day["confirmLine"].as_str().is_some_and(|l| l.contains("on every device")), "{day}");    // A member's phone that never sends the generation is signed in: the phone asks first, then goes on anyway.    let asked = crate::methods::dispatch(&handle, "restore.begin", &json!({"id": id})).expect("begun or asked");    let begun = if asked.get("confirm").is_some() {        assert!(asked["confirm"]["line"].as_str().is_some_and(|l| l.contains("older Cotton")), "{asked}");        crate::methods::dispatch(&handle, "restore.begin", &json!({"id": id, "anyway": true})).expect("begun anyway")    } else {        asked    };    assert_eq!((begun["stage"].as_str(), begun["underWay"].as_bool()), (Some("checking"), Some(true)), "{begun}");    assert_eq!(begun["to"], day["to"]);    assert!(begun["line"].as_str().is_some_and(|l| l.starts_with("Checking the copy of")), "{begun}");    let stepped = crate::methods::dispatch(&handle, "restore.progress", &json!({})).expect("a step");    println!("E2E-RESTORE-STEP {}", json!({"stage": stepped["stage"], "done": stepped["done"], "total": stepped["total"]}));    assert!(matches!(stepped["stage"].as_str(), Some("checking" | "laying" | "done")), "{stepped}");    // Interrupted: the app is gone mid-restore. Opened again, it finds the restore where the server holds it.    drop(handle);    let handle = phone_in(&dir);    connect(&handle);    let found = crate::methods::dispatch(&handle, "restore.points", &json!({})).expect("the days again");    println!("E2E-RESTORE-FOUND {}", json!({"stage": found["progress"]["stage"]}));    let mut state = crate::methods::dispatch(&handle, "restore.progress", &json!({})).expect("resumed");    for _ in 0..30 {        if !state["underWay"].as_bool().unwrap_or(false) {            break;        }        state = crate::methods::dispatch(&handle, "restore.progress", &json!({})).expect("a step");    }    assert!(matches!(state["stage"].as_str(), Some("done" | "none")), "it reached its end: {state}");    // The phone sees the new generation and makes its copy again: the kept day's to-dos, nothing written after it.    let mut held = Vec::new();    for _ in 0..10 {        level(&handle);        held = titles(&handle);        if held.iter().any(|t| t.starts_with("Kept ")) && !held.iter().any(|t| t == "Written after the kept day") {            break;        }        std::thread::sleep(std::time::Duration::from_millis(500));    }    assert!(held.iter().any(|t| t == "Kept 0") && held.iter().any(|t| t == "Kept later"), "the kept day is back on the phone: {held:?}");    assert!(!held.iter().any(|t| t == "Written after the kept day"), "after the day: gone: {held:?}");    let after = crate::methods::dispatch(&handle, "restore.after", &json!({})).expect("after");    assert_eq!((after["restored"].as_bool(), after["to"].as_str().map(|to| to[..19].to_string())), (Some(true), day["to"].as_str().map(|to| to[..19].to_string())), "{after}");    assert!(after["line"].as_str().is_some_and(|l| l.starts_with("Your Cotton was put back to how it was on")), "{after}");    println!("E2E-RESTORE-DONE {}", json!({"titles": held.len(), "keptAside": after["keptAside"], "bringing": after["bringing"]}));}/// RULE: once the account's delete has begun (from another of the owner's devices), a restore is refused in the set's/// words, and nothing is frozen.#[test]#[ignore = "run by apps/business/scripts/__tests__/e2e-restore.ts against wrangler dev"]fn a_restore_is_refused_once_the_erase_starts() {    let owner = door(&given("COTTON_E2E_CREDENTIAL"));    let listed = points(&owner, "Asia/Kolkata").expect("the days before");    let id = listed["days"][0]["id"].as_str().unwrap_or("none").to_string();    let other = door(&given("COTTON_E2E_OTHER"));    let code = other.address.send(other.exchange.as_ref(), "POST", "/v1/account/delete/code", bearer(&other.credential), None).expect("a code");    let challenge = code["challenge_id"].as_str().expect("a challenge").to_string();    other        .address        .send(other.exchange.as_ref(), "POST", "/v1/account/delete", bearer(&other.credential), Some(&json!({"challenge_id": challenge, "code": "123456", "confirm": "delete"})))        .expect("the delete begins");    let refused = begin(&owner, &json!({"id": id, "anyway": true}), "Asia/Kolkata").expect_err("refused");    assert_eq!((refused.code.as_str(), refused.message.as_str()), ("account_deleting", say("refused.deleting", &[]).as_str()));    assert_eq!(points(&owner, "Asia/Kolkata").expect_err("refused").code, "account_deleting");    println!("E2E-RESTORE-ERASE {}", json!({"refused": refused.code}));}