//! Deleting the account from a phone, against an invented personal object //! that answers by route: the code asked, the code typed back, and nothing of //! the database left on the phone; and a phone told by a pass that the //! account was deleted elsewhere. use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use cotton_client::transport::scripted::{Reply, ScriptedExchange}; use cotton_client::transport::Exchange; use serde_json::{json, Value}; use crate::handle::CottonHandle; use crate::phone::personal_object::{call_with, SIGNED_OUT}; const DATABASE: &str = "11111111-1111-4111-8111-111111111111"; const NUMBER: &str = "+919000000009"; /// The invented object: its definitions, an empty page, the owner, and the deletion's two doors. #[derive(Debug, Default)] struct Deleting { /// Once set, every request is answered as a deleted account's. gone: AtomicBool, /// Past the thirty days: the refusal no longer names a date. erased: AtomicBool, /// Every body the deletion's doors were sent, by path. asked: Mutex>, } impl Exchange for Deleting { fn send( &self, origin: &cotton_client::transport::Origin, request: &cotton_client::transport::http1::Http1Request<'_>, ceiling: std::time::Duration, ) -> Result, String> { let body: Value = request.body.and_then(|b| serde_json::from_slice(b).ok()).unwrap_or(Value::Null); let reply = if request.path == crate::phone::account_delete::KEEP || request.path == crate::phone::account_delete::LEAVE { self.asked.lock().unwrap().push((request.path.to_string(), json!(request.headers.iter().any(|(k, v)| k.eq_ignore_ascii_case("authorization") && v == "Bearer fresh-credential")))); Reply::ok(r#"{"kept": true, "left": true}"#) } else if request.path == "/v1/sign-in" { Reply::ok(&json!({"credential": "fresh-credential", "person": {"id": "owner-person"}, "expires_in": 100, "database_id": DATABASE, "deleting": {"erase_at": "2026-12-22T09:00:00.000Z"}}).to_string()) } else if self.erased.load(Ordering::SeqCst) { Reply::json(410, r#"{"code": "account_deleted", "message": "This account was deleted."}"#) } else if self.gone.load(Ordering::SeqCst) { Reply::json(410, r#"{"code": "account_deleted", "message": "This account is set to be deleted on 2026-12-22. Sign in to keep it."}"#) } else if request.path.starts_with("/v1/definitions") { Reply::ok(&json!({"business": {"kind": "personal", "database_id": DATABASE, "timezone": "Asia/Kolkata"}, "tools": [], "tables": [], "flavour": {}, "boards": [], "etag": "e1"}).to_string()) } else if request.path.starts_with("/v1/sync") { Reply::ok(&json!({"version": 3, "rows": [], "server_time": "2026-11-22T09:00:00.000Z", "device": null}).to_string()) } else if request.path.starts_with("/v1/me") { Reply::ok(&json!({"person": {"id": "owner-person", "phone": NUMBER, "role": "owner"}, "version": 3}).to_string()) } else if request.path == crate::phone::account_delete::CODE { self.asked.lock().unwrap().push((request.path.to_string(), body)); Reply::ok(r#"{"challenge_id": "invented-challenge", "expires_in": 300}"#) } else if request.path == crate::phone::account_delete::DELETE { self.asked.lock().unwrap().push((request.path.to_string(), body.clone())); if body["code"] == "123456" && body["confirm"] == "delete" && body["challenge_id"] == "invented-challenge" { self.gone.store(true, Ordering::SeqCst); Reply::json(202, r#"{"deleting": true, "started_at": "2026-11-22T09:00:00.000Z", "erase_at": "2026-12-22T09:00:00.000Z"}"#) } else { Reply::json(401, r#"{"code": "invalid_code", "message": "invalid or expired code"}"#) } } else { Reply::ok("{}") }; ScriptedExchange::new([reply]).send(origin, request, ceiling) } fn send_stream( &self, origin: &cotton_client::transport::Origin, request: &cotton_client::transport::http1::Http1Request<'_>, body: &mut dyn std::io::Read, length: u64, ceiling: std::time::Duration, ) -> Result, String> { let mut bytes = Vec::new(); std::io::Read::read_to_end(&mut std::io::Read::take(body, length), &mut bytes).map_err(|error| error.to_string())?; let whole = cotton_client::transport::http1::Http1Request { body: Some(&bytes), headers: request.headers.clone(), ..*request }; self.send(origin, &whole, ceiling) } } fn phone() -> (tempfile::TempDir, CottonHandle) { let dir = tempfile::tempdir().expect("a temp container"); 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(serde_json::from_str(include_str!("../../../../apps/cotton/App/CottonManifest/flavour.json")).expect("Cotton's manifest")), }) .expect("an open core"); (dir, handle) } fn connected(object: &Arc) -> (tempfile::TempDir, CottonHandle) { let (dir, handle) = phone(); let ask = json!({"server": "https://cotton.example.com", "databaseId": DATABASE, "credential": "synthetic-credential", "deviceName": "An invented phone"}); call_with(&handle, "personal.connect", &ask, Arc::clone(object) as Arc).expect("connected"); assert!(handle.client().layout().replica(DATABASE).exists(), "the copy is made"); (dir, handle) } /// Every file under the container whose path or contents name the database. fn named_files(dir: &tempfile::TempDir) -> Vec { fn walk(at: &std::path::Path, out: &mut Vec) { for entry in std::fs::read_dir(at).into_iter().flatten().flatten() { let path = entry.path(); let names = path.is_file() && path.extension().is_some_and(|ext| ext == "json") && std::fs::read_to_string(&path).is_ok_and(|text| text.contains(DATABASE)); if path.to_string_lossy().contains(DATABASE) || names { out.push(path.to_string_lossy().to_string()); } if path.is_dir() { walk(&path, out); } } } let mut out = Vec::new(); walk(dir.path(), &mut out); out } #[test] fn the_page_says_what_goes_what_stays_and_that_it_goes_in_thirty_days() { let page = crate::phone::account_delete::page("Days"); assert!(page["when"].as_str().is_some_and(|words| words.contains("30 days")), "{page}"); for key in ["row", "heading", "whatGoes", "whatStays", "when", "otherApps", "send", "codeLabel", "confirm", "cancel", "working"] { assert!(page[key].as_str().is_some_and(|words| !words.is_empty()), "{key} has words: {page}"); } assert_eq!(page["row"], "Delete account"); assert!(page["otherApps"].as_str().is_some_and(|words| words.contains("Days") && !words.contains('{')), "the app is named: {page}"); // The app the person is in, one account shared by every Cotton app, and no messaging app (coordinator, 24 Nov 2026). assert_eq!(page["whatStays"], "You use one Cotton account in Days and in every other Cotton app."); for key in ["whatGoes", "whatStays", "otherApps", "when"] { assert!(!page[key].as_str().unwrap_or_default().to_lowercase().contains("messag"), "{key} names no messaging app: {page}"); } } #[test] fn a_code_typed_back_deletes_the_account_and_nothing_of_it_stays_on_the_phone() { let object = Arc::new(Deleting::default()); let (dir, handle) = connected(&object); let code = crate::phone::account_delete::call(&handle, "account.deleteCode", &json!({})).expect("a code asked"); assert_eq!(code["challengeId"], "invented-challenge"); assert!(code["sent"].as_str().is_some_and(|line| line.contains(NUMBER)), "the line names the number: {code}"); // A wrong code is said in the kit's words, and nothing goes. let wrong = crate::phone::account_delete::call(&handle, "account.delete", &json!({"challengeId": "invented-challenge", "code": "000000"})).expect_err("refused"); assert_eq!(wrong.code, "invalid_code"); assert_eq!(wrong.message, crate::phone::account_delete::say("wrong", &[])); assert!(handle.client().layout().replica(DATABASE).exists(), "the copy stays while nothing was deleted"); let deleted = crate::phone::account_delete::call(&handle, "account.delete", &json!({"challengeId": "invented-challenge", "code": "123456", "app": "Days"})).expect("deleted"); assert_eq!(deleted["deleted"], true); assert_eq!(deleted["heading"], crate::phone::account_delete::say("done_heading", &[])); assert!(deleted["line"].as_str().is_some_and(|line| line.contains("Days") && line.contains("Your account will be deleted on 22 December. Until then, sign in to keep it.")), "{deleted}"); assert!(confirmed(&object), "the deletion was asked with confirm: delete"); assert_eq!(deleted["databaseId"], DATABASE, "the app is told which data key to forget"); // Nothing of the database is left on the phone, and it stands on a fresh database of its own. assert!(named_files(&dir).is_empty(), "nothing of the database stays: {:?}", named_files(&dir)); let held = crate::phone::copy_aside::held(handle.client().layout()).and_then(|held| held.workspace_id); assert!(held.is_some_and(|id| id != DATABASE), "a fresh local database stands"); } fn confirmed(object: &Deleting) -> bool { object.asked.lock().unwrap().iter().any(|(path, body)| path == crate::phone::account_delete::DELETE && body["confirm"] == "delete") } #[test] fn a_pass_told_the_account_was_deleted_elsewhere_says_so_and_forget_leaves_nothing() { let object = Arc::new(Deleting::default()); let (dir, handle) = connected(&object); object.gone.store(true, Ordering::SeqCst); assert!(handle.client().sync_now().is_err(), "the pass is refused"); let said: Vec = handle.events().buffered_events().into_iter().filter(|event| event["payload"]["phase"] == "personal").collect(); assert_eq!(said.len(), 1, "told once: {said:?}"); assert_eq!(said[0]["payload"]["stage"], SIGNED_OUT); assert_eq!(said[0]["payload"]["code"], "account_deleted"); assert_eq!(said[0]["payload"]["deleted"], true); assert_eq!(said[0]["payload"]["words"]["heading"], crate::phone::account_delete::say("elsewhere_heading", &[])); assert!(said[0]["payload"]["words"]["line"].as_str().is_some_and(|line| line.contains("22 December") && !line.contains('{')), "{said:?}"); let forgot = crate::phone::account_delete::call(&handle, "account.forget", &json!({})).expect("forgot"); assert_eq!(forgot["forgot"], true); assert_eq!(forgot["databaseId"], DATABASE); assert!(named_files(&dir).is_empty(), "nothing of the database stays: {:?}", named_files(&dir)); } #[test] fn forget_also_takes_a_copy_set_aside_by_an_earlier_sign_out() { let object = Arc::new(Deleting::default()); let (dir, handle) = connected(&object); crate::phone::personal_object::stand_local(&handle, &json!({"signedOut": true})).expect("signed out"); assert!(crate::phone::copy_aside::is_aside(handle.client().layout(), DATABASE), "set aside"); // The account then deleted from elsewhere: the copy aside goes too. crate::phone::copy_aside::forget(handle.client().layout(), DATABASE, &cotton_client::copy_keep::PersonsAct::of_the_person()).expect("forgot"); assert!(!crate::phone::copy_aside::is_aside(handle.client().layout(), DATABASE)); assert!(named_files(&dir).is_empty(), "nothing of the database stays: {:?}", named_files(&dir)); } #[test] fn a_phone_away_past_the_date_says_the_account_was_deleted() { let object = Arc::new(Deleting::default()); let (dir, handle) = connected(&object); object.gone.store(true, Ordering::SeqCst); object.erased.store(true, Ordering::SeqCst); // A pass already under way when the phone came back may answer first; the next one is refused. let mut said: Vec = Vec::new(); for _ in 0..3 { let _ = handle.client().sync_now(); said = handle.events().buffered_events().into_iter().filter(|event| event["payload"]["phase"] == "personal").collect(); if !said.is_empty() { break; } } assert!(!said.is_empty(), "the pass is refused and the phone told"); assert_eq!(said[0]["payload"]["deleted"], true); assert_eq!(said[0]["payload"]["words"]["heading"], crate::phone::account_delete::say("erased_heading", &[])); crate::phone::account_delete::call(&handle, "account.forget", &json!({})).expect("forgot"); assert!(named_files(&dir).is_empty(), "it clears itself: {:?}", named_files(&dir)); } #[test] fn a_sign_in_in_the_thirty_days_asks_keep_or_leave_with_the_sign_ins_own_credential() { let object = Arc::new(Deleting::default()); let (_dir, handle) = phone(); let signed = call_with(&handle, "personal.signIn", &json!({"server": "https://cotton.example.com", "databaseId": DATABASE, "challengeId": "c", "code": "123456"}), Arc::clone(&object) as Arc).expect("signed in"); let deleting = &signed["deleting"]; assert_eq!(deleting["date"], "22 December"); assert_eq!(deleting["keep"], "Keep my account"); assert_eq!(deleting["leave"], "Leave it to be deleted"); assert!(deleting["line"].as_str().is_some_and(|line| line.contains("22 December")), "{deleting}"); let ask = json!({"server": "https://cotton.example.com", "credential": signed["credential"]}); let kept = crate::phone::account_delete::call_with(&handle, "account.keep", &ask, object.as_ref()).expect("kept"); assert_eq!(kept["kept"], true); assert_eq!(kept["line"], crate::phone::account_delete::say("kept", &[])); let left = crate::phone::account_delete::call_with(&handle, "account.leave", &ask, object.as_ref()).expect("left"); assert_eq!(left["left"], true); let asked = object.asked.lock().unwrap().clone(); assert_eq!(asked, vec![(crate::phone::account_delete::KEEP.to_string(), json!(true)), (crate::phone::account_delete::LEAVE.to_string(), json!(true))], "each with the sign-in's own credential"); } #[test] fn the_date_reads_as_a_day_and_a_month() { use crate::phone::account_delete::day_and_month; assert_eq!(day_and_month("2026-12-22T09:00:00.000Z"), "22 December"); assert_eq!(day_and_month("2027-01-05T00:00:00.000Z"), "5 January"); assert_eq!(day_and_month("soon"), "soon"); }