//! The installer, over a fake git and a fake server.//!//! Every side effect is behind a seam, so nothing here touches the login//! keychain and nothing here dials anything. The real `git credential` and the//! real route are the runbook's rehearsal.use std::sync::Mutex;use chrono::TimeZone;usesuper::*;usecrate::transport::{ClientAnswer, ServerRefusal};/// A `git credential` that remembers one description per (host, username) —/// which is what the keychain is, for this file's purposes.#[derive(Debug, Default)]structFakeGit {/// Every `(verb, stdin)` in order, so a case asserts the BYTES that went/// to the helper and not just that it was called. calls: Mutex<Vec<(String, String)>>,/// `host\u{0}username` → password. stored: Mutex<Vec<(String, String)>>,/// When set, every run answers this sentence instead. refuses: Option<String>,/// `approve` accepts and keeps NOTHING — the measured no-op of a Mac with/// no credential helper configured. silently_drops: bool,}implFakeGit {fn new() -> FakeGit {FakeGit::default() }fn with_no_helper() -> FakeGit {FakeGit { silently_drops: true, ..FakeGit::default() } }/// A git whose keychain already holds `password` under `(host, username)`/// — the Mac the common launch finds.fn holding(host: &str, username: &str, password: &str) -> FakeGit {let git = FakeGit::default(); git.stored .lock() .expect("the lock") .push((format!("{host}\u{0}{username}"), password.to_string())); git }fn refusing(sentence: &str) -> FakeGit {FakeGit { refuses: Some(sentence.to_string()), ..FakeGit::default() } }fn calls(&self) -> Vec<(String, String)> {self.calls.lock().expect("the lock").clone() }fn verbs(&self) -> Vec<String> {self.calls() .into_iter() .map(|(verb, _)| verb) .collect() }fn key(input: &str) -> String {let field = |name: &str| { input .lines() .find_map(|line| line.strip_prefix(&format!("{name}="))) .unwrap_or_default() .to_string() }; format!("{}\u{0}{}", field("host"), field("username")) }}implCredentialHelperforFakeGit {fn run(&self, verb: &str, input: &str) -> Result<String, String> {self.calls .lock() .expect("the lock") .push((verb.to_string(), input.to_string()));ifletSome(sentence) = &self.refuses {returnErr(sentence.clone()); }let key = FakeGit::key(input);match verb {"approve" => {if !self.silently_drops {let password = input .lines() .find_map(|line| line.strip_prefix("password=")) .unwrap_or_default() .to_string();self.stored.lock().expect("the lock").push((key, password)); }// "No output should be emitted", and the exit status is 0 in// both cases — which is the whole trap.Ok(String::new()) }"fill" => {let held = self .stored .lock() .expect("the lock") .iter() .find(|(stored, _)| *stored == key) .map(|(_, password)| password.clone());match held {Some(password) => Ok(format!("protocol=https\nhost=x\nusername=u\npassword={password}\n" )),// With no helper and no terminal, a real `fill` fails// loudly. The sentence is git's own shape.None => Err("git credential fill refused — fatal: could not read Username: terminal \ prompts disabled" .to_string(), ), } }"reject" => {self.stored .lock() .expect("the lock") .retain(|(stored, _)| *stored != key);Ok(String::new()) } other => Err(format!("this fake git does not answer `{other}`")), } }}/// A server that answers one scripted reply to the mint and records the body.#[derive(Debug, Default)]structFakeServer { reply: Mutex<Option<(u16, String)>>, seen: Mutex<Vec<(String, String)>>,/// Every method in order, so a case can tell "it asked" from "it minted"/// without the path tuples every other case compares against changing. methods: Mutex<Vec<String>>,/// The ceiling each request asked for, in order — `None` for one that/// took the transport's own. ceilings: Mutex<Vec<Option<u64>>>,/// What `GET /v1/code/credentials` answers, when a case scripts one./// `None` leaves the mint's own reply standing for every verb, which is/// what the cases written before the liveness check expect: a body with no/// `credentials` array reads as "could not ask". listed: Mutex<Option<String>>,}implFakeServer {fn minting(id: &str, secret: &str) -> FakeServer {FakeServer { reply: Mutex::new(Some((201, serde_json::json!({"id": id,"secret": secret,"name": "Studio Mac","scope": "device", }) .to_string(), ))), ..FakeServer::default() } }fn refusing(status: u16, error: &str) -> FakeServer {FakeServer { reply: Mutex::new(Some(( status, serde_json::json!({ "error": error, "code": "device_revoked" }).to_string(), ))), ..FakeServer::default() } }/// What the list route answers. `holding` names the live credentials; a/// case that wants one revoked or expired scripts the rows itself.fn holding(self, rows: serde_json::Value) -> FakeServer { *self.listed.lock().expect("the lock") =Some(serde_json::json!({ "credentials": rows }).to_string());self }fn seen(&self) -> Vec<(String, String)> {self.seen.lock().expect("the lock").clone() }fn methods(&self) -> Vec<String> {self.methods.lock().expect("the lock").clone() }fn ceilings(&self) -> Vec<Option<u64>> {self.ceilings.lock().expect("the lock").clone() }/// How many credentials this server was asked to mint.fn mints(&self) -> usize {self.methods() .iter() .filter(|method| *method == "POST") .count() }}implServerFetchforFakeServer {fn call(&self, request: ClientRequest) -> Result<ClientAnswer, ServerRefusal> {self.ceilings .lock() .expect("the lock") .push(request.ceiling_ms);self.seen.lock().expect("the lock").push(( request.path.clone(), request .body .as_ref() .map(|bytes| String::from_utf8_lossy(bytes).to_string()) .unwrap_or_default(), ));self.methods .lock() .expect("the lock") .push(request.method.to_string());if request.method == "GET" {ifletSome(listed) = self.listed.lock().expect("the lock").clone() {returnOk(ClientAnswer { status: 200, body: listed.into_bytes(), }); } }let reply = self.reply.lock().expect("the lock").clone();match reply {Some((status, body)) => Ok(ClientAnswer { status, body: body.into_bytes(), }),None => Err(ServerRefusal::offline("there is no server here")), } }}const HOST: &str = "x7k2.relay.cottondb.com";const DEVICE: &str = "device-a";const SECRET: &str = "ctg_abcdefghijklmnopqrstuvwxyz0123456789ab";fn now() -> DateTime<Utc> {Utc.with_ymd_and_hms(2026, 9, 20, 12, 0, 0) .single() .unwrap_or_else(Utc::now)}fn request<'a>( fetch: &'a dynServerFetch, helper: &'a dynCredentialHelper, note: &'a Path,) -> Install<'a> {Install { fetch, helper, host: HOST, username: DEVICE, mac_name: "Studio Mac", note, now: now(), key_version: None, confirm: true, }}// ── the bytes the helper is fed ─────────────────────────────────────────────#[test]fn the_description_is_the_exact_bytes_git_documents_blank_line_and_all() {let described = credential_input(HOST, DEVICE, SECRET).expect("a describable trio"); assert_eq!( described, format!("protocol=https\nhost={HOST}\npath=git/\nusername={DEVICE}\npassword={SECRET}\n\n" ) );// The BLANK LINE is the terminator. Without it the helper waits for more// input and the write never completes, so it is asserted as such. assert!(described.ends_with("\n\n"));// A read-back query carries the description and NO value.let query = fill_input(HOST, DEVICE).expect("a describable pair"); assert!(!query.contains("password="), "{query}"); assert!(query.ends_with("\n\n")); assert_eq!(reject_input(HOST, DEVICE).expect("the same pair"), query);}#[test]fn a_value_git_would_read_as_the_end_of_the_description_is_refused_by_name() {// **THE FORMAT HAS NO ESCAPE.** git's own words are "all bytes are treated// as-is", so a `\n` in any of the three does not corrupt the description —// it EXTENDS it. `host=example.test\nusername=root` is two pairs, and a// `\n\n` terminates the conversation early with whatever follows read as// the next request.//// All three are trusted today (a relay name, a device id, a server-minted// base64url), and the module header STATED the constraint while nothing// enforced it. A refusal rather than an escape, because a newline here is// a bug upstream and rewriting it would hide the bug and still store a// credential under a host nobody asked for.for (what, host, username, secret) in [ ("host", "relay.example.test\nusername=root", DEVICE, SECRET), ("username", HOST, "dev-1\npassword=stolen", SECRET), ("credential", HOST, DEVICE, "ctg_aaa\n\nprotocol=https"), ("a NUL in the host", "relay.example.test\0", DEVICE, SECRET), ("a carriage return", HOST, "dev-1\r", SECRET), ("an empty host", "", DEVICE, SECRET), ("an empty username", HOST, "", SECRET), ] {let said = credential_input(host, username, secret) .expect_err(&format!("{what} was accepted into a git description")); assert!( said.contains("nothing was stored"),"{what}: the refusal does not say nothing was stored — {said}" );// **AND IT NEVER QUOTES THE VALUE.** The sentence travels into// `Outcome::Refused`, the boot log and the Serving page. assert!(!said.contains(SECRET), "{what}: the refusal carries the credential — {said}"); assert!(!said.contains("stolen"), "{what}: the refusal quotes the value — {said}"); }// And the describable trio still is. assert!(credential_input(HOST, DEVICE, SECRET).is_ok());}#[test]fn a_host_with_a_port_keeps_it_because_git_matches_on_the_port() {let with_port = credential_input("127.0.0.1:8749", DEVICE, SECRET).expect("describable"); assert!( with_port.contains("host=127.0.0.1:8749"),"the port was dropped: {with_port}" );}#[test]fn the_password_is_read_off_a_fill_answer_and_nothing_else_is() { assert_eq!( password_of("protocol=https\nhost=x\nusername=u\npassword=ctg_x\n").as_deref(),Some("ctg_x") );// A value that happens to hold an `=` survives, because the split is the// prefix and not the first `=`. assert_eq!( password_of("password=ctg_a=b\n").as_deref(),Some("ctg_a=b") ); assert_eq!(password_of("protocol=https\nhost=x\n"), None); assert_eq!(password_of(""), None);}// ── the pass ────────────────────────────────────────────────────────────────#[test]fn a_first_pass_mints_stores_reads_back_and_writes_the_note() {let dir = tempfile::tempdir().expect("a temp dir");let note = dir.path().join("client").join(NOTE_FILE);let server = FakeServer::minting("cred-1", SECRET);let git = FakeGit::new();let outcome = install(&request(&server, &git, ¬e), false); assert_eq!( outcome,Outcome::Installed { id: "cred-1".to_string(), installed_at: "2026-09-20T12:00:00.000Z".to_string(), note_problem: None, } );// ONE mint, at the route, naming this Mac and the `device` scope.let seen = server.seen(); assert_eq!(seen.len(), 1); assert_eq!(seen[0].0, MINT_PATH);let body: serde_json::Value = serde_json::from_str(&seen[0].1).expect("a JSON body"); assert_eq!(body.get("name").and_then(|v| v.as_str()), Some("Studio Mac")); assert_eq!(body.get("scope").and_then(|v| v.as_str()), Some("device"));// approve THEN fill — the read-back is not optional. assert_eq!(git.verbs(), vec!["approve".to_string(), "fill".to_string()]); assert_eq!( git.calls()[0].1, credential_input(HOST, DEVICE, SECRET).expect("describable") ); assert_eq!( git.calls()[1].1, fill_input(HOST, DEVICE).expect("describable") );let written = Note::read(¬e).expect("the note"); assert_eq!(written.id, "cred-1"); assert_eq!(written.host, HOST);// The note carries an id and an instant and NEVER the credential.let text = std::fs::read_to_string(¬e).expect("the note's text"); assert!(!text.contains(SECRET), "the note holds the credential: {text}");}#[test]fn a_pass_that_could_not_ask_mints_nothing_and_says_it_did_not_ask() {let dir = tempfile::tempdir().expect("a temp dir");let note = dir.path().join("client").join(NOTE_FILE);Note { id: "cred-1".to_string(), installed_at: "2026-09-19T09:00:00.000Z".to_string(), host: HOST.to_string(), username: DEVICE.to_string(), } .write(¬e) .expect("the note lands");let server = FakeServer::minting("cred-2", SECRET);let git = FakeGit::new();let outcome = install(&request(&server, &git, ¬e), false);// IT ASKED, and it did not mint. A body with no `credentials` array reads// as "could not ask", which is not a reason to mint — a Mac spends most of// its life away from its server.//// **BUT IT IS NOT `AlreadyInstalled` EITHER, which is what this answered// until 24 Sep.** The caller's flag takes only `installed` and// `alreadyInstalled` as "this Mac is done", so reporting a question that// never got through as a confirmed note stopped the pass for the rest of// the launch. When schema 29 killed every pre-upgrade `ctg_` at once, the// ask ran into its ceiling on a serving Mac and every launch afterwards// said "already installed" about a credential every checkout was being// refused for. assert_eq!( outcome,Outcome::Unconfirmed { id: "cred-1".to_string(), installed_at: "2026-09-19T09:00:00.000Z".to_string(), why: "the server's answer carried no credentials list".to_string(), } ); assert_eq!(server.mints(), 0, "it minted a second credential");// The one thing git is asked is whether it still holds the entry — the// local half of the pass, which reads nothing off a server. assert_eq!(git.verbs(), vec!["fill".to_string()], "it did more than ask git");}#[test]fn a_401_from_the_git_surface_makes_the_next_pass_mint_again() {let dir = tempfile::tempdir().expect("a temp dir");let note = dir.path().join("client").join(NOTE_FILE);Note { id: "cred-1".to_string(), installed_at: "2026-09-19T09:00:00.000Z".to_string(), host: HOST.to_string(), username: DEVICE.to_string(), } .write(¬e) .expect("the note lands");let server = FakeServer::minting("cred-2", SECRET);let git = FakeGit::new();let outcome = install(&request(&server, &git, ¬e), true); assert_eq!( outcome,Outcome::Installed { id: "cred-2".to_string(), installed_at: "2026-09-20T12:00:00.000Z".to_string(), note_problem: None, } ); assert_eq!(Note::read(¬e).expect("the note").id, "cred-2");// **AND THE ONE IT SUPERSEDED IS REVOKED.** A `device` credential has no// expiry by design, so one this Mac has stopped using and nothing revokes// authenticates the whole git surface for ever — and the panel grows a row// per re-mint that a person cannot tell from the live one. assert!( server .seen() .iter() .any(|(path, _)| path == "/v1/code/credentials/cred-1"),"the superseded credential was left live: {:?}", server.seen() );}// ── the hand-over recovery ──────────────────────────────────────────────────#[test]fn a_note_the_server_has_never_heard_of_makes_this_pass_mint_again() {// **THE HAND-OVER.** Before version 29 a `ctg_` lived in ONE Mac's// `registry.db`, so the Mac now answering the relay name had never heard of// the credential in this one's keychain. A signed one survives that, but a// revoked or re-paired credential lands here the same way, and the recovery// is the same pass. The note is a fact about this disk and stays true while// being useless, so until the pass ASKED, the recovery the module header// describes had no caller at all: every checkout on this Mac 401ed for ever// while the pass said "already installed".let dir = tempfile::tempdir().expect("a temp dir");let note = dir.path().join("client").join(NOTE_FILE);Note { id: "cred-1".to_string(), installed_at: "2026-09-19T09:00:00.000Z".to_string(), host: HOST.to_string(), username: DEVICE.to_string(), } .write(¬e) .expect("the note lands");// The new server holds one credential, and it is somebody else's.let server = FakeServer::minting("cred-9", SECRET) .holding(serde_json::json!([{ "id": "cred-other", "scope": "device" }]));let git = FakeGit::new();let outcome = install(&request(&server, &git, ¬e), false); assert_eq!( outcome,Outcome::Installed { id: "cred-9".to_string(), installed_at: "2026-09-20T12:00:00.000Z".to_string(), note_problem: None, },"{outcome:?}" ); assert_eq!(server.mints(), 1, "{:?}", server.methods()); assert_eq!(Note::read(¬e).expect("the note").id, "cred-9");// THE DEAD KEYCHAIN ENTRY WENT FIRST — `reject` before `approve`, so a// mint that could not be stored leaves git answering nothing rather than a// credential the server refuses. The one verb ahead of it is the local// check: git asked what it holds, before any server was.let verbs = git.verbs(); assert_eq!( verbs, vec!["fill".to_string(),"reject".to_string(),"approve".to_string(),"fill".to_string() ],"{verbs:?}" );}#[test]fn a_revoked_or_expired_row_is_not_a_live_credential_and_an_unreachable_server_is_not_an_answer() {let listed = |rows: serde_json::Value| serde_json::json!({ "credentials": rows });// Live: the row is there, not revoked, and either has no expiry or has one// in the future. assert_eq!( still_live(&listed(serde_json::json!([{ "id": "a" }])), "a", now()),Some(true) ); assert_eq!( still_live( &listed(serde_json::json!([{ "id": "a", "expiresAt": "2027-01-01T00:00:00.000Z" }])),"a", now() ),Some(true) );// Not live: absent, revoked, or expired.for rows in [ serde_json::json!([]), serde_json::json!([{ "id": "b" }]), serde_json::json!([{ "id": "a", "revokedAt": "2026-09-19T09:00:00.000Z" }]), serde_json::json!([{ "id": "a", "expiresAt": "2026-09-20T11:59:59.999Z" }]), ] { assert_eq!( still_live(&listed(rows.clone()), "a", now()),Some(false),"{rows} read as live" ); }// **AND "COULD NOT ASK" IS NOT "IT IS GONE".** A Mac spends most of its// life away from its server, and reading an unreadable answer as a dead// credential would mint one on every launch out of the house.for body in [ serde_json::json!({}), serde_json::json!({ "credentials": "not a list" }), serde_json::json!({ "error": "offline" }), ] { assert_eq!(still_live(&body, "a", now()), None, "{body} read as an answer"); }}#[test]fn a_credential_this_pass_minted_is_revoked_when_git_keeps_nothing() {// THE MINT COMES FIRST AND THE KEYCHAIN CAN STILL REFUSE. On a Mac with no// credential helper that happens at every launch — so without this, every// launch leaves behind one more `device` credential that never expires and// is in nobody's keychain: a live credential for the person's whole git// surface, abandoned, and a row in the panel nobody can explain.let dir = tempfile::tempdir().expect("a temp dir");let note = dir.path().join("client").join(NOTE_FILE);let server = FakeServer::minting("cred-1", SECRET);let git = FakeGit::with_no_helper();let outcome = install(&request(&server, &git, ¬e), false); assert!(matches!(outcome, Outcome::Refused(_)), "{outcome:?}"); assert!( server .seen() .iter() .any(|(path, _)| path == "/v1/code/credentials/cred-1"),"the abandoned credential was left live: {:?}", server.seen() );}#[test]fn needs_remint_is_true_with_no_note_after_a_refusal_and_on_a_different_host_or_username() { assert!(needs_remint(None, HOST, DEVICE, false));let held = Note { id: "cred-1".to_string(), installed_at: "2026-09-19T09:00:00.000Z".to_string(), host: HOST.to_string(), username: DEVICE.to_string(), }; assert!(!needs_remint(Some(&held), HOST, DEVICE, false)); assert!(needs_remint(Some(&held), HOST, DEVICE, true));// A Mac that moved between a LAN address and the relay name has a note// about a host that is not this one. assert!(needs_remint(Some(&held), "127.0.0.1:8749", DEVICE, false));// **AND A RE-PAIR CHANGES THE USERNAME, WHICH IS PART OF THE KEYCHAIN// ITEM'S KEY.** A note that matched on the host alone left the entry under// the old device id in the keychain for ever, with no expiry, while the// pass answered `alreadyInstalled`. assert!(needs_remint(Some(&held), HOST, "device-after-a-re-pair", false));// A note written before the username was recorded carries none, which is// unknown rather than a match.let older = Note { username: String::new(), ..held.clone() }; assert!(needs_remint(Some(&older), HOST, DEVICE, false));}// ── the refusals ────────────────────────────────────────────────────────────#[test]fn a_mac_with_no_credential_helper_is_told_so_and_the_note_is_not_written() {let dir = tempfile::tempdir().expect("a temp dir");let note = dir.path().join("client").join(NOTE_FILE);let server = FakeServer::minting("cred-1", SECRET);// `approve` exits 0 and keeps nothing — the measured no-op.let git = FakeGit::with_no_helper();let outcome = install(&request(&server, &git, ¬e), false);match outcome {Outcome::Refused(sentence) => { assert!( sentence.contains("no credential helper"),"the refusal did not name the cause: {sentence}" ); assert!( sentence.contains("Command Line Tools"),"the refusal did not say what to do: {sentence}" ); assert!(!sentence.contains(SECRET), "the refusal leaked it");// git's own words are carried, because a sentence that paraphrases// the tool is a sentence a person cannot search for. assert!( sentence.contains("terminal prompts disabled"),"the refusal dropped what git said: {sentence}" ); } other => panic!("a silent no-op was believed: {other:?}"), } assert!(Note::read(¬e).is_none(),"a note was written for a credential that is nowhere" );}#[test]fn a_server_that_refuses_the_mint_is_a_sentence_and_git_is_never_run() {let dir = tempfile::tempdir().expect("a temp dir");let note = dir.path().join("client").join(NOTE_FILE);let server = FakeServer::refusing(403, "this device was revoked");let git = FakeGit::new();match install(&request(&server, &git, ¬e), false) {Outcome::Refused(sentence) => { assert!(sentence.contains("403"), "{sentence}"); assert!(sentence.contains("this device was revoked"), "{sentence}"); } other => panic!("a refused mint was not a refusal: {other:?}"), } assert!( git.calls().is_empty(),"git was run with no credential to store" ); assert!(Note::read(¬e).is_none());}#[test]fn a_git_that_cannot_run_is_the_sentence_git_gave_and_nothing_is_noted() {let dir = tempfile::tempdir().expect("a temp dir");let note = dir.path().join("client").join(NOTE_FILE);let server = FakeServer::minting("cred-1", SECRET);let git = FakeGit::refusing("git credential approve refused — xcrun: error");match install(&request(&server, &git, ¬e), false) {Outcome::Refused(sentence) => assert!(sentence.contains("xcrun"), "{sentence}"), other => panic!("a broken git was not a refusal: {other:?}"), } assert!(Note::read(¬e).is_none());}// ── forgetting ──────────────────────────────────────────────────────────────#[test]fn forgetting_erases_the_keychain_entry_and_the_note_so_the_next_pass_mints() {let dir = tempfile::tempdir().expect("a temp dir");let note = dir.path().join("client").join(NOTE_FILE);let server = FakeServer::minting("cred-1", SECRET);let git = FakeGit::new(); install(&request(&server, &git, ¬e), false); assert!(Note::read(¬e).is_some()); forget(&git, HOST, DEVICE, ¬e).expect("the erase lands"); assert_eq!(git.verbs().last().map(String::as_str), Some("reject")); assert!(Note::read(¬e).is_none()); assert!(needs_remint(Note::read(¬e).as_ref(), HOST, DEVICE, false));}#[test]fn a_re_pair_erases_the_entry_under_the_old_device_id_before_installing() {// **THE KEYCHAIN ITEM'S KEY IS `(protocol, host, path, username)`.** A// re-pair gives this Mac a new device id, so the install below stores under// a new pair and the old entry is left behind — under a username no// checkout looks up, with no expiry, because a `device` credential has none// by design. Nothing ever took it out.let dir = tempfile::tempdir().expect("a temp dir");let note = dir.path().join("client").join(NOTE_FILE);Note { id: "cred-1".to_string(), installed_at: "2026-09-19T09:00:00.000Z".to_string(), host: HOST.to_string(), username: "device-before-the-re-pair".to_string(), } .write(¬e) .expect("the note lands");let server = FakeServer::minting("cred-2", SECRET);let git = FakeGit::new();let outcome = install(&request(&server, &git, ¬e), false); assert!(matches!(outcome, Outcome::Installed { .. }), "{outcome:?}");// THE ERASE RAN FIRST, and under the OLD pair — erasing under the new one// would have taken out nothing at all. assert_eq!(git.verbs().first().map(String::as_str), Some("reject"));let erased = &git.calls()[0].1; assert!( erased.contains("username=device-before-the-re-pair"),"the erase named the NEW device id, so the stale entry stayed: {erased}" );// And the note now records the pair it was really stored under, which is// what makes the next launch's question answerable.let held = Note::read(¬e).expect("the note"); assert_eq!(held.username, DEVICE); assert_eq!(held.host, HOST);}// ── where the note lives ────────────────────────────────────────────────────#[test]fn the_note_sits_beside_connection_json_because_it_is_about_this_mac() {let layout = crate::layout::Layout::new("/Users/x/CottonDB"); assert_eq!( note_path(&layout),PathBuf::from("/Users/x/CottonDB/client/git-credential.json") ); assert_eq!( note_path(&layout).parent(), layout.connection_json().parent(),"the note left the folder that holds this Mac's own facts" );}#[test]fn a_note_that_cannot_be_read_is_no_note_and_never_a_panic() {let dir = tempfile::tempdir().expect("a temp dir");let note = dir.path().join(NOTE_FILE); assert_eq!(Note::read(¬e), None); std::fs::write(¬e, b"not json at all").expect("a file"); assert_eq!(Note::read(¬e), None); assert!(needs_remint(None, HOST, DEVICE, false));}#[test]fn an_erase_names_the_pair_the_note_holds_and_never_the_one_being_asked_about() {// **THE KEY IS `(protocol, host, path, username)` AND THE USERNAME IS THIS// MAC'S DEVICE ID.** A re-pair gives this Mac a new one, and a move between// a LAN address and the relay name changes the host — so an erase composed// from what the host is answering with NOW takes out nothing at all, while// dropping the note that was the only record of where the entry really is.// That is what the panel's Remove did until this function had two callers// instead of one and a half.let note = Note { id: "cred-1".to_string(), installed_at: "2026-09-20T10:00:00.000Z".to_string(), host: "studio.relay.cottondb.com".to_string(), username: "device-old".to_string(), }; assert_eq!( erase_pair(Some(¬e), "harbour-lamp.relay.cottondb.com", "device-new"), ("studio.relay.cottondb.com", "device-old") );// A NOTE WITH NO USERNAME has no pair to name — it was written before the// field existed — so the caller's is the best available.let older = Note { username: String::new(), host: "192.168.1.20:8749".to_string(), ..note.clone() }; assert_eq!( erase_pair(Some(&older), "studio.relay.cottondb.com", "device-new"), ("studio.relay.cottondb.com", "device-new") );// And no note at all is the same answer, for the same reason. assert_eq!( erase_pair(None, "studio.relay.cottondb.com", "device-new"), ("studio.relay.cottondb.com", "device-new") );}#[test]fn the_liveness_ask_gives_up_long_before_the_transports_own_ceiling() {// **THE 37-SECOND LAUNCH.** Every launch asks the list route before it// trusts the note it already holds, and on a serving Mac that request goes// out over the relay and back down its own tunnel — so one arriving before// the line is active is HELD while the relay's hand-over window runs. The// transport's sixty-second ceiling is a backstop against a socket that// never settles, not a budget for a probe every checkout on the machine// waits behind.//// It is safe to be short because `still_live` already treats "could not// ask" as a state: the pass changes nothing and the next launch asks again.let dir = tempfile::tempdir().expect("a temp dir");let note = dir.path().join("client").join(NOTE_FILE);Note { id: "cred-1".to_string(), installed_at: "2026-09-19T09:00:00.000Z".to_string(), host: HOST.to_string(), username: DEVICE.to_string(), } .write(¬e) .expect("the note lands");let server = FakeServer::minting("cred-2", SECRET).holding(serde_json::json!([ { "id": "cred-1", "revokedAt": null, "expiresAt": null } ]));let git = FakeGit::holding(HOST, DEVICE, SECRET);let outcome = install(&request(&server, &git, ¬e), false); assert!( matches!(outcome, Outcome::AlreadyInstalled { .. }),"{outcome:?}" ); assert_eq!( server.ceilings(), vec![Some(super::LIVENESS_CEILING_MS)],"the liveness ask is the one call this pass makes, and it names its own ceiling", );// AND IT IS SHORTER THAN THE BACKSTOP. A caller may give up sooner than the// transport's ceiling and never later — `SignedHttp::ceiling_for` takes the// smaller of the two, so this is the number that applies. assert_eq!(super::LIVENESS_CEILING_MS .min(crate::transport::REQUEST_CEILING_MS),super::LIVENESS_CEILING_MS, );}#[test]fn a_server_that_did_not_answer_is_told_apart_from_one_that_confirmed_the_note() {// The three answers, side by side, because two of them used to be one.let dir = tempfile::tempdir().expect("a temp dir");let held = || Note { id: "cred-1".to_string(), installed_at: "2026-09-19T09:00:00.000Z".to_string(), host: HOST.to_string(), username: DEVICE.to_string(), };// CONFIRMED — the list came back and carries this id, live.let note = dir.path().join("confirmed").join(NOTE_FILE); held().write(¬e).expect("the note lands");let server = FakeServer::minting("cred-2", SECRET).holding(serde_json::json!([ { "id": "cred-1", "revokedAt": null, "expiresAt": null } ]));let git = FakeGit::holding(HOST, DEVICE, SECRET); assert!( matches!( install(&request(&server, &git, ¬e), false),Outcome::AlreadyInstalled { .. } ),"a note the server vouched for and git still holds is the common answer and mints nothing", ); assert_eq!(server.mints(), 0); assert_eq!( git.verbs(), vec!["fill".to_string()],"the one thing git is asked is whether it still holds the entry" );// GONE — the list came back and does NOT carry it. This is the only shape// that mints, and it is the recovery the hand-over needs.let note = dir.path().join("gone").join(NOTE_FILE); held().write(¬e).expect("the note lands");let server = FakeServer::minting("cred-2", SECRET) .holding(serde_json::json!([{ "id": "someone-else", "revokedAt": null }]));let git = FakeGit::new(); assert!( matches!( install(&request(&server, &git, ¬e), false),Outcome::Installed { .. } ),"a credential the server no longer holds is the one case that mints again", ); assert_eq!(server.mints(), 1);// UNCONFIRMED — nothing came back. Mints nothing, and says so, so the// caller asks again instead of recording this launch as done.let note = dir.path().join("unconfirmed").join(NOTE_FILE); held().write(¬e).expect("the note lands");let server = FakeServer::minting("cred-2", SECRET);let git = FakeGit::new(); assert!( matches!( install(&request(&server, &git, ¬e), false),Outcome::Unconfirmed { .. } ),"silence is not a yes", ); assert_eq!(server.mints(), 0);}#[test]fn a_note_the_server_confirms_but_git_no_longer_holds_is_minted_again() {// 28 Sep 2026, 01:22 IST, a Mac: git `reject`ed the credential after a// 401 the relay answered while the serving Mac was overloaded, and// `osxkeychain` deleted the item. The note stayed and the server still// listed the id, so every launch said "already installed" about an entry// that was gone — and every checkout on the Mac failed with "could not// read Username" until the app was relaunched with the note removed.let dir = tempfile::tempdir().expect("a temp dir");let note = dir.path().join("client").join(NOTE_FILE);Note { id: "cred-1".to_string(), installed_at: "2026-09-19T09:00:00.000Z".to_string(), host: HOST.to_string(), username: DEVICE.to_string(), } .write(¬e) .expect("the note lands");let server = FakeServer::minting("cred-2", SECRET).holding(serde_json::json!([ { "id": "cred-1", "revokedAt": null, "expiresAt": null } ]));let git = FakeGit::new();let outcome = install(&request(&server, &git, ¬e), false); assert!( matches!(outcome, Outcome::Installed { .. }),"an entry git no longer holds is minted again: {outcome:?}" ); assert_eq!(server.mints(), 1);// Asked first, then the dead pair rejected, then the new one stored and// read back — the same pass a server that dropped the id runs. assert_eq!( git.verbs(), vec!["fill".to_string(),"reject".to_string(),"approve".to_string(),"fill".to_string() ] );let written = Note::read(¬e).expect("a new note"); assert_eq!(written.id, "cred-2");// The one that Mac had been failing on is revoked rather than left live. assert!( server .seen() .iter() .any(|(path, _)| path == "/v1/code/credentials/cred-1"),"the superseded credential was left live: {:?}", server.seen() );}// ── a rotation, and the local check ─────────────────────────────────────────//// 28 Sep 2026, 17:13Z: a stale Mac held the relay name for sixty seconds and// rotated the workspace key from v3 to v4. Every `ctg_` in the household was// signed under v3; the rows stayed live, git still held each one and every note// matched — so no Mac minted again until it was relaunched and somebody removed// the note by hand./// A real `ctg_`, signed under `version`, as the server mints them.fn signed_at(version: u32) -> String { cotton_core::vault::code_tokens::mint( &[5u8; 32], &cotton_core::vault::code_tokens::CodeClaims { vmk_version: version, issued_at_ms: 1_758_000_000_000, expires_at_ms: 0, scope: cotton_core::vault::code_tokens::Scope::Device, workspace_id: "workspace-a".to_string(), credential_id: "cred-1".to_string(), device_id: DEVICE.to_string(), repo_id: None, }, ) .expect("a claim the scheme can carry")}fn noted(dir: &Path, name: &str) -> PathBuf {let note = dir.join(name).join(NOTE_FILE);Note { id: "cred-1".to_string(), installed_at: "2026-09-19T09:00:00.000Z".to_string(), host: HOST.to_string(), username: DEVICE.to_string(), } .write(¬e) .expect("the note lands"); note}/// A server that still lists `cred-1` live — the row a rotation leaves alone.fn still_listing(mint_id: &str, mint_secret: &str) -> FakeServer {FakeServer::minting(mint_id, mint_secret).holding(serde_json::json!([ { "id": "cred-1", "revokedAt": null, "expiresAt": null } ]))}/// RULE: A Mac whose git credential is signed under a key version its file has rotated past mints a new one by itself, without a relaunch.#[test]fn a_credential_signed_under_a_key_the_file_has_moved_past_is_minted_again_without_a_relaunch() {let dir = tempfile::tempdir().expect("a temp dir");let note = noted(dir.path(), "client");let old = signed_at(3);let fresh = signed_at(4);let server = still_listing("cred-2", &fresh);let git = FakeGit::holding(HOST, DEVICE, &old);let outcome = install( &Install { key_version: Some(4), ..request(&server, &git, ¬e) },false, ); assert!( matches!(outcome, Outcome::Installed { ref id, .. } if id == "cred-2"),"a credential behind the key was left in place: {outcome:?}" ); assert_eq!(server.mints(), 1);// NO LIVENESS ASK: the row is live, and that is exactly what a rotation// leaves true. The version answered the question on this disk. assert!( !server.methods().iter().any(|method| method == "GET"),"it asked the server about a row a rotation does not touch: {:?}", server.methods() ); assert_eq!( git.verbs(), vec!["fill".to_string(),"reject".to_string(),"approve".to_string(),"fill".to_string() ] ); assert_eq!(Note::read(¬e).expect("a new note").id, "cred-2"); assert!( server .seen() .iter() .any(|(path, _)| path == "/v1/code/credentials/cred-1"),"the credential it replaced was left live: {:?}", server.seen() );}#[test]fn behind_the_key_the_old_entry_stays_until_a_replacement_has_been_minted() {// "Behind" is judged against THIS Mac's copy of the file, which can be the// stale one. So a mint that fails leaves git holding what it held.let dir = tempfile::tempdir().expect("a temp dir");let note = noted(dir.path(), "client");let old = signed_at(3);let server = FakeServer::refusing(503, "this Mac is not the one that should answer");let git = FakeGit::holding(HOST, DEVICE, &old);let outcome = install( &Install { key_version: Some(4), ..request(&server, &git, ¬e) },false, ); assert!(matches!(outcome, Outcome::Refused(_)), "{outcome:?}"); assert_eq!( git.verbs(), vec!["fill".to_string()],"the keychain entry was touched before a replacement existed" ); assert_eq!( password_of(&git.run("fill", &fill_input(HOST, DEVICE).expect("a pair")).expect("held")) .as_deref(),Some(old.as_str()) ); assert!(Note::read(¬e).is_some(), "the note went with nothing to replace it");}#[test]fn a_credential_at_the_files_key_version_or_ahead_of_it_is_left_alone() {let dir = tempfile::tempdir().expect("a temp dir");for (name, key_version) in [("same", Some(3)), ("ahead", Some(2)), ("unknown", None)] {let note = noted(dir.path(), name);let server = still_listing("cred-2", SECRET);let git = FakeGit::holding(HOST, DEVICE, &signed_at(3));let outcome = install( &Install { key_version, ..request(&server, &git, ¬e) },false, ); assert!( matches!(outcome, Outcome::AlreadyInstalled { .. }),"{name}: {outcome:?}" ); assert_eq!(server.mints(), 0, "{name}: it minted over a current credential"); }}#[test]fn the_local_check_answers_from_this_disk_and_dials_nothing() {let dir = tempfile::tempdir().expect("a temp dir");let note = noted(dir.path(), "client");let server = still_listing("cred-2", SECRET);let git = FakeGit::holding(HOST, DEVICE, &signed_at(3));let outcome = install( &Install { key_version: Some(3), confirm: false, ..request(&server, &git, ¬e) },false, ); assert!(matches!(outcome, Outcome::AlreadyInstalled { .. }), "{outcome:?}"); assert!(server.seen().is_empty(), "a local check dialled: {:?}", server.seen()); assert_eq!(git.verbs(), vec!["fill".to_string()]);}#[test]fn the_local_check_that_finds_something_wrong_runs_the_whole_pass() {let dir = tempfile::tempdir().expect("a temp dir");// GIT HOLDS NOTHING — erased after a 401. The whole pass: the server still// lists the id, git holds nothing, so it mints.let note = noted(dir.path(), "erased");let server = still_listing("cred-2", SECRET);let git = FakeGit::new();let outcome = install( &Install { key_version: Some(3), confirm: false, ..request(&server, &git, ¬e) },false, ); assert!(matches!(outcome, Outcome::Installed { .. }), "erased: {outcome:?}"); assert_eq!(server.mints(), 1);// BEHIND THE KEY — a rotation landed in this Mac's file.let note = noted(dir.path(), "rotated");let fresh = signed_at(4);let server = still_listing("cred-2", &fresh);let git = FakeGit::holding(HOST, DEVICE, &signed_at(3));let outcome = install( &Install { key_version: Some(4), confirm: false, ..request(&server, &git, ¬e) },false, ); assert!(matches!(outcome, Outcome::Installed { .. }), "rotated: {outcome:?}"); assert_eq!(server.mints(), 1);}#[test]fn behind_the_key_is_a_comparison_of_two_known_versions_and_nothing_else() { assert!(behind_the_key(&signed_at(3), Some(4))); assert!(!behind_the_key(&signed_at(4), Some(4)));// AHEAD is this Mac's file not having folded a rotation, never stale. assert!(!behind_the_key(&signed_at(5), Some(4)));// Unknown is not stale: no file version, or a password that is not a// `ctg_` the scheme can read. assert!(!behind_the_key(&signed_at(3), None)); assert!(!behind_the_key(SECRET, Some(4))); assert!(!behind_the_key("a password somebody typed", Some(4)));}#[test]fn a_replacement_no_newer_than_what_git_holds_is_revoked_and_never_minted_every_minute() {// This Mac's file names v4, but the server answering the name signs under// v3 — this Mac's copy is the odd one out, or the server is stale. Storing// its answer would read as "behind" on the next tick and mint again every// minute; so the pass keeps what git holds and answers a refusal, which the// enrolment backs off on.let dir = tempfile::tempdir().expect("a temp dir");let note = noted(dir.path(), "client");let old = signed_at(3);let server = still_listing("cred-2", &signed_at(3));let git = FakeGit::holding(HOST, DEVICE, &old);let outcome = install( &Install { key_version: Some(4), ..request(&server, &git, ¬e) },false, ); assert!(matches!(outcome, Outcome::Refused(_)), "{outcome:?}"); assert_eq!(git.verbs(), vec!["fill".to_string()], "the keychain was touched"); assert_eq!(Note::read(¬e).expect("the note").id, "cred-1"); assert!( server .seen() .iter() .any(|(path, _)| path == "/v1/code/credentials/cred-2"),"the replacement it would not store was left live: {:?}", server.seen() );}