//! COTTON SECRETS, PROVEN ON DEV (assets/design/keys/CONTRACT.md row 19): two invented people, each a Secrets phone //! through the C ABI against the dev Worker, who accept each other, check each other's sharing key, share a secret, //! open it, take it back, change it, and ask and answer, through the calls the screens use. Every number, name and //! value is invented. The secrets proof script runs it. //! //! What it shows: the holder opens the secret on their own phone; each open is counted where the value is fetched; //! a take back is said as far as the server saw; a secret seen and taken back stays "still known" until it is //! changed; an ask is answered from the app. What the server keeps is checked by the Worker's own tests and by the //! in-memory network in `phone/secrets_app_tests.rs` (`the_server_reads_none_of_it`): the phones post only sealed //! boxes, which this run's phones did too, through the same code. //! //! 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 numbers (+1555019). 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-secrets"; const FLAVOUR: &str = "keys"; const WAIT: Duration = Duration::from_secs(45); 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 { 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 { 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 step(name: &str, started: Instant) { println!("SECRETS PROOF {name} ({:.1} s)", started.elapsed().as_secs_f64()); } #[test] fn two_invented_people_share_open_take_back_change_and_ask() { 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 giver = Phone::open(&walk, &walk.number(1), "giver"); let holder = Phone::open(&walk, &walk.number(2), "holder"); for phone in [&giver, &holder] { phone.sign_in(&walk); phone.found_key(); } step("signed in, keys founded", started); // Your people: each adds the other in Comms. giver.must("people.add", json!({ "number": holder.number })); holder.must("people.add", json!({ "number": giver.number })); giver.until("secrets.people", json!({}), "the holder in Your people", |a| a["people"].as_array().is_some_and(|p| p.iter().any(|row| row["number"] == holder.number.as_str()))); step("accepted each other", started); // S1: the same six words on both phones, then each confirms. let mine = giver.must("secrets.check", json!({ "number": holder.number })); let theirs = holder.must("secrets.check", json!({ "number": giver.number })); assert_eq!(mine["words"], theirs["words"], "the same six words on both phones"); giver.must("secrets.check.confirm", json!({ "number": holder.number })); holder.must("secrets.check.confirm", json!({ "number": giver.number })); step("checked each other", started); let id = giver.lent("keys.add", json!({ "kind": "api_key", "name": "Invented proof key", "fields": { "key": VALUE } }))["id"].as_str().expect("an id").to_string(); let share = giver.lent("secrets.share", json!({ "id": id, "number": holder.number, "may": "copy", "until": "week" }))["share"].as_str().expect("a share").to_string(); step("shared", started); holder.until("secrets.inbox", json!({}), "the share in the holder's list", |a| a["rows"].as_array().is_some_and(|rows| rows.iter().any(|row| row["share"] == share.as_str()))); let field = holder.must("secrets.shared.field", json!({ "share": share, "field": "key" })); assert_eq!(field["value"], VALUE, "the holder opens it on their own phone"); giver.until("secrets.holders", json!({ "id": id }), "the open counted", |a| a["holders"][0]["opens"] == json!(1)); step("opened, and the open counted", started); let plan = giver.lent("secrets.take.plan", json!({ "id": id, "number": holder.number })); assert!(plan["after"].as_str().unwrap_or_default().contains("opened it once"), "{}", plan["after"]); giver.must("secrets.take", json!({ "id": id, "numbers": [holder.number] })); holder.until("secrets.inbox", json!({}), "the share gone from the holder", |a| !a["rows"].as_array().is_some_and(|rows| rows.iter().any(|row| row["share"] == share.as_str()))); assert!(holder.call("secrets.shared.field", json!({ "share": share, "field": "key" })).is_err(), "taken back: it opens no more"); let known = giver.lent("secrets.holders", json!({ "id": id })); assert_eq!(known["holders"][0]["state"], "still_known"); step("taken back, still known", started); giver.lent("keys.change", json!({ "id": id, "fields": { "key": CHANGED } })); giver.must("secrets.changed", json!({ "id": id })); assert_eq!(giver.must("secrets.holders", json!({ "id": id }))["holders"][0]["state"], "changed"); step("changed at the provider", started); holder.must("secrets.ask", json!({ "number": giver.number, "text": "the invented proof key again", "why": "one more build" })); let asks = giver.until("secrets.asks", json!({}), "the ask arriving", |a| a["rows"].as_array().is_some_and(|rows| !rows.is_empty())); let ask = &asks["rows"][0]; assert_eq!(ask["suggest"]["id"], id.as_str(), "the secret its words name"); giver.lent("secrets.ask.answer", json!({ "ask": ask["ask"], "id": id, "may": "see" })); let inbox = holder.until("secrets.inbox", json!({}), "the answer's share", |a| a["rows"].as_array().is_some_and(|rows| !rows.is_empty())); let again = inbox["rows"][0]["share"].as_str().expect("a share").to_string(); let field = holder.must("secrets.shared.field", json!({ "share": again, "field": "key" })); assert_eq!((field["value"].as_str(), field["mayCopy"].as_bool()), (Some(CHANGED), Some(false)), "the changed value, see only"); step("asked and answered", started); println!("SECRETS PROOF PASSED in {:.1} s (giver {}, holder {})", started.elapsed().as_secs_f64(), giver.number, holder.number); }