//! `shared.*` on two phones over a scripted object: what each phone posts is//! wraps and sealed text, and the other member opens it. Every number and word//! is invented.use std::sync::Arc;use cotton_client::transport::object::ObjectAddress;use cotton_client::transport::scripted::{Reply, ScriptedExchange, Seen};use serde_json::{json, Value};usesuper::over;usecrate::handle::CottonHandle;usecrate::phone::personal_object::ObjectDoor;const CREDENTIAL: &str = "ctd_11111111-1111-4111-8111-111111111111_test-credential";const A: &str = "+15550100011";const B: &str = "+15550100012";fn phone() -> (tempfile::TempDir, CottonHandle) {let dir = tempfile::tempdir().expect("a temp container");let manifest = json!({"genesis": "personal", "flavour": "books", "name": "Cotton Books", "databases": "single", "database": "personal","fan": {"home": false, "tools": false, "opens": "books"}, "kit": "books", });let handle = 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(manifest), }) .expect("an open core");crate::methods::dispatch(&handle, "workspace.startLocal", &json!({"deviceName": "An invented phone"})).expect("started");letmut bytes = [0u8; 32]; rand::RngCore::fill_bytes(&mut rand::rngs::OsRng, &mut bytes);let client = handle.client();let database = client.current_database().expect("a database"); client.data_keys().hold(&database, &cotton_core::seal::DataKey::from_bytes(bytes));// The sharing key posted once this launch, as the first note read or written posts it. door(&handle, vec![ok()]);crate::phone::send_seal::post_key(&client).expect("the sharing key posted"); (dir, handle)}fn door(handle: &CottonHandle, replies: Vec<Reply>) -> Arc<ScriptedExchange> {let exchange = ScriptedExchange::new(replies);let door = ObjectDoor { address: ObjectAddress::open("https://cottondb.example.test").expect("an address"), exchange: exchange.clone(), credential: CREDENTIAL.to_string() }; handle.client().set_object_door(Some(Arc::new(door))); exchange}fn answer(handle: &CottonHandle, method: &str, request: Value) -> Value { over(&handle.client(), method, &request).unwrap_or_else(|error| panic!("{method}: {} {}", error.code, error.message))}fn body(seen: &Seen) -> Value { serde_json::from_slice(&seen.body).expect("a JSON body")}fn public(handle: &CottonHandle) -> String {crate::phone::send_seal::sharing(&handle.client()).expect("a sharing key").1}/// The list as the founder's object answers a member.fn listed(me: &str, state: &Value) -> Reply {Reply::ok(&json!({ "me": me, "owner": A, "id": "list-weekend", "state": state }).to_string())}fn ok() -> Reply {Reply::ok(r#"{"ok":true}"#)}/// This person's notes as their object answers them: none yet.fn no_notes() -> Reply {Reply::ok(r#"{"notes":[]}"#)}/// This person's notes holding one note, sealed to themselves as `secrets_app::put_note` seals it.fn notes_with(handle: &CottonHandle, key: &str, value: &Value) -> Reply {use cotton_core::seal::share::{key_from_text, seal_to_person};let (secret, public) = crate::phone::send_seal::sharing(&handle.client()).expect("a sharing key");let public = key_from_text(&public).expect("a key");let boxed = seal_to_person(&secret, &public, &format!("secret-note:{key}"), &serde_json::to_vec(value).unwrap()).expect("sealed");Reply::ok(&json!({ "notes": [{ "key": key, "box": boxed }] }).to_string())}fn seen_key(number: &str) -> String {crate::phone::secrets_app::pin_key(number).replacen("pin:", "seen:", 1)}/// RULE (R5): a list founded on one phone, written on the other, read back on the first; what the phones post holds/// no word of it. Removing the second phone's person seals every item again, and they open nothing after.#[test]fn two_phones_share_a_list_and_a_removed_member_opens_nothing() {let (_da, a) = phone();let (_db, b) = phone();// A founds the list with B: B's key asked of A's object, the state posted.let key = Reply::ok(&json!({ "key": public(&b), "me": A }).to_string());let seen = door(&a, vec![key, no_notes(), ok(), ok()]); assert_eq!(answer(&a, "shared.found", json!({ "id": "list-weekend", "members": [B] }))["owner"], A);// B's key pinned on first sight, before anything was wrapped to it.let pinned = seen.seen().into_iter().find(|s| s.path == "/v1/secret/note" && !s.body.is_empty()).expect("B's key pinned"); assert_eq!(body(&pinned)["key"], seen_key(B));letmut state = body(&seen.seen().into_iter().find(|s| s.path == "/v1/shared/lists").expect("posted"))["state"].clone(); assert_eq!(state["membership"]["epoch"], 1); assert!(state["membership"]["wraps"]["1"][B].as_str().unwrap().starts_with("w1:"));// B writes an item through A's object.let seen = door(&b, vec![listed(B, &state), ok()]); answer(&b, "shared.put", json!({ "owner": A, "id": "list-weekend", "item": "i1", "body": { "text": "Oat milk", "done": false } }));let posted = body(&seen.seen().into_iter().find(|s| s.path == "/v1/shared/list/item").expect("an item posted"));let sealed = posted["sealed"].as_str().unwrap().to_string(); assert!(sealed.starts_with("g1:1:") && !sealed.contains("Oat"), "sealed text only"); state["items"]["i1"] = json!(sealed);// A reads it; the founder's phone checks the membership once: B is A's person, B's key never moved. door(&a, vec![listed(A, &state), no_notes(), Reply::ok(&json!({ "key": public(&b), "me": A }).to_string()), ok()]);let read = answer(&a, "shared.read", json!({ "id": "list-weekend" })); assert_eq!(read["items"][0]["text"], "Oat milk"); assert_eq!(read["doubts"], json!([]));// A removes B: a new epoch, every item sealed again; B opens nothing of what the object then holds.let seen = door(&a, vec![listed(A, &state), ok()]); answer(&a, "shared.remove", json!({ "id": "list-weekend", "number": B }));let next = body(&seen.seen().into_iter().find(|s| s.path == "/v1/shared/list/state").expect("state posted"))["state"].clone(); assert_eq!(next["membership"]["epoch"], 2); assert!(next["items"]["i1"].as_str().unwrap().starts_with("g1:2:")); assert!(!next.to_string().contains("Oat")); door(&b, vec![listed(B, &next)]);let theirs = answer(&b, "shared.read", json!({ "owner": A, "id": "list-weekend" })); assert_eq!(theirs["items"], json!([])); assert_eq!(theirs["unopened"], json!(["i1"])); door(&b, vec![listed(B, &next)]); assert!(over(&b.client(), "shared.put", &json!({ "owner": A, "id": "list-weekend", "item": "i2", "body": { "text": "x" } })).is_err(), "a removed member writes nothing");}/// AUDIT FIX B1 (B-2): a member's key that is not the one first wrapped to is refused, never wrapped to; only the/// founder adds or takes others off; and on the founder's phone a member they never added is said.#[test]fn a_changed_key_is_refused_a_member_adds_no_one_and_the_founder_is_told_of_a_stranger() {let (_da, a) = phone();let (_db, b) = phone();let (_dc, c) = phone();let state = {let seen = door(&a, vec![Reply::ok(&json!({ "key": public(&b), "me": A }).to_string()), no_notes(), ok(), ok()]); answer(&a, "shared.found", json!({ "id": "list-weekend", "members": [B] })); body(&seen.seen().into_iter().find(|s| s.path == "/v1/shared/lists").expect("posted"))["state"].clone() };// C's key is pinned on A's phone as one key; C's object now answers another: refused, and nothing posted.let pin = json!({ "number": "+15550100013", "key": public(&b) });let seen = door(&a, vec![listed(A, &state), Reply::ok(&json!({ "key": public(&c), "me": A }).to_string()), notes_with(&a, &seen_key("+15550100013"), &pin)]);let refused = over(&a.client(), "shared.add", &json!({ "id": "list-weekend", "number": "+15550100013" })).expect_err("a changed key is refused"); assert_eq!(refused.code, "key_changed"); assert!(seen.seen().iter().all(|s| s.path != "/v1/shared/list/state"), "nothing wrapped to the changed key");// B, a member, adds no one and takes no one else off. door(&b, vec![listed(B, &state)]); assert_eq!(over(&b.client(), "shared.add", &json!({ "owner": A, "id": "list-weekend", "number": "+15550100013" })).expect_err("founder only").code, "founder_only"); door(&b, vec![listed(B, &state)]); assert_eq!(over(&b.client(), "shared.remove", &json!({ "owner": A, "id": "list-weekend", "number": A })).expect_err("founder only").code, "founder_only");// A list someone else changed before this build: a member A never added is said on A's phone, once a membership.letmut tampered = state.clone(); tampered["membership"]["members"]["+15550100014"] = json!(public(&c)); door(&a, vec![ listed(A, &tampered), no_notes(),Reply::ok(&json!({ "key": public(&b), "me": A }).to_string()),Reply::json(403, r#"{"code":"not_your_person","message":"not one of your people"}"#), ok(), ]);let read = answer(&a, "shared.read", json!({ "id": "list-weekend" })); assert_eq!(read["doubts"], json!([{ "number": "+15550100014", "why": "not_added_by_you" }]));}