//! This Mac installs its own code credential, once.//!//! ## What it does, and why it has to happen at all//!//! Every repository Cotton serves is private, so `GET /git/…/info/refs` answers//! `401` with `WWW-Authenticate: Basic` before a byte of a pack is read. A//! developer's Mac therefore needs one credential in its login keychain, and//! then every checkout on that machine — a Claude Code session, `pnpm//! worktree:new`, a runner's `actions/checkout` — clones and pushes with no//! prompt. On a Mac nobody is sitting at, a prompt is a hang.//!//! So: mint a `device`-scoped `ctg_` over the owner route this Mac already//! signs, hand it to `git credential approve` on stdin, and write a note beside//! `connection.json` saying it was done. Nothing is stored in a row: **which//! credential this Mac's keychain holds is a fact about this Mac's disk**, the//! same reason `applied.json` sits beside a bare clone and `media-budget.json`//! beside the replica.//!//! ## Three traps, each measured//!//! 1. **`approve` with no helper is a silent no-op.** `git -c credential.helper=//! credential approve` exits **0**, prints nothing and stores nothing. So the//! install is not believed on an exit code — it is verified with a `fill`//! read-back ([`Outcome::Refused`] when the value does not come back). On any//! Mac with Xcode or the Command Line Tools, `osxkeychain` is already the//! default helper from the SYSTEM gitconfig, so the happy path needs no//! configuration at all.//! 2. **The secret travels on STDIN, never on a command line and never in a//! log.** A credential in `argv` is visible to every process on the machine//! via `ps`, and this crate's own rule is that a token travels through stdin//! or `GIT_CONFIG_*`. [`Outcome`] carries an id and an instant and never a//! value, and its `Debug` has nothing to redact because it holds nothing.//! 3. **`host` must carry the port when there is one.** Measured: with a//! non-default port, `git credential` matches on `host=127.0.0.1:8749` and//! not on `127.0.0.1`. The relay name is reached on 443 so the common case//! has no port, but a LAN address does — which is why the host is a//! parameter and not composed here.//!//! ## And when the server stops accepting it//!//! A `ctg_` is SIGNED off the workspace key since version 29, so a hand-over no//! longer kills one (Cotton note "Code hosting — why a repository lives in Cotton" § Hand-over). A//! credential can still stop being live — revoked from the panel, expired, or//! belonging to a device that was removed — and the note beside//! `connection.json` is a fact about THIS disk that stays true while being//! useless. **THE RECOVERY IS THE PASS ASKING** ([`still_live`]): before it//! trusts the note, it reads `GET /v1/code/credentials` and looks for the//! note's id, live, giving up after [`LIVENESS_CEILING_MS`]. An answer without//! the id `reject`s the dead keychain entry and mints again — which is why the//! mint route has to be reachable from every paired Mac.//!//! **AND A ROTATION KILLS ONE WHOSE ROW STAYS LIVE.** Revoking a device — or a//! stale Mac holding the name for a minute, as on 28 Sep 2026 at 17:13Z —//! rotates the workspace key, and every `ctg_` signed under the old version//! stops verifying while its row, the note and git's entry all stay exactly as//! they were. So the pass reads the version out of the credential git holds and//! compares it with the one this Mac's file names ([`behind_the_key`]); behind//! is a re-mint, on this disk, with no server asked first.//!//! **IT IS NOT A LAUNCH-TIME PASS ANY MORE.** The app runs it on a timer//! (`CodeCredentialEnrolment`): a LOCAL check every minute ([`Install::confirm`]//! `false` — git still holds a password, and it is not behind the key) and the//! whole pass, server included, every few minutes. A refusal backs off; it//! never loops.//!//! It is the pass's own question rather than a flag a caller passes, and that is//! deliberate: `refused: true` exists for a caller that has SEEN a `401`, and//! nothing in the app probes the git surface, so a recovery that waited for one//! would have no caller at all — which is exactly what it had before this. A//! server that cannot be reached answers `None` and changes nothing: a Mac//! spends most of its life away from home, and minting on every launch out of//! the house would be the cure being the disease.//!//! **AND THE PANEL CAN DO IT NOW.** Remove on this Mac's own row under//! *Settings › Code hosting* revokes the row and then calls//! `code.forgetCredential`, which is [`forget`] — so the entry leaves the//! keychain and the note goes with it immediately, rather than waiting for the//! next launch's liveness ask. That method is this function's one production//! caller; before it, `forget` had none.//!//! ## The description is a format with no escape//!//! `host`, `username` and the secret go into `key=value` lines that git reads//! "as-is" — no quoting, no escaping — so a `\n` in any of them does not//! corrupt the description, it EXTENDS it with pairs nobody asked for, or//! terminates the conversation early. All three are trusted (a relay name, a//! device id, a server-minted base64url), which is why [`describable`]//! REFUSES rather than escapes: a newline here is a bug upstream, and//! rewriting it would hide the bug and still store a credential under a host//! nobody named.use std::fmt;use std::io::Write;use std::path::{Path, PathBuf};use std::process::{Command, Stdio};use chrono::{DateTime, Utc};use serde::{Deserialize, Serialize};use serde_json::{json, Value};usecrate::transport::{ClientRequest, ServerFetch};/// The credential-helper attribute that scopes this credential to the git/// surface.////// A trailing slash because git compares a stored `path` as a PREFIX. It is/// advisory: `credential.useHttpPath` defaults to **false**, so one credential/// covers the whole host unless somebody turns that on — in which case this is/// the path it matches.pubconst CREDENTIAL_PATH: &str = "git/";/// The scope this Mac mints for itself.pubconst DEVICE_SCOPE: &str = "device";/// The route the mint goes to.pubconst MINT_PATH: &str = "/v1/code/credentials";/// The note this Mac keeps, beside `connection.json`.pubconst NOTE_FILE: &str = "git-credential.json";/// What one pass did.////// It carries an id and an instant and never a value — there is nothing here to/// redact because there is nothing here to leak.#[derive(Debug, Clone, PartialEq, Eq)]pubenumOutcome {/// The note says this Mac already installed one and nothing has refused it./// The common answer, every launch after the first.AlreadyInstalled { id: String, installed_at: String },/// Minted and stored, and read back.////// `note_problem` is the one thing that can go wrong AFTER the credential/// is safely in the keychain: the note beside `connection.json` did not/// write. It is carried rather than swallowed — a silent fallback is what/// this repo's rule forbids — and rather than failing the pass, because/// the credential IS installed and the only cost of a lost note is one/// redundant mint on the next launch. The caller prints it; nothing/// retries on it.Installed { id: String, installed_at: String, note_problem: Option<String>, },/// There is a note, and the server could not be asked whether it is still/// true — so **this pass decided nothing and must run again**.////// **IT IS NOT [`Outcome::AlreadyInstalled`], and that distinction is the/// whole of this variant.** The two used to be one answer: a liveness ask/// that timed out was reported as a confirmed note, the caller's/// "installed" flag was set, and this Mac never asked again until it was/// relaunched. When schema 29 made every pre-upgrade `ctg_` dead at once,/// that is exactly what happened — the ask ran into the ceiling on a/// serving Mac, every pass answered "already installed", and every/// checkout `401`ed until somebody deleted the note by hand.////// A Mac away from home still mints nothing: this says "unknown", never/// "gone". What it changes is only that unknown stops being recorded as/// yes.Unconfirmed { id: String, installed_at: String,/// Why the server could not answer, verbatim, so the log names it. why: String, },/// No `git` on this Mac. A STATE: nothing is cloned, and the Serving page/// says [`super::discover::GIT_MISSING`].NoGit,/// A sentence a person can act on — the server refused the mint, or the/// helper did not keep what it was handed.Refused(String),}/// The note on disk. Per-Mac, never a row.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pubstructNote {/// The credential's id — not its value. Enough to name the row on the/// Settings panel and to ask the server to revoke it.pub id: String,pub installed_at: String,/// The host it was stored under, so a Mac that moved between a LAN address/// and the relay name re-installs rather than trusting a note about a/// different host.pub host: String,/// The USERNAME it was stored under — this Mac's device id.////// **THE KEYCHAIN ITEM'S KEY IS `(protocol, host, path, username)`, AND/// THE USERNAME IS PART OF IT.** Without this the note matched after a/// re-pair — which gives this Mac a NEW device id — so the pass answered/// `alreadyInstalled` while git held an entry under the old id that no/// checkout looks up any more. That entry stayed in the login keychain for/// ever, and a `device` credential has no expiry by design.////// `#[serde(default)]` because a note written before this field existed/// carries none, and an empty username is "unknown": the pass re-mints/// rather than trusting it, and erases under the request's own pair/// because there is no other pair to name. #[serde(default)]pub username: String,}implNote {pubfn read(path: &Path) -> Option<Note> {let bytes = std::fs::read(path).ok()?; serde_json::from_slice(&bytes).ok() }/// Write it, creating the directory if the client folder is not there yet.////// A failure to write is NOT a failure of the install: the credential is in/// the keychain either way, and the only cost of a lost note is one/// redundant mint on the next launch. So this answers a sentence the caller/// logs rather than one that fails the pass.pubfn write(&self, path: &Path) -> Result<(), String> {ifletSome(parent) = path.parent() { std::fs::create_dir_all(parent) .map_err(|error| format!("could not make {}: {error}", parent.display()))?; }let bytes = serde_json::to_vec_pretty(self) .map_err(|error| format!("the note could not be written: {error}"))?; std::fs::write(path, bytes) .map_err(|error| format!("could not write {}: {error}", path.display())) }}/// The note's path, beside `connection.json`.pubfn note_path(layout: &crate::layout::Layout) -> PathBuf { layout.client_dir().join(NOTE_FILE)}/// Is this value one a `git credential` description may carry?////// **THE FORMAT HAS NO ESCAPE AND NO QUOTING** — git's own words are "all/// bytes are treated as-is" — so a value is a line and the only characters/// that cannot be in one are the ones that END a line or a string: `\n`, `\r`/// and `\0`. A newline in `host`, `username` or `secret` would not corrupt the/// description, it would EXTEND it: everything after it reads as another/// `key=value` pair, or as the blank line that terminates the whole/// conversation.////// **REFUSED, NEVER ESCAPED**, because all three are trusted inputs — a relay/// name (`[a-z0-9-]+` plus an optional port), a device id, a server-minted/// base64url — so a newline in one is not a person's data that must survive, it/// is a bug somewhere upstream, and quietly rewriting it would hide that bug/// while still storing a credential under a host nobody asked for. An empty/// value is refused for the same reason: `host=` matches nothing and/// `username=` is a keychain item nobody can look up.////// The constraint used to be STATED in this module's header and enforced/// nowhere.pubfn describable(field: &str, value: &str) -> Result<(), String> {if value.is_empty() {returnErr(format!("Cotton cannot write a git credential with no {field}, so nothing was stored." )); }ifletSome(at) = value.find(['\n', '\r', '\0']) {let named = match value.as_bytes()[at] { b'\n' => "a line break", b'\r' => "a carriage return", _ => "a NUL", };returnErr(format!("The {field} Cotton was given holds {named}, which `git credential` reads as the end \ of the description — so nothing was stored. This is a fault in whatever composed it, \ not something to retype." )); }Ok(())}/// The exact bytes `git credential approve` is fed.////// Pure, and asserted byte for byte by a test, because every rule here is one/// git states and none of them is guessable:////// * `key=value` lines, **terminated by a blank line** — without it the helper/// waits for more input and the write never completes./// * values may hold any byte but a newline or a NUL, and nothing is quoted or/// escaped ("all bytes are treated as-is"), so a `ctg_` — base64url, no/// newline — needs no encoding. [`describable`] is what makes that true/// rather than hoped./// * `host` includes the port when there is one; the caller composes that.pubfn credential_input( host: &str, username: &str, secret: &str,) -> Result<String, String> { describable("host", host)?; describable("username", username)?;// NOT "secret" AND NOT ITS VALUE. The sentence travels — into// `Outcome::Refused`, the boot log and the Serving page — and a refusal// that quoted the credential to say it was malformed would be the leak// this module exists to avoid. describable("credential", secret)?;Ok(format!("protocol=https\nhost={host}\npath={CREDENTIAL_PATH}\nusername={username}\npassword={secret}\n\n" ))}/// The bytes a read-back query is fed — the same description with no value.pubfn fill_input(host: &str, username: &str) -> Result<String, String> { describable("host", host)?; describable("username", username)?;Ok(format!("protocol=https\nhost={host}\npath={CREDENTIAL_PATH}\nusername={username}\n\n" ))}/// The bytes an erase is fed.pubfn reject_input(host: &str, username: &str) -> Result<String, String> { fill_input(host, username)}/// One run of `git credential <verb>` — the seam every side effect is behind.////// A trait rather than a function so a test drives a FAKE git: it records what/// was written to stdin and answers whatever the case needs, and no case in/// this file touches the real login keychain. `tests/` and the runbook's/// rehearsal exercise the real one, exactly as litestream is.pubtraitCredentialHelper: Send + Sync + fmt::Debug {/// Feed `input` to `git credential <verb>` on stdin and answer its stdout.////// `Err` is a sentence: git was not runnable, or it exited non-zero.fn run(&self, verb: &str, input: &str) -> Result<String, String>;}/// The real one — the discovered git, and nothing on the command line.////// `env_clear()` and then the handful of variables git needs, for/// `backup/process.rs`'s reason: nothing leaks in, and nothing a login shell/// happened to export decides where a credential goes. `HOME` is kept because/// git reads the person's own `~/.gitconfig` through it and the whole point is/// to write into the helper THEY use.#[derive(Debug, Clone)]pubstructSpawnedCredentialHelper {/// An absolute path from [`super::discover`]. Never a bare name: the/// program lookup a `Command` does is the parent's PATH, not the one this/// process meant.pub git: PathBuf,pub home: PathBuf,}implCredentialHelperforSpawnedCredentialHelper {fn run(&self, verb: &str, input: &str) -> Result<String, String> {if !cfg!(target_os = "macos") {returnErr("Automatic git credential installation is not available on Linux: it uses the macOS login Keychain. Configure a git credential helper explicitly.".to_string()); }letmut child = Command::new(&self.git) .arg("credential") .arg(verb) .env_clear() .env("HOME", &self.home)// The four paths the ladder knows, so `git` can exec its own// `git-credential-osxkeychain` sub-program. Not the login PATH: a// credential write must not depend on a person's shell profile. .env("PATH", "/usr/bin:/bin:/usr/sbin:/sbin")// Suppresses the install-the-tools prompt on both the success and// the failure path, on a Mac whose selection is stale. .env("DEVELOPER_DIR", "/Library/Developer/CommandLineTools") .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::piped()) .spawn() .map_err(|error| format!("{} could not be run — {error}", self.git.display()))?; {let stdin = child .stdin .as_mut() .ok_or_else(|| "git credential took no stdin".to_string())?; stdin .write_all(input.as_bytes()) .map_err(|error| format!("the description could not be written — {error}"))?; }let output = child .wait_with_output() .map_err(|error| format!("git credential did not finish — {error}"))?;if !output.status.success() {// The STDERR, capped, because git's own sentence is more use than a// paraphrase. Capped because a `fill` with no TTY prints a long one.//// **AND SCRUBBED.** A `ctg_` was on this child's stdin moments ago// and this sentence travels — into `Outcome::Refused`, the Mac's// boot log and the Serving page. A helper that echoed what it was// handed, or a future git that quoted the description back in an// error, would put the credential in all three. The rule is the// `cfi_` lesson: scrub at the seam, not where you hope it cannot// happen.let said: String = cotton_core::transforms::redact::redact_secrets(&String::from_utf8_lossy( &output.stderr, )) .chars() .take(200) .collect();returnErr(format!("git credential {verb} refused — {}", said.trim())); }Ok(String::from_utf8_lossy(&output.stdout).to_string()) }}/// The `password` out of a `git credential fill` answer, if it carried one.////// Line-based because that is what git writes; `key=value`, one per line, and/// the value is whatever follows the first `=`.pubfn password_of(answer: &str) -> Option<String> { answer .lines() .find_map(|line| line.strip_prefix("password=")) .map(str::to_string)}/// Mint one `device` credential over the owner route.////// The name is this Mac's own name, because the panel's whole job is letting a/// person tell two Macs apart when they come to remove one.pubfn mint_over( fetch: &dynServerFetch, name: &str,) -> Result<(String, String), String> {let body = serde_json::to_vec(&json!({ "name": name, "scope": DEVICE_SCOPE })) .map_err(|error| format!("the mint body could not be written — {error}"))?;let answer = fetch .call(ClientRequest::post_json(MINT_PATH, body)) .map_err(|refusal| refusal.message)?;if answer.status != 201 && answer.status != 200 {// The status AND the server's own sentence when it sent one: a 401 here// is a Mac that is not admitted, which is a different thing to fix// from a 400 about the body.let said: Value = serde_json::from_slice(&answer.body).unwrap_or(Value::Null);let sentence = said .get("error") .and_then(Value::as_str) .unwrap_or("the server did not say why");returnErr(format!("this Mac's code credential was not minted ({}) — {sentence}", answer.status )); }let minted: Value = serde_json::from_slice(&answer.body) .map_err(|error| format!("the mint answer could not be read — {error}"))?;let id = minted .get("id") .and_then(Value::as_str) .ok_or_else(|| "the mint answer carried no id".to_string())? .to_string();let secret = minted .get("secret") .and_then(Value::as_str) .ok_or_else(|| "the mint answer carried no credential".to_string())? .to_string();Ok((id, secret))}/// Revoke one credential this Mac is done with, by id.////// **BEST EFFORT, AND IT SAYS SO.** Every caller here is already on its way to/// an answer — a refusal to report, or a credential that installed — and a/// server that cannot be reached for the revoke must not turn either of those/// into something else. What it returns is a sentence for a LOG, never one a/// person is asked to act on, because there is nothing for them to do about it/// and the tail sweep will not collect a row nobody revoked.fn revoke_over(fetch: &dynServerFetch, id: &str) -> Result<(), String> {let answer = fetch .call(ClientRequest::delete(format!("{MINT_PATH}/{id}"))) .map_err(|refusal| refusal.message)?;if answer.status == 200 || answer.status == 204 || answer.status == 404 {// A 404 is a credential that is already gone, which is the outcome// asked for.returnOk(()); }Err(format!("the server would not revoke {id} ({})", answer.status ))}/// Revoke a credential this pass is finished with, and carry on either way.////// The one caller shape: a pass that is already returning something, whose/// answer must not change because a revoke could not be sent. A failure is a/// log line — the tail sweep does not collect a row nobody revoked, so the/// line is how anybody ever learns it is still there./// `eprintln!` and not a logger because this crate has none — it answers/// STATES, and the Mac's own boot log is stderr plus `os_log` (`BootLog.say`),/// so a line written here is a line a person can find in Console. It carries no/// secret: `revoke_over` names an id and a status and nothing else.fn abandon(fetch: &dynServerFetch, id: &str) {ifletErr(said) = revoke_over(fetch, id) { eprintln!("cotton-client: this Mac's superseded code credential is still live — {said}"); }}/// How long the liveness ask may take before this pass gives up on it.////// **FIVE SECONDS, AND THE 37-SECOND LAUNCH IS WHY.** The transport's own/// ceiling is sixty seconds (`transport::REQUEST_CEILING_MS`) — a backstop/// against a socket that never settles, not a budget. This request goes out/// over the relay name even on the Mac that is serving it (`connection`'s/// address ladder), so a launch that arrives before that Mac's tunnel line is/// active is HELD by the relay while its hand-over window runs — up to fifty/// seconds, of which 37 was measured on a freshly started server. The pass is/// blocking, and every checkout on the machine waits behind it.////// It is safe to be short because [`still_live`] already documents `None` as a/// state rather than an error: a server that could not be asked changes/// nothing, and the next launch asks again.pubconst LIVENESS_CEILING_MS: u64 = 5_000;/// Every credential this workspace holds, as the list route answers it.fn list_over(fetch: &dynServerFetch) -> Result<Value, String> {let answer = fetch .call(ClientRequest::get(MINT_PATH).within_ms(LIVENESS_CEILING_MS)) .map_err(|refusal| refusal.message)?; serde_json::from_slice(&answer.body) .map_err(|error| format!("the credentials list could not be read — {error}"))}/// Does the server still hold this credential, live?////// **`None` IS "COULD NOT ASK", AND IT IS NOT A REASON TO MINT.** A Mac spends/// most of its life out of reach of its server, and a pass that read an/// unreachable server as "my credential is gone" would mint one on every launch/// away from home. So only a list that came back AND does not carry this id/// live is `Some(false)`.////// `now` is compared as a fixed-width ISO string in UTC, which IS the instant/// compare — the same reading `code::credentials::authenticate` does.pubfn still_live(listed: &Value, id: &str, now: DateTime<Utc>) -> Option<bool> {let rows = listed.get("credentials")?.as_array()?;let stamp = now.format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string();Some(rows.iter().any(|row| { row.get("id").and_then(Value::as_str) == Some(id) && row.get("revokedAt").and_then(Value::as_str).is_none() && row .get("expiresAt") .and_then(Value::as_str) .is_none_or(|expires| expires > stamp.as_str()) }))}/// Everything one pass needs, so the pass itself is one readable function.pubstructInstall<'a> {/// This Mac's signed transport to whichever server holds the data.pub fetch: &'a dynServerFetch,/// `git credential`, behind its seam.pub helper: &'a dynCredentialHelper,/// `<name>.relay.cottondb.com`, WITH the port when there is one.pub host: &'a str,/// The Basic username. This Mac's device id — a legible label, never a/// second factor (the server ignores it; `code::credentials::parse_basic`/// says why).pub username: &'a str,/// This Mac's own name, which becomes the credential's name.pub mac_name: &'a str,/// Where the note goes.pub note: &'a Path,pub now: DateTime<Utc>,/// The workspace key version THIS MAC's copy of the file names as current/// (`cotton_vault_state.vmk_version`), or `None` when it could not be read.////// A `ctg_` carries the version it was signed under in its body, readable/// without the key ([`behind_the_key`]), so a credential git holds that is/// signed under an older version is one a rotation retired — whatever the/// note and the server's list say about its row.pub key_version: Option<u32>,/// Ask the server whether the noted credential is still live.////// `false` is the LOCAL CHECK the enrolment runs every minute: when git/// still holds a password for this pair and it is not behind the key, the/// pass answers from this disk and dials nothing. Anything else — no note,/// nothing in git, a credential behind the key — falls through to the whole/// pass exactly as `true` runs it.pub confirm: bool,}/// Is `held` — the password git answers — a `ctg_` signed under a workspace key/// version BEHIND the one this Mac's file names?////// **WHY THIS EXISTS.** 28 Sep 2026, 17:13Z: a stale Mac held the relay name for/// a minute and rotated the key from v3 to v4, and every `ctg_` in the/// household was signed under v3. The row behind each stayed live, git still/// held each one, and the note matched — so a Mac never minted again until it/// was relaunched and somebody removed the note. The version is in the token's/// own body ([`cotton_core::vault::code_tokens::selector`]), so this is a/// comparison on this disk, with no key and no server.////// `false` whenever either side is unknown: a password that is not a `ctg_`,/// or a file whose key version could not be read. Unknown is not stale. And a/// credential AHEAD of the file is not stale either — that is this Mac's file/// not having folded a rotation yet.#[must_use]pubfn behind_the_key(held: &str, key_version: Option<u32>) -> bool {let (Some(current), Some(selector)) = ( key_version, cotton_core::vault::code_tokens::selector(held), ) else {returnfalse; }; selector.vmk_version < current}/// Does this Mac need to mint again?////// `true` when there is no note, when the note is about a DIFFERENT HOST OR A/// DIFFERENT USERNAME, or when the caller saw a `401` from the git surface and/// asked for a re-mint. Pure, so every reason is held by a test rather than by/// an `if` in the middle of a pass.////// **THE USERNAME IS PART OF THE KEYCHAIN ITEM'S KEY**, so a note that matches/// on the host alone is a note that can be about an entry no checkout looks up/// any more: a re-pair gives this Mac a new device id, and the old entry then/// sits in the login keychain for ever with no expiry. An EMPTY username on/// the note is a note written before this was recorded — unknown, which is/// treated as different rather than as a match.pubfn needs_remint( note: Option<&Note>, host: &str, username: &str, refused: bool,) -> bool {match note {None => true,Some(_) if refused => true,Some(held) => held.host != host || held.username != username, }}/// The `(host, username)` an erase must name: **THE NOTE'S OWN PAIR**.////// One declaration, because there are two callers and they had drifted:/// [`forget_stale`] followed this rule and `code.forgetCredential` — the/// panel's Remove, the one a person presses — erased under the pair the host is/// answering with RIGHT NOW. After a re-pair (a new device id) or a move/// between a LAN address and the relay name those are different pairs, so/// Remove took out nothing, dropped the note that was the only record of where/// the entry lived, and orphaned it in the login keychain for ever — a `device`/// credential has no expiry by design.////// A note with no username — one written before the field existed — has no pair/// to name, so the caller's is the best available.pubfn erase_pair<'a>( held: Option<&'a Note>, host: &'a str, username: &'a str,) -> (&'a str, &'a str) {match held {Some(note) if !note.username.is_empty() => (note.host.as_str(), note.username.as_str()), _ => (host, username), }}/// Erase the keychain entry a stale note names, under ITS OWN pair.////// **THE NOTE'S PAIR AND NOT THE REQUEST'S**, which is the whole point after a/// re-pair: the entry that has to go is the one stored under the OLD device id,/// and erasing under the new one would take out nothing at all. A note with no/// username — one written before it was recorded — has no pair to name, so the/// request's is the best available and is used with that stated.////// Best effort, and the sentence is a log line: the install that follows stores/// under the new pair either way, and a keychain that would not give an entry/// up must not stop a Mac getting a working credential.fn forget_stale(request: &Install<'_>, held: Option<&Note>) {let (host, username) = erase_pair(held, request.host, request.username);ifletErr(said) = forget(request.helper, host, username, request.note) { eprintln!("cotton-client: the stale code credential for {host} could not be taken out of the \ keychain — {said}" ); }}/// One pass: mint if needed, store, read back, write the note.pubfn install(request: &Install<'_>, refused: bool) -> Outcome {// THE DESCRIPTION IS CHECKED BEFORE ANYTHING IS MINTED. `describable`// refuses a value `git credential` would read as the end of the// description, and a refusal after the mint would leave a live credential// in nobody's keychain.let query = match fill_input(request.host, request.username) {Ok(query) => query,Err(said) => returnOutcome::Refused(said), };let held = Note::read(request.note);if !needs_remint(held.as_ref(), request.host, request.username, refused) {let one = held .as_ref() .expect("needs_remint answered false, so there is a note");// **THE KEYCHAIN FIRST, AND ON THIS DISK.** What git holds is the one// thing every checkout on this Mac spends, and two questions about it// need no server: does it hold anything, and is what it holds signed// under a key the file has moved past?let in_git = request.helper.run("fill", &query);let password = in_git.as_ref().ok().and_then(|answer| password_of(answer));ifletSome(password) = password.as_deref() {if behind_the_key(password, request.key_version) { eprintln!("cotton-client: code credential {} is signed under a workspace key this \ Mac's file has rotated past — minting again", one.id );return remint_behind_the_key(request, held.as_ref(), &query, password); }if !request.confirm {// The local check: git holds a current credential, and the// server is asked on the pass that confirms, not this one.returnOutcome::AlreadyInstalled { id: one.id.clone(), installed_at: one.installed_at.clone(), }; } }// **THE SERVER'S ANSWER BEATS THE NOTE'S WORD.** A note is a fact about// THIS Mac's disk, and a revocation makes it wrong without touching it.// Until this asked, the recovery the module header describes had no// caller at all — every checkout on such a Mac `401`ed for ever while// the pass said "already installed".//// `None` from `still_live` is "could not ask" and is NOT a reason to// mint: a Mac spends most of its life away from its server.// **ASKED, AND THE ANSWER TOLD APART FROM THE SILENCE.** `Some(true)`// is a note the server confirmed; `Some(false)` is a credential it no// longer holds; `None` is a question that did not get through, and// that is NOT an answer — see `Outcome::Unconfirmed`.match list_over(request.fetch) .map(|listed| still_live(&listed, &one.id, request.now)) {// **THE KEYCHAIN'S WORD BEATS THE NOTE'S AND THE SERVER'S.** A// note is a fact about this Mac's disk and the list is a fact// about the server; neither says whether git still HOLDS the// entry. git erases it by itself: a `401` on any fetch or push —// one the relay answered while the serving Mac was overloaded,// 28 Sep 2026, 01:22 IST on a Mac — makes git `reject` the// credential it just used, and `osxkeychain` deletes the item.// The note stayed, the server still listed the id, and until this// asked git every pass said "already installed" about an entry// that was gone, so every checkout on that Mac failed with// "could not read Username" until somebody relaunched the app with// the note removed. So a confirmed note is READ BACK: git holding// a password is the common answer; git holding nothing is the// re-mint below, said out loud.Ok(Some(true)) => match &in_git {Ok(_) if password.is_some() => {returnOutcome::AlreadyInstalled { id: one.id.clone(), installed_at: one.installed_at.clone(), } }Ok(_) => eprintln!("cotton-client: the server still lists code credential {} but git holds no \ password for {} — minting again", one.id, request.host ),Err(said) => eprintln!("cotton-client: the server still lists code credential {} but git holds \ nothing for {} ({said}) — minting again", one.id, request.host ), },// A LIST THAT CAME BACK IN A SHAPE THIS CANNOT READ IS ALSO A// QUESTION THAT DID NOT GET THROUGH. `still_live` answers `None`// only when the body carries no `credentials` array, which says as// little about the credential as a timeout does.Ok(None) => {returnOutcome::Unconfirmed { id: one.id.clone(), installed_at: one.installed_at.clone(), why: "the server's answer carried no credentials list".to_string(), } }Err(why) => {returnOutcome::Unconfirmed { id: one.id.clone(), installed_at: one.installed_at.clone(), why, } }Ok(Some(false)) => {} }// THE DEAD KEYCHAIN ENTRY GOES FIRST. `approve` below stores under the// same (host, username) pair, but a `reject` here is what makes the// failure paths honest: a mint that then cannot be stored must not// leave git answering a credential the server refuses. forget_stale(request, held.as_ref()); } elseifletSome(stale) = held .as_ref() .filter(|note| note.host != request.host || note.username != request.username) {// **A RE-PAIR, OR A MOVE BETWEEN A LAN ADDRESS AND THE RELAY NAME.**// The install below stores under the NEW pair, which leaves the old// entry in the login keychain — under a device id no checkout looks up// and with no expiry, because a `device` credential has none by// design. So it is erased first, under its OWN pair. forget_stale(request, Some(stale)); }// THE ID THIS PASS IS REPLACING, read before the mint so the revoke below// has something to name. A `device` credential has NO EXPIRY by design, so// one this Mac has stopped using and nothing revokes goes on authenticating// the whole git surface — and the panel grows a row per re-mint that a// person cannot tell from the live one.let superseded = held.as_ref().map(|one| one.id.clone());let (id, secret) = match mint_over(request.fetch, request.mac_name) {Ok(minted) => minted,Err(sentence) => returnOutcome::Refused(sentence), }; store_minted(request, &query, superseded, id, secret)}/// A credential behind the key: MINT FIRST, and only then take the old one out.////// **THE OTHER ORDER FROM A DEAD NOTE's, and deliberately.** "Behind the key"/// is judged against THIS Mac's copy of the file, and this Mac's copy can be the/// wrong one — the 28 Sep Mac was exactly that, a stale machine that had rotated/// on its own. So the entry git holds is kept until a server has actually/// handed over its replacement: a mint that fails leaves this Mac with what it/// had, which may still be good somewhere, rather than with nothing.////// **AND A REPLACEMENT NO NEWER THAN WHAT GIT HOLDS IS NOT ONE.** If the server/// answering the name signs under a key version no newer than the credential/// git already holds, THIS Mac's file is the one ahead of the household — or/// the server is the stale one. Storing its answer would find it "behind" again/// on the next tick and mint every minute for ever; so the replacement is/// revoked, the entry git holds stays, and the pass answers a refusal the/// enrolment backs off on.fn remint_behind_the_key( request: &Install<'_>, held: Option<&Note>, query: &str, in_git: &str,) -> Outcome {let (id, secret) = match mint_over(request.fetch, request.mac_name) {Ok(minted) => minted,Err(sentence) => returnOutcome::Refused(sentence), };let version = |token: &str| { cotton_core::vault::code_tokens::selector(token).map(|selector| selector.vmk_version) };iflet (Some(fresh), Some(old)) = (version(&secret), version(in_git)) {if fresh <= old { abandon(request.fetch, &id);returnOutcome::Refused(format!("the server answering for this household signs code credentials under key \ version {fresh}, and this Mac's copy of the file names a newer one — the \ credential this Mac holds is kept, and Cotton will ask again later" )); } }// `approve` stores under the same pair; the old entry goes first so the// read-back below cannot answer it (`forget_stale`'s reason). forget_stale(request, held); store_minted(request, query, held.map(|one| one.id.clone()), id, secret)}/// Store a credential this pass minted, read it back, revoke the one it/// replaced, and write the note.fn store_minted( request: &Install<'_>, query: &str, superseded: Option<String>, id: String, secret: String,) -> Outcome {let description = match credential_input(request.host, request.username, &secret) {Ok(description) => description,Err(said) => {// A CREDENTIAL THE SERVER MINTED AND THIS MAC WILL NOT STORE IS// REVOKED. The only value this can refuse on is the secret itself// — host and username were checked before the mint — so this is a// server that answered something that is not a `ctg_`. abandon(request.fetch, &id);returnOutcome::Refused(said); } };ifletErr(sentence) = request.helper.run("approve", &description) {// A CREDENTIAL THAT WAS MINTED AND IS NOWHERE IS REVOKED, not left. On// a Mac with no credential helper this path runs at EVERY launch, so// without the revoke each one leaves behind another live credential in// nobody's keychain. abandon(request.fetch, &id);returnOutcome::Refused(sentence); }// THE READ-BACK, and it is not optional: `approve` with no helper// configured exits 0 and stores nothing, so an exit code proves that git// ran and not that a credential is anywhere.//// BOTH WAYS IT CAN GO WRONG MEAN THE SAME THING and get the same sentence.// A `fill` with no helper and no terminal fails LOUDLY ("could not read// Username: terminal prompts disabled"); a `fill` that answers somebody// else's value succeeds and is just as wrong. Either way the credential// this pass minted is not in this Mac's keychain, and what the person has// to do about it is the same — so git's own words are carried inside one// actionable sentence rather than reported as two different faults.let kept = match request.helper.run("fill", query) {Ok(answer) => {if password_of(&answer).as_deref() == Some(secret.as_str()) {Ok(()) } else {Err("git answered a different credential".to_string()) } }Err(sentence) => Err(sentence), };ifletErr(said) = kept { abandon(request.fetch, &id);returnOutcome::Refused(format!("git kept no credential for {} — this Mac has no credential helper configured. \ Install the Xcode Command Line Tools, which bring \ git-credential-osxkeychain and make it the default. git said: {said}", request.host )); }// THE ONE IT REPLACED, now that the new one is really in the keychain: the// order is deliberate, because a revoke that ran first and then a mint that// failed would leave this Mac with nothing at all.ifletSome(old) = superseded.filter(|old| *old != id) { abandon(request.fetch, &old); }let installed_at = request.now.format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string();let note = Note { id: id.clone(), installed_at: installed_at.clone(), host: request.host.to_string(), username: request.username.to_string(), };Outcome::Installed { id, installed_at,// The credential IS installed either way; see `Outcome::Installed`. note_problem: note.write(request.note).err(), }}/// Take this Mac's credential out of its keychain.////// The server-side revoke is `DELETE /v1/code/credentials/{id}`; this is the/// local half, and the note goes with it so the next pass mints again./// The NOTE goes whatever git said: a note claiming a credential this Mac may/// no longer hold would keep the next pass from minting one, which is the worse/// of the two failures. What git said comes back as a sentence for the caller/// to print.pubfn forget( helper: &dynCredentialHelper, host: &str, username: &str, note: &Path,) -> Result<(), String> {// THE NOTE GOES EVEN WHEN THE DESCRIPTION IS UNUSABLE. A note this build// cannot compose an erase for is a note that would keep the next pass from// minting, which is the worse of the two failures.let description = reject_input(host, username);let said = match &description {Ok(description) => helper.run("reject", description),Err(said) => Err(said.clone()), };let _ = std::fs::remove_file(note); said.map(|_| ())}#[cfg(test)]#[path = "keychain_tests.rs"]mod tests;