492 lines · 27.7 KB · RustRaw
//! `password.*` on a Cotton Keys phone: a login is a `secret` row sealed v2//! under the vault, listed for AutoFill without its value, revealed on an//! unlocked vault, changed, removed, generated and imported. Every value is//! invented and none is printed: a failing assertion names the field, never//! the value.use base64::engine::general_purpose::URL_SAFE_NO_PAD;use base64::Engine as _;use serde_json::{json, Value};use cotton_core::vault::{seal, wrap, Vmk};use super::over;use crate::handle::CottonHandle;const FAKE: &str = "SYNTHETIC-pass-0001";/// A fresh Cotton Keys phone, kept local (local first).pub(crate) fn phone() -> (tempfile::TempDir, CottonHandle) { let dir = tempfile::tempdir().expect("a temp container"); let manifest = json!({ "genesis": "personal", "flavour": "keys", "name": "Cotton Keys", "databases": "single", "database": "personal", "fan": {"home": false, "tools": false, "opens": "keys"}, "kit": "keys", }); 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"); (dir, handle)}/// This device's vault key, fixed: 32 bytes counting up. Opens nothing real.fn device_secret() -> [u8; 32] { std::array::from_fn(|i| i as u8)}fn vmk() -> Vmk { Vmk::from_bytes(std::array::from_fn(|i| 200u8.wrapping_sub(i as u8)))}fn b64(bytes: &[u8]) -> String { URL_SAFE_NO_PAD.encode(bytes)}pub(crate) fn lent() -> Value { json!(b64(&device_secret()))}pub(crate) fn exec(handle: &CottonHandle, sql: &str, params: &[&str]) { handle .client() .with_writer(|replica| { let bound: Vec<rusqlite::types::Value> = params.iter().map(|v| rusqlite::types::Value::Text((*v).to_string())).collect(); replica.driver.run(sql, &bound).map(|_| ()).map_err(|e| e.to_string()) }) .expect("the seed");}/// The vault as it stands once this device's key is wrapped at version 1.pub(crate) fn wrapped(handle: &CottonHandle) { let client = handle.client(); let workspace = client.with_writer(|replica| Ok(replica.workspace_id.to_string())).unwrap(); let device = client.self_device_id().expect("a device id"); let now = "2026-11-11T09:00:00.000Z"; exec(handle, "INSERT INTO cotton_vault_state (workspace_id, vmk_version, rotated_at, created_at, updated_at) VALUES (?, 1, ?, ?, ?)", &[&workspace, now, now, now]); let public = wrap::public_of(&device_secret()); let wrapped = wrap::wrap(&public, vmk().expose()).expect("a wrap"); exec( handle, "INSERT INTO cotton_vault_keys (id, workspace_id, device_id, public_key, wrapped_vmk, vmk_version, created_at, updated_at) VALUES ('vk-1', ?, ?, ?, ?, 1, ?, ?)", &[&workspace, &device, &b64(&public), &wrapped, now, now], );}fn table() -> String { super::SECRETS.to_string()}pub(crate) fn row(handle: &CottonHandle, id: &str) -> serde_json::Map<String, Value> { handle .client() .with_writer(|replica| { let row = replica .driver .get(&format!("SELECT * FROM {} WHERE id = ?", table()), &[rusqlite::types::Value::Text(id.to_string())]) .map_err(|e| e.to_string())? .expect("the row"); Ok(row .columns() .iter() .map(|(name, value)| { let value = match value { rusqlite::types::Value::Text(t) => Value::from(t.clone()), rusqlite::types::Value::Integer(n) => Value::from(*n), rusqlite::types::Value::Real(x) => Value::from(*x), _ => Value::Null, }; (name.clone(), value) }) .collect()) }) .unwrap()}fn add(handle: &CottonHandle, site: &str, username: &str, password: &str) -> String { let asked = json!({"site": site, "username": username, "password": password, "privateKey": lent()}); over(&handle.client(), "password.add", &asked).expect("added")["id"].as_str().unwrap().to_string()}fn revealed(handle: &CottonHandle, id: &str) -> Value { over(&handle.client(), "password.reveal", &json!({"id": id, "privateKey": lent()})).expect("revealed")}// RULE (owner, 11 Nov 2026): a password's secret is sealed exactly as a// passkey's private key is: v2 under the vault master key, bound to its row's// id, its key version in the row's own vmk_version column, written by this// device; no hint and nothing under the Worker's key; a person or token// patching the sealed column is refused.#[test]fn an_added_login_is_a_row_sealed_on_this_device() { let (_dir, handle) = phone(); wrapped(&handle); let id = add(&handle, "https://Mail.Invented.test/login", "ada@invented.test", FAKE); let stored = row(&handle, &id); assert_eq!(stored["kind"], "login"); assert_eq!(stored["name"], "mail.invented.test", "a login with no name is named by its site"); assert_eq!(stored["site"], "mail.invented.test"); assert_eq!(stored["username"], "ada@invented.test"); assert_eq!(stored["vmk_version"], 1); assert!(stored["hint"].is_null() && stored.get("sealed").is_none_or(Value::is_null), "no hint and no Worker-sealed value"); let sealed = stored["value_enc"].as_str().unwrap(); assert!(sealed.starts_with(seal::SEAL_PREFIX), "sealed v2"); assert!(!serde_json::to_string(&stored).unwrap().contains("SYNTHETIC"), "the value is in no column"); let opened = seal::open(&vmk(), &id, 1, sealed).expect("bound to this row's id"); let payload: Value = serde_json::from_slice(&opened).unwrap(); assert!(payload == json!({"kind": "login", "password": FAKE}), "the vault's typed payload"); let held = over(&handle.client(), "password.add", &json!({"site": "mail.invented.test", "username": "ada@invented.test", "password": "SYNTHETIC-pass-0002", "privateKey": lent()})).unwrap_err(); assert_eq!(held.code, "password_held"); let patch = crate::methods::dispatch(&handle, "records.update", &json!({"table": "secret", "id": id, "patch": {"value_enc": "v2:forged"}})); assert!(patch.is_err(), "the readonly column refuses an authored patch");}// RULE (owner, 11 Nov 2026): the list for AutoFill names each login by site,// user name, name and id, and never a value, a sealed column or a hint; a// row the Worker sealed (its k1 text stays in the object's `sealed`, so the// copy holds no value_enc) is listed but does not open here, and is left as// it was.#[test]fn the_list_names_no_value() { let (_dir, handle) = phone(); wrapped(&handle); let mail = add(&handle, "mail.invented.test", "ada@invented.test", FAKE); add(&handle, "bank.invented.test", "ada", "SYNTHETIC-pass-0002"); let workspace = handle.client().with_writer(|replica| Ok(replica.workspace_id.to_string())).unwrap(); exec( &handle, &format!("INSERT INTO {} (id, workspace_id, name, kind, site, username, hint, created_at, updated_at) VALUES ('worker-1', ?, 'Old', 'login', 'old.invented.test', 'ada', 'XXXX', '2026-10-01T00:00:00Z', '2026-10-01T00:00:00Z')", table()), &[&workspace], ); let listed = over(&handle.client(), "password.list", &json!({})).expect("listed"); let text = listed.to_string(); for never in ["SYNTHETIC", "value_enc", "sealed", "hint", "XXXX"] { assert!(!text.contains(never), "the list carries {never}"); } let sites: Vec<&str> = listed["passwords"].as_array().unwrap().iter().map(|one| one["site"].as_str().unwrap()).collect(); assert_eq!(sites, ["bank.invented.test", "mail.invented.test", "old.invented.test"]); let opens: Vec<bool> = listed["passwords"].as_array().unwrap().iter().map(|one| one["opens"].as_bool().unwrap()).collect(); assert_eq!(opens, [true, true, false]); let found = over(&handle.client(), "password.list", &json!({"q": "MAIL"})).unwrap(); assert_eq!(found["passwords"].as_array().unwrap().len(), 1); assert_eq!(found["passwords"][0]["id"], json!(mail)); let old = over(&handle.client(), "password.reveal", &json!({"id": "worker-1", "privateKey": lent()})).unwrap_err(); assert_eq!(old.code, "not_sealed_here"); assert!(!old.message.contains("SYNTHETIC")); let left = row(&handle, "worker-1"); assert!(left["value_enc"].is_null() && left["hint"] == json!("XXXX") && left["last_used_at"].is_null(), "the Worker's row is left as it was");}// RULE (owner, 11 Nov 2026): reveal and copy open one password on an unlocked// vault and stamp its last use; a locked vault refuses vault_locked in words// and nothing is answered.#[test]fn reveal_opens_on_an_unlocked_vault_and_refuses_a_locked_one() { let (_dir, handle) = phone(); wrapped(&handle); let id = add(&handle, "mail.invented.test", "ada@invented.test", FAKE); let locked = over(&handle.client(), "password.reveal", &json!({"id": id})).unwrap_err(); assert_eq!(locked.code, "vault_locked"); assert_eq!(locked.message, "The vault is locked. Unlock it to see this."); let opened = revealed(&handle, &id); assert_eq!(opened["site"], "mail.invented.test"); assert!(opened["payload"]["password"] == json!(FAKE), "the payload opens"); assert!(opened["copies"] == json!(FAKE), "Copy takes the login's password, as the core says"); assert!(row(&handle, &id)["last_used_at"].is_string(), "a reveal is a use"); let missing = over(&handle.client(), "password.reveal", &json!({"id": "nobody", "privateKey": lent()})).unwrap_err(); assert_eq!(missing.code, "password_not_found");}// RULE (owner, 11 Nov 2026): a change of the plain columns needs no vault; a// change of the password, notes or code opens the payload, changes it and// seals it again; remove moves the row to the bin and the list loses it.#[test]fn change_reseals_the_payload_and_remove_bins_the_row() { let (_dir, handle) = phone(); wrapped(&handle); let id = add(&handle, "mail.invented.test", "ada@invented.test", FAKE); over(&handle.client(), "password.change", &json!({"id": id, "name": "Invented Mail", "username": "ada2@invented.test"})).expect("renamed, locked"); let stored = row(&handle, &id); assert_eq!((stored["name"].as_str(), stored["username"].as_str()), (Some("Invented Mail"), Some("ada2@invented.test"))); let before = stored["value_enc"].clone(); let locked = over(&handle.client(), "password.change", &json!({"id": id, "password": "SYNTHETIC-pass-0009"})).unwrap_err(); assert_eq!(locked.code, "vault_locked"); over(&handle.client(), "password.change", &json!({"id": id, "password": "SYNTHETIC-pass-0009", "notes": "SYNTHETIC note", "privateKey": lent()})).expect("changed"); assert_ne!(row(&handle, &id)["value_enc"], before, "sealed again"); let opened = revealed(&handle, &id); assert!(opened["payload"] == json!({"kind": "login", "password": "SYNTHETIC-pass-0009", "notes": "SYNTHETIC note"}), "the payload changed"); over(&handle.client(), "password.change", &json!({"id": id, "notes": null, "privateKey": lent()})).expect("notes cleared"); assert!(revealed(&handle, &id)["payload"].get("notes").is_none(), "notes cleared"); let removed = over(&handle.client(), "password.remove", &json!({"id": id})).expect("removed"); assert_eq!(removed["removed"], true); assert_eq!(over(&handle.client(), "password.list", &json!({})).unwrap()["passwords"], json!([])); assert_eq!(over(&handle.client(), "password.remove", &json!({"id": id})).unwrap_err().code, "password_not_found");}// RULE (owner, 11 Nov 2026): a generated password follows a rule held as// data: the shipped one, or the one the caller hands over, refused in words// when it cannot make a password.#[test]fn generate_follows_the_rule_as_data() { let (_dir, handle) = phone(); let made = over(&handle.client(), "password.generate", &json!({})).expect("made"); assert_eq!(made["password"].as_str().unwrap().chars().count(), 20); assert_eq!(made["rule"]["length"], 20); let pin = over(&handle.client(), "password.generate", &json!({"rule": {"length": 6, "classes": [{"id": "digits", "chars": "0123456789", "at_least": 6}]}})).expect("a pin"); assert!(pin["password"].as_str().unwrap().chars().all(|ch| ch.is_ascii_digit())); let bad = over(&handle.client(), "password.generate", &json!({"rule": {"length": 0, "classes": []}})).unwrap_err(); assert_eq!(bad.code, "bad_rule");}const APPLE_CSV: &str = include_str!("../../../cotton-core/tests/fixtures/passwords/apple.csv");// RULE (owner, 11 Nov 2026): Apple Passwords' CSV export lands each login as// add lands one, sealed v2; a row with no password and a login already kept// are skipped and said; a locked vault refuses the whole file and writes// nothing.#[test]fn an_apple_csv_lands_each_login_sealed() { let (_dir, handle) = phone(); wrapped(&handle); let locked = over(&handle.client(), "password.importCsv", &json!({"csv": APPLE_CSV})).unwrap_err(); assert_eq!(locked.code, "vault_locked"); assert_eq!(over(&handle.client(), "password.list", &json!({})).unwrap()["passwords"], json!([])); let answer = over(&handle.client(), "password.importCsv", &json!({"csv": APPLE_CSV, "privateKey": lent()})).expect("imported"); let imported = answer["imported"].as_array().unwrap(); assert_eq!(imported.len(), 3); assert_eq!(imported[0]["site"], "mail.invented.test"); assert_eq!(answer["skipped"], json!([{"title": "No password", "reason": "it has no password"}])); assert_eq!(answer["unnamed"], json!(["Favourite"])); // What it says is the core's, the same on both phones. assert_eq!(answer["said"], "3 passwords imported, 1 skipped.\nNo password: it has no password"); assert!(!answer.to_string().contains("SYNTHETIC"), "the answer names no value"); let id = imported[0]["id"].as_str().unwrap(); assert!(row(&handle, id)["value_enc"].as_str().unwrap().starts_with(seal::SEAL_PREFIX)); assert!(revealed(&handle, id)["payload"]["password"] == json!("SYNTHETIC-pass-0001")); let again = over(&handle.client(), "password.importCsv", &json!({"csv": APPLE_CSV, "privateKey": lent()})).expect("twice"); assert_eq!(again["imported"], json!([])); assert_eq!(again["skipped"].as_array().unwrap().len(), 4, "{}", again["skipped"]); let broken = over(&handle.client(), "password.importCsv", &json!({"csv": "Name\nx", "privateKey": lent()})).unwrap_err(); assert_eq!(broken.code, "bad_export");}/// A synthetic Credential Exchange export carrying logins beside nothing else.fn cxf_logins() -> String { json!({ "version": {"major": 1, "minor": 0}, "exporterRpId": "exporter.invented.test", "exporterDisplayName": "Synthetic Exporter", "timestamp": 1_735_689_600u64, "accounts": [{ "id": "YWNjb3VudA", "username": "", "email": "ada@invented.test", "collections": [], "items": [ {"id": "aXRlbS0x", "title": "Invented Mail", "creationAt": 1_735_689_600u64, "scope": {"urls": ["https://mail.invented.test/login"], "androidApps": []}, "credentials": [ {"type": "basic-auth", "username": {"fieldType": "string", "value": "ada@invented.test"}, "password": {"fieldType": "concealed-string", "value": "SYNTHETIC-pass-0001"}}, {"type": "totp", "secret": "SYNTHETICSECRET", "period": 30, "digits": 6, "algorithm": "sha1"}]}, {"id": "aXRlbS0y", "title": "Wifi", "credentials": [{"type": "wifi", "ssid": {"fieldType": "string", "value": "SYNTHETIC"}}]} ] }] }) .to_string()}// RULE (owner, 11 Nov 2026): the Credential Exchange import Apple's Passwords// app hands Cotton Keys lands its password items beside its passkeys, each a// login sealed as add seals one, made when the export says; a login already// kept is skipped and said.#[test]fn a_cxf_export_lands_its_passwords_sealed() { let (_dir, handle) = phone(); wrapped(&handle); let asked = json!({"json": cxf_logins(), "privateKey": lent()}); let answer = crate::phone::passkeys::over(&handle.client(), "passkey.importCxf", &asked).expect("imported"); assert_eq!(answer["imported"], json!([]), "no passkey in this export"); let passwords = answer["passwords"].as_array().unwrap(); assert_eq!(passwords.len(), 1); assert_eq!(passwords[0]["site"], "mail.invented.test"); assert_eq!(answer["skipped"].as_array().unwrap().len(), 1, "the wifi item: {}", answer["skipped"]); assert!(!answer.to_string().contains("SYNTHETIC"), "the answer names no value"); let id = passwords[0]["id"].as_str().unwrap(); let stored = row(&handle, id); assert_eq!(stored["created_at"], "2025-01-01T00:00:00.000Z", "made when the export says"); assert_eq!(stored["name"], "Invented Mail"); let opened = revealed(&handle, id); assert!(opened["payload"]["password"] == json!("SYNTHETIC-pass-0001")); assert!(opened["payload"]["totp"].as_str().is_some_and(|code| code.starts_with("otpauth://totp/")), "the code rides with its password"); let again = crate::phone::passkeys::over(&handle.client(), "passkey.importCxf", &asked).expect("twice"); assert_eq!(again["passwords"], json!([])); assert!(again["skipped"].as_array().unwrap().iter().any(|skip| skip["reason"] == "this login is already kept here"));}// RULE (owner, 11 Nov 2026): Cotton Keys' provider fills passwords from the// shared keychain, which holds each login sealed on this device opened under// a stamp; the mirror answers only what the keychain lacks or holds stale and// names what must leave it, opening the vault only when something must be// opened; a Worker-sealed login never reaches the keychain.#[test]fn the_mirror_answers_what_the_keychain_lacks_and_what_must_leave() { let (_dir, handle) = phone(); wrapped(&handle); let mail = add(&handle, "mail.invented.test", "ada@invented.test", FAKE); let workspace = handle.client().with_writer(|replica| Ok(replica.workspace_id.to_string())).unwrap(); exec( &handle, &format!("INSERT INTO {} (id, workspace_id, name, kind, site, username, hint, created_at, updated_at) VALUES ('worker-1', ?, 'Old', 'login', 'old.invented.test', 'ada', 'XXXX', '2026-10-01T00:00:00Z', '2026-10-01T00:00:00Z')", table()), &[&workspace], ); let locked = over(&handle.client(), "password.mirror", &json!({"held": {"gone-1": "x"}})).expect("locked still answers"); assert_eq!(locked["locked"], true); assert_eq!(locked["passwords"], json!([])); assert_eq!(locked["gone"], json!(["gone-1"]), "what must leave needs no vault"); let first = over(&handle.client(), "password.mirror", &json!({"held": {}, "privateKey": lent()})).expect("mirrored"); let passwords = first["passwords"].as_array().unwrap(); assert_eq!(passwords.len(), 1, "the Worker's row never reaches the keychain"); assert_eq!(passwords[0]["id"], json!(mail)); assert_eq!(passwords[0]["site"], "mail.invented.test"); assert!(passwords[0]["password"] == json!(FAKE), "opened"); let stamp = passwords[0]["stamp"].as_str().unwrap().to_string(); let same = over(&handle.client(), "password.mirror", &json!({"held": {mail.clone(): stamp.clone()}})).expect("nothing to open"); assert_eq!((same["passwords"].clone(), same["locked"].clone()), (json!([]), json!(false)), "held fresh: no vault asked"); over(&handle.client(), "password.used", &json!({"id": mail})).expect("a use"); let used = over(&handle.client(), "password.mirror", &json!({"held": {mail.clone(): stamp.clone()}})).unwrap(); assert_eq!(used["passwords"], json!([]), "a use leaves the stamp"); over(&handle.client(), "password.change", &json!({"id": mail, "password": "SYNTHETIC-pass-0003", "privateKey": lent()})).unwrap(); let stale = over(&handle.client(), "password.mirror", &json!({"held": {mail.clone(): stamp.clone()}, "privateKey": lent()})).unwrap(); assert!(stale["passwords"][0]["password"] == json!("SYNTHETIC-pass-0003"), "a changed password is mirrored again"); assert_ne!(stale["passwords"][0]["stamp"], json!(stamp)); over(&handle.client(), "password.remove", &json!({"id": mail})).unwrap(); let removed = over(&handle.client(), "password.mirror", &json!({"held": {mail.clone(): stamp}})).unwrap(); assert_eq!(removed["gone"], json!([mail]));}// RULE (owner, 11 Nov 2026): a fill the provider made is a use: its last use// is stamped, with no vault; a login gone since says so.#[test]fn a_fill_stamps_its_last_use() { let (_dir, handle) = phone(); wrapped(&handle); let id = add(&handle, "mail.invented.test", "ada@invented.test", FAKE); let answer = over(&handle.client(), "password.used", &json!({"id": id, "usedAt": "2026-11-11T10:00:00.000Z"})).expect("stamped, locked"); assert_eq!(answer["last_used_at"], "2026-11-11T10:00:00.000Z"); assert_eq!(row(&handle, &id)["last_used_at"], "2026-11-11T10:00:00.000Z"); assert_eq!(over(&handle.client(), "password.used", &json!({"id": "nobody"})).unwrap_err().code, "password_not_found");}// RULE (owner, 11 Nov 2026): a password a site's form hands Cotton Keys (iOS// 26.2's save request) is added when new; when the site and user name are// kept already, the login takes the new password and keeps its notes; a login// the Worker sealed is never touched.#[test]fn save_adds_a_new_login_and_changes_a_kept_one() { let (_dir, handle) = phone(); wrapped(&handle); let made = over(&handle.client(), "password.save", &json!({"site": "https://mail.invented.test/signup", "username": "ada@invented.test", "password": FAKE, "privateKey": lent()})).expect("saved"); assert_eq!(made["made"], true); let id = made["id"].as_str().unwrap().to_string(); over(&handle.client(), "password.change", &json!({"id": id, "notes": "SYNTHETIC note", "privateKey": lent()})).unwrap(); let locked = over(&handle.client(), "password.save", &json!({"site": "mail.invented.test", "username": "ada@invented.test", "password": "SYNTHETIC-pass-0004"})).unwrap_err(); assert_eq!(locked.code, "vault_locked"); let changed = over(&handle.client(), "password.save", &json!({"site": "mail.invented.test", "username": "ada@invented.test", "password": "SYNTHETIC-pass-0004", "privateKey": lent()})).expect("changed"); assert_eq!((changed["id"].clone(), changed["made"].clone()), (json!(id), json!(false))); assert!(revealed(&handle, &id)["payload"] == json!({"kind": "login", "password": "SYNTHETIC-pass-0004", "notes": "SYNTHETIC note"})); assert!(!changed.to_string().contains("SYNTHETIC"), "the answer names no value"); let workspace = handle.client().with_writer(|replica| Ok(replica.workspace_id.to_string())).unwrap(); exec( &handle, &format!("INSERT INTO {} (id, workspace_id, name, kind, site, username, hint, created_at, updated_at) VALUES ('worker-1', ?, 'Old', 'login', 'old.invented.test', 'ada', 'XXXX', '2026-10-01T00:00:00Z', '2026-10-01T00:00:00Z')", table()), &[&workspace], ); let old = over(&handle.client(), "password.save", &json!({"site": "old.invented.test", "username": "ada", "password": "SYNTHETIC-pass-0005", "privateKey": lent()})).unwrap_err(); assert_eq!(old.code, "not_sealed_here"); assert!(row(&handle, "worker-1")["value_enc"].is_null(), "the Worker's row is left as it was");}// RULE (owner, 11 Nov 2026): Plus's New password makes a login for the// site typed with a password by the shipped rule, sealed as add seals one;// the answer names the row, never the password.#[test]fn new_makes_a_login_with_a_generated_password() { let (_dir, handle) = phone(); wrapped(&handle); assert_eq!(super::door_method("password_new"), Some("password.new")); assert_eq!(super::door_method("find_book"), None); let locked = over(&handle.client(), "password.new", &json!({"site": "mail.invented.test"})).unwrap_err(); assert_eq!(locked.code, "vault_locked"); let made = over(&handle.client(), "password.new", &json!({"site": "https://mail.invented.test/signup", "privateKey": lent()})).expect("made"); assert_eq!(made.as_object().unwrap().keys().collect::<Vec<_>>(), ["id"], "the answer names the row alone"); let id = made["id"].as_str().unwrap(); assert_eq!(row(&handle, id)["site"], "mail.invented.test"); let opened = revealed(&handle, id); assert_eq!(opened["copies"].as_str().unwrap().chars().count(), 20, "by the shipped rule"); let held = over(&handle.client(), "password.new", &json!({"site": "mail.invented.test", "privateKey": lent()})).unwrap_err(); assert_eq!(held.code, "password_held");}#[test]fn every_password_method_is_a_phone_method() { for method in super::METHODS { assert!(crate::methods::CLIENT_METHODS.contains(&method), "{method}"); assert!(crate::methods::ALL_METHODS.contains(&method), "{method}"); }}/// RULE (OPEN-TABLES.md §3): with the vault open after a pass, every password the Worker still seals under its own/// key is asked for, sealed here under the vault key (it opens with the vault key and nothing else), and handed back/// in one batch; with the vault shut nothing is asked at all. Invented values only.#[test]fn a_password_saved_over_mcp_moves_under_the_vault_key_once_the_vault_is_open() { use std::sync::Arc; use cotton_client::transport::scripted::Reply; use cotton_core::keys::password_row; use cotton_core::vault::payload::SecretPayload; use crate::phone::unlock::tests::{door, fixture_vmk}; use crate::shell::client::phone_tests::attached_on_a_clock; let (_dir, client, _clock) = attached_on_a_clock(); let id = "00000000-0000-4000-8000-0000000000a1"; let served = json!({"rows": [ {"id": id, "version": 7, "payload": json!({"kind": "api_key", "key": "invented-key-0000-1111"}).to_string()}, {"id": "00000000-0000-4000-8000-0000000000a2", "version": 3, "payload": "not a password"}, ], "unopened": 0, "left": 0}); let (object, exchange) = door([Reply::ok(&served.to_string()), Reply::ok(r#"{"moved":1,"skipped":0}"#), Reply::ok(r#"{"rows":[],"unopened":0,"left":0}"#)]); client.set_object_door(Some(Arc::new(object))); // Shut: nothing asked. assert_eq!(super::rewrap(&client).expect("nothing to do"), 0); assert_eq!(exchange.calls(), 0, "a shut vault asks the Worker for nothing"); client.vault().expect("the vault").unlock(fixture_vmk(), 1, client.now()); assert_eq!(super::rewrap(&client).expect("moved"), 1); assert_eq!(exchange.nth(0).method, "GET"); assert_eq!(exchange.nth(1).method, "POST"); let posted: Value = serde_json::from_slice(&exchange.nth(1).body).unwrap(); let rows = posted["rows"].as_array().expect("rows"); assert_eq!(rows.len(), 1, "a payload that is not a password's shape is left where it is"); assert_eq!(rows[0]["id"], id); assert_eq!(rows[0]["version"], 7); assert_eq!(rows[0]["vmk_version"], 1); let value_enc = rows[0]["value_enc"].as_str().expect("value_enc"); assert!(value_enc.starts_with("v2:") && !value_enc.contains("invented-key"), "sealed, never the value"); let row = json!({"value_enc": value_enc, "vmk_version": 1}); let opened = password_row::open(row.as_object().unwrap(), id, &fixture_vmk()).expect("opens with the vault key"); assert_eq!(opened, SecretPayload::ApiKey { key: "invented-key-0000-1111".into(), notes: None }); assert!(password_row::open(row.as_object().unwrap(), id, &cotton_core::vault::Vmk::from_bytes([9; 32])).is_err(), "and with no other key"); assert_eq!(exchange.calls(), 3, "asked again once, and nothing was left"); client.set_object_door(None);}