Skip to main content

greengate_runtime/
attest.rs

1//! The signed successor to [`crate::gate_stamp`]: an attestation CI can trust.
2//!
3//! `gate_stamp` answers a LOCAL question — "did the push gate already run on
4//! this commit?" — and its notes deliberately never leave the machine, because
5//! an unsigned note is only as honest as whoever can write the ref. This
6//! module answers the REMOTE version of the same question: "may CI skip a
7//! test job because the equivalent gate already passed here?" — and for that
8//! the note has to travel, so it has to be signed.
9//!
10//! # What is amont's, and what is attest's
11//!
12//! The attestation FORMAT — the payload, a note's blocks, the `attest-inputs`
13//! spec, fingerprints, the canonical tree, the note keys, signing, the
14//! fetch-append-push publish loop and the verifier — is attest's, and amont
15//! calls the `git_attest` library for every part of it (decisions ADR-0037).
16//! There used to be a copy here, kept in step by hand; a fix to the format now
17//! lands once.
18//!
19//! What stays here is amont's: WHEN to attest and WHICH gates a push vouches
20//! for (the dispatcher's knowledge), its own config and key, the recursive-push
21//! guard below, every line it prints, and the provenance record amont-agent
22//! hands it (decisions ADR-0036), which it signs and publishes through the
23//! same library under its own namespace.
24//!
25//! Every failure mode points the same direction as `gate_stamp`'s: no key, a
26//! signer that errors, a note git refused, a notes push the remote rejected —
27//! all mean "no attestation", and no attestation means CI RUNS the tests.
28//! Nothing here can let an untested tree skip CI; it can only cost a
29//! redundant run.
30//!
31//! One sharp edge is the notes push itself: `git push` from inside pre-push
32//! runs pre-push again. The child carries [`PUSH_GUARD`] in its environment
33//! and the dispatcher yields immediately when it sees it — checking a ref
34//! list that is only ever `refs/notes/amont-attest` would be work spent
35//! proving nothing.
36
37use crate::names::BIN;
38use std::path::{Path, PathBuf};
39
40use git_attest::format::block;
41use git_attest::notes::{publish as publish_notes, Publish, Published};
42use git_attest::produce::attestation;
43
44use crate::pushrefs::PushRef;
45
46pub use git_attest::format::{platform, FORMAT, INPUTS_REF, NAMESPACE, NOTES_REF};
47pub use git_attest::notes::{classify_push as classify_push_stderr, PushFailure};
48
49/// The order attest's name sets are read in (decisions ADR-0068): a block's
50/// header picks one, and its namespace follows. It mirrors git-attest's
51/// verify.rs read order, `[(GREEN, ..), (LEGACY, ..)]`; that order is owned
52/// by git-attest, and this copy is removed at the Phase 5 census.
53const READ_NAMES: [git_attest::format::Names; 2] =
54    [git_attest::format::GREEN, git_attest::format::LEGACY];
55
56/// The notes ref, fully qualified — `update-ref -d` needs it.
57pub const NOTES_FULL_REF: &str = "refs/notes/amont-attest";
58pub const INPUTS_FULL_REF: &str = "refs/notes/amont-attest-inputs";
59
60/// The provenance record (decisions ADR-0036, amont `docs/provenance.md`):
61/// what a push carried besides its tests, the plan and the verdicts on it.
62/// Its own ref, so CI's attestation verifier never reads it, and its own
63/// namespace, so a provenance signature is never accepted as an attestation.
64pub const PROVENANCE_REF: &str = "amont-provenance";
65pub const PROVENANCE_FULL_REF: &str = "refs/notes/amont-provenance";
66pub const PROVENANCE_NAMESPACE: &str = "amont-provenance";
67pub const PROVENANCE_FORMAT: &str = "amont-provenance-v1";
68
69/// Environment marker carried by the notes push so the recursive pre-push
70/// invocation stands down. See the module doc.
71pub const PUSH_GUARD: &str = "GREENGATE_ATTEST_PUSH";
72
73/// The repository a hook stands in: git starts hooks at the worktree top.
74fn here() -> &'static Path {
75    Path::new(".")
76}
77
78/// The opt-in switch. Off by default: an attestation is a statement to
79/// another system, and amont does not speak for a repository that never
80/// asked it to.
81const TOGGLE: &str = "greengate.attest";
82
83/// Where the signing key lives when the repository does not say.
84const KEY_CONFIG: &str = "greengate.attestKey";
85const KEY_DEFAULT: &str = ".ssh/amont-attest";
86
87/// Is the recursive-push marker set on THIS invocation?
88pub fn push_guard_active() -> bool {
89    std::env::var_os(PUSH_GUARD).is_some()
90}
91
92/// Has this repository opted in?
93pub fn enabled(settings: &crate::config::Settings) -> bool {
94    crate::config::boolean_or(settings, TOGGLE, false)
95}
96
97/// The signing key path: `greengate.attestKey`, else `~/.ssh/amont-attest`.
98///
99/// Read like `greengate.knownIdentity` is — a raw string through git, unset
100/// collapsing to the default — because a path has no shape git could
101/// validate for us anyway.
102fn key_path() -> Option<PathBuf> {
103    if let Some(k) = crate::git::stdout(&["config", "--get", KEY_CONFIG]) {
104        if !k.is_empty() {
105            return Some(PathBuf::from(k));
106        }
107    }
108    let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE"))?;
109    Some(PathBuf::from(home).join(KEY_DEFAULT))
110}
111
112/// pre-push, after every block gate has passed: attest each pushed tip and
113/// send the notes refs to the remote being pushed.
114///
115/// `gates` is what the dispatcher saw actually PASS — `Warned` and
116/// `Unavailable` never appear in it, because "could not run" is not
117/// "passed". Empty means nothing testlike ran, and an attestation listing
118/// no gates would be a signed way of saying nothing.
119///
120/// `cluster_gates` are the attestable `platform=any` gates the cluster passed
121/// (ADR-0016). Each pushed tip gets, besides the laptop's block, a second
122/// block on `x86_64-linux` naming only those the cluster proved on THAT tip's
123/// tree: a multi-tip push never signs a linux pass for a tree the cluster did
124/// not judge. Both blocks go out in one publish per notes ref. With
125/// `greengate.cluster.signer in-cluster`, a gate that a signer block filed on
126/// the tree by `cluster collect` covers is published as that block instead
127/// of being signed here; the rest are signed here, without waiting.
128///
129/// What each block says, and every key it is filed under (the tree and the
130/// commit in the main ref; each declared gate's fingerprint and the canonical
131/// tree in the inputs ref), is attest's [`attestation`]. The note goes on the
132/// TREE as well as the commit: the tree is what the signature covers, so it
133/// is the key that survives a squash-merge, an amend or a rebase, and the
134/// commit note is what `git log --notes` shows and an older verifier finds.
135///
136/// Best-effort throughout, and quiet about it: pre-push has already printed
137/// its verdicts, and a push that works minus its CI shortcut is not a
138/// problem anyone needs to solve at push time.
139pub fn attest_push(
140    settings: &crate::config::Settings,
141    remote: &str,
142    refs: &[PushRef],
143    gates: &[String],
144    cluster_gates: &[String],
145) {
146    attest_push_per_tip(settings, remote, refs, &|_| gates.to_vec(), cluster_gates);
147}
148
149/// [`attest_push`], with the laptop's gates asked per pushed tip:
150/// `gates_for(tip)` names only the gates whose run saw THAT tip's content
151/// (#289). A gate that ran in a dirty working tree tested what was on disk,
152/// not the commit, and its pass must not be signed onto the commit's tree.
153pub fn attest_push_per_tip(
154    settings: &crate::config::Settings,
155    remote: &str,
156    refs: &[PushRef],
157    gates_for: &dyn Fn(&str) -> Vec<String>,
158    cluster_gates: &[String],
159) {
160    if remote.is_empty() || !enabled(settings) {
161        return;
162    }
163    let Some(key) = key_path() else { return };
164    if !key.exists() {
165        crate::config::complain(
166            TOGGLE,
167            &format!("signing key {} does not exist", key.display()),
168            "no attestation (CI will run the tests)",
169        );
170        return;
171    }
172    let producer = env!("CARGO_PKG_VERSION");
173    // The laptop's gates signed on at least one tip, for the summary line.
174    let mut laptop_signed: Vec<String> = Vec::new();
175    let mut blocks: Vec<(String, String)> = Vec::new();
176    let mut input_blocks: Vec<(String, String)> = Vec::new();
177    let mut linux_signed: Vec<String> = Vec::new();
178    let (mut n_inputs, mut n_canon) = (0, 0);
179    // Read once, and only for a tip the cluster proved something on.
180    let in_cluster = std::cell::OnceCell::new();
181    for r in refs {
182        if is_zero(&r.local_oid) {
183            continue; // deleting a ref pushes no code
184        }
185        let gates = gates_for(&r.local_oid);
186        if gates.is_empty() && cluster_gates.is_empty() {
187            continue;
188        }
189        let gates_line = gates.join(" ");
190        let spec = format!("{}^{{tree}}", r.local_oid);
191        let Some(tree) = crate::git::stdout(&["rev-parse", &spec]) else {
192            continue;
193        };
194        let mut proved_here: Vec<String> = cluster_gates
195            .iter()
196            .filter(|g| crate::cluster::proved(g, &tree))
197            .cloned()
198            .collect();
199        // `greengate.cluster.signer in-cluster`: a gate a filed signer block
200        // already covers on this tree is published as that block, not signed
201        // again here; every other gate is signed here as before, at once.
202        if !proved_here.is_empty()
203            && *in_cluster.get_or_init(|| crate::cluster::in_cluster_signer().is_some())
204        {
205            for signed in filed_signer_blocks(&tree) {
206                let (covered, rest): (Vec<String>, Vec<String>) = proved_here
207                    .into_iter()
208                    .partition(|g| signed.gates.contains(g));
209                proved_here = rest;
210                if covered.is_empty() {
211                    continue;
212                }
213                for name in covered {
214                    if !linux_signed.contains(&name) {
215                        linux_signed.push(name);
216                    }
217                }
218                blocks.push((tree.clone(), signed.body.clone()));
219                blocks.push((r.local_oid.clone(), signed.body));
220            }
221        }
222        let platforms = [
223            (platform(), gates_line.clone(), Vec::new()),
224            (
225                crate::cluster::PLATFORM.to_string(),
226                proved_here.join(" "),
227                proved_here,
228            ),
229        ];
230        // Both platforms' blocks carry the same input fingerprints for this
231        // ref; the summary counts them once.
232        let mut counted = false;
233        for (on, line, linux_names) in platforms {
234            if line.is_empty() {
235                continue;
236            }
237            // The reasons a route is missing are attest's to give in CI's
238            // log; at push time they are noise.
239            let mut reasons = Vec::new();
240            let att = attestation(here(), &tree, &line, &on, producer, &mut reasons);
241            let Ok(sig) = git_attest::sign::sign(NAMESPACE, &att.payload, &key) else {
242                continue;
243            };
244            let body = block(&att.payload, &sig);
245            if !counted {
246                n_inputs += att.inputs.len();
247                n_canon += usize::from(att.canon.is_some());
248                counted = true;
249            }
250            for k in &att.input_keys {
251                input_blocks.push((k.clone(), body.clone()));
252            }
253            blocks.push((tree.clone(), body.clone()));
254            blocks.push((r.local_oid.clone(), body));
255            if linux_names.is_empty() {
256                for name in &gates {
257                    if !laptop_signed.contains(name) {
258                        laptop_signed.push(name.clone());
259                    }
260                }
261            }
262            for name in linux_names {
263                if !linux_signed.contains(&name) {
264                    linux_signed.push(name);
265                }
266            }
267        }
268    }
269    if blocks.is_empty() {
270        return;
271    }
272    // Each ref on its own: a main ref that is already up to date never
273    // short-circuits the inputs ref, which is how a push whose inputs ref
274    // failed earlier repairs the missing keys.
275    let main_ok = publish(remote, NOTES_REF, &blocks);
276    let inputs_ok = input_blocks.is_empty() || publish(remote, INPUTS_REF, &input_blocks);
277    if main_ok {
278        // Each list names its own platform, so the laptop's gates never read
279        // as attested on linux.
280        let mut signed_on = Vec::new();
281        if !laptop_signed.is_empty() {
282            signed_on.push(format!(
283                "{} on {}",
284                crate::ui::highlight(&laptop_signed.join(" ")),
285                platform()
286            ));
287        }
288        if !linux_signed.is_empty() {
289            signed_on.push(format!(
290                "{} on {}",
291                crate::ui::highlight(&linux_signed.join(" ")),
292                crate::cluster::PLATFORM
293            ));
294        }
295        let what = signed_on.join("; ");
296        crate::say!(
297            "{} attested {} for CI ({}{})",
298            crate::ui::valid_sign(),
299            what,
300            NOTES_REF,
301            if input_blocks.is_empty() {
302                String::new()
303            } else if inputs_ok {
304                match (n_inputs, n_canon) {
305                    (0, _) => ", canonical tree".to_string(),
306                    (n, 0) => format!(", {n} input fingerprints"),
307                    (n, _) => format!(", {n} input fingerprints, canonical tree"),
308                }
309            } else {
310                ", input fingerprints not published".to_string()
311            },
312        );
313    }
314}
315
316/// Where amont-agent leaves each provenance payload: `<config dir>/amont-agent/
317/// provenance`, the config dir resolved as amont-agent's `settings::config_dir`
318/// does (`$CLAUDE_CONFIG_DIR`, else `$HOME/.claude`, else
319/// `%USERPROFILE%\.claude`).
320///
321/// Never a git config key: a key could point amont at a directory nobody
322/// guards, and the payload's `review` line is only as true as the guard on
323/// amont-agent's store. `env` is the lookup, so a test needs no global state.
324fn provenance_dir(env: impl Fn(&str) -> Option<std::ffi::OsString>) -> Option<PathBuf> {
325    let config = match env("CLAUDE_CONFIG_DIR") {
326        Some(d) => PathBuf::from(d),
327        None => PathBuf::from(env("HOME").or_else(|| env("USERPROFILE"))?).join(".claude"),
328    };
329    Some(config.join("amont-agent").join("provenance"))
330}
331
332/// The repository's name as amont-agent files it (its `repo_name`): the
333/// directory holding the common git directory, so every worktree of a
334/// repository shares one name. Resolved the same way, step for step, or the
335/// two sides would look in different directories.
336fn repo_name() -> Option<String> {
337    let common = crate::git::stdout(&["rev-parse", "--git-common-dir"])?;
338    if common.is_empty() {
339        return None;
340    }
341    let common = PathBuf::from(common);
342    let common = if common.is_absolute() {
343        common
344    } else {
345        std::env::current_dir().ok()?.join(common)
346    };
347    let common = std::fs::canonicalize(&common).unwrap_or(common);
348    common
349        .parent()
350        .and_then(std::path::Path::file_name)
351        .map(|n| n.to_string_lossy().into_owned())
352        .filter(|n| !n.is_empty())
353}
354
355/// Sign and publish the provenance record amont-agent left for each pushed
356/// commit (ADR-0036). Opt-in, key and fail-open as [`attest_push`], with one
357/// difference: it does not wait for a gate to pass, because a push that changes
358/// only documentation or its plan still carries a plan and a review.
359pub fn provenance_push(settings: &crate::config::Settings, remote: &str, refs: &[PushRef]) {
360    if remote.is_empty() || !enabled(settings) {
361        return;
362    }
363    let (Some(dir), Some(name)) = (provenance_dir(|k| std::env::var_os(k)), repo_name()) else {
364        return;
365    };
366    provenance_push_from(&dir.join(name), remote, refs);
367}
368
369/// [`provenance_push`] reading payloads from `dir`.
370fn provenance_push_from(dir: &std::path::Path, remote: &str, refs: &[PushRef]) {
371    let mut found: Vec<(PathBuf, String, String, String)> = Vec::new();
372    for r in refs {
373        if is_zero(&r.local_oid) {
374            continue;
375        }
376        let file = dir.join(&r.local_oid);
377        let Ok(payload) = std::fs::read_to_string(&file) else {
378            continue; // no record for this commit: nothing to say
379        };
380        let spec = format!("{}^{{tree}}", r.local_oid);
381        let Some(tree) = crate::git::stdout(&["rev-parse", &spec]) else {
382            continue;
383        };
384        let first = payload.lines().next().unwrap_or_default();
385        let claimed = payload.lines().find_map(|l| l.strip_prefix("tree "));
386        if first != PROVENANCE_FORMAT || claimed != Some(tree.as_str()) {
387            crate::say!(
388                "  provenance for {} not signed: its payload is not an {PROVENANCE_FORMAT} record of this tree",
389                &r.local_oid[..r.local_oid.len().min(7)]
390            );
391            continue;
392        }
393        // The canonical tree is a tree fact the signer owns (attest SPEC,
394        // "The handoff"): a payload that states one is refused, never fixed
395        // up, and the person is told which file to delete.
396        if payload
397            .lines()
398            .any(|l| l.split_ascii_whitespace().next() == Some("canon"))
399        {
400            for line in canon_refusal(&r.local_oid, &file) {
401                crate::say!("{line}");
402            }
403            continue;
404        }
405        // canon(T) whatever `planExempt` says: that governs skipping a gate,
406        // not a tree's identity. No canon, no signature: kept for next time.
407        let Ok(canon) = git_attest::fingerprint::canon(here(), &tree) else {
408            crate::say!(
409                "  provenance for {} not signed: its canonical tree cannot be computed;",
410                &r.local_oid[..r.local_oid.len().min(7)]
411            );
412            crate::say!("    the payload is kept for the next push");
413            continue;
414        };
415        let payload = with_canon(&payload, &canon);
416        found.push((file, r.local_oid.clone(), tree, payload));
417    }
418    if found.is_empty() {
419        return;
420    }
421    let Some(key) = key_path().filter(|k| k.exists()) else {
422        crate::say!("  provenance not signed: no signing key");
423        return;
424    };
425    let mut blocks: Vec<(String, String)> = Vec::new();
426    let mut signed: Vec<PathBuf> = Vec::new();
427    for (file, commit, tree, payload) in found {
428        let Ok(sig) = git_attest::sign::sign(PROVENANCE_NAMESPACE, &payload, &key) else {
429            continue;
430        };
431        let body = block(&payload, &sig);
432        blocks.push((tree, body.clone()));
433        blocks.push((commit, body));
434        signed.push(file);
435    }
436    if blocks.is_empty() {
437        crate::say!("  provenance not signed: the signer refused");
438        return;
439    }
440    if publish(remote, PROVENANCE_REF, &blocks) {
441        for file in &signed {
442            if std::fs::remove_file(file).is_err() {
443                crate::say!(
444                    "  provenance published, but its payload {} could not be removed",
445                    file.display()
446                );
447            }
448        }
449        crate::say!(
450            "{} provenance published ({PROVENANCE_REF})",
451            crate::ui::valid_sign()
452        );
453    } else {
454        crate::say!("  provenance not published: kept for the next push");
455    }
456}
457
458/// `payload` with `canon <canon>` inserted right after its first `tree` line,
459/// where attest SPEC `amont-provenance-v1` places it.
460fn with_canon(payload: &str, canon: &str) -> String {
461    let mut out = String::with_capacity(payload.len() + canon.len() + 7);
462    let mut done = false;
463    for line in payload.split_inclusive('\n') {
464        out.push_str(line);
465        if !done && line.starts_with("tree ") {
466            if !line.ends_with('\n') {
467                out.push('\n');
468            }
469            out.push_str(&format!("canon {canon}\n"));
470            done = true;
471        }
472    }
473    out
474}
475
476/// What is said for a payload that carries its own `canon` line: the reason
477/// and the fix, every line at most 80 columns for a path of usual length. The
478/// file is named as its directory and its name, so neither line holds both.
479fn canon_refusal(commit: &str, file: &std::path::Path) -> Vec<String> {
480    let dir = file.parent().unwrap_or(file).display().to_string();
481    let name = file
482        .file_name()
483        .map(|n| n.to_string_lossy().into_owned())
484        .unwrap_or_default();
485    vec![
486        format!(
487            "  provenance for {} not signed: its payload carries a canon line",
488            &commit[..commit.len().min(7)]
489        ),
490        "    (a pre-release amont-agent wrote it); delete the file".to_string(),
491        format!("    {name} in"),
492        format!("    {dir}"),
493        "    and upgrade amont-agent".to_string(),
494    ]
495}
496
497/// How many times a push that lost a race is retried before giving up.
498const PUSH_ATTEMPTS: u32 = 4;
499
500/// Publish `blocks` (object, block) to `notes_ref` (short name) on `remote`
501/// through attest's loop: fetch the remote's ref into a temporary one, append
502/// each block not already there, push, and go again on a lost race. Never
503/// `notes add -f` (it erases every other producer's block) and never a push
504/// of the local ref (it would re-publish a block origin revoked). The push
505/// carries [`PUSH_GUARD`] so this hook's own pre-push stands down, and does
506/// not wait between rounds: this is the commit path.
507fn publish(remote: &str, notes_ref: &str, blocks: &[(String, String)]) -> bool {
508    let how = Publish {
509        remote,
510        attempts: PUSH_ATTEMPTS,
511        pause: false,
512        identity: None,
513        push_env: &[(PUSH_GUARD, "1")],
514    };
515    let mut log = Vec::new();
516    matches!(
517        publish_notes(here(), &how, notes_ref, blocks, &mut log),
518        Published::Pushed | Published::AlreadyPresent
519    )
520}
521
522/// `amont attest covered` — the verifying side, as a one-liner for CI that is
523/// neither GitHub nor Forgejo: the gate names a VALID attestation covers for
524/// the tree checked out here, space-separated, or `None`.
525///
526/// attest's verifier, the one its action and `git-attest covered` run: input
527/// fingerprints, the canonical tree and every block of a note included.
528/// `principal` of `None` accepts whoever the signature says, if that key is in
529/// the signers file. `anywhere` names the gates accepted from any platform
530/// (`amont stamps` passes the trusted `platform=any` ones; CI's one-liner
531/// passes none). Lines that say the repository's refs changed, or that
532/// something committed is deprecated, go to stderr; fail-open is the caller's
533/// contract, not its option.
534pub fn covered(
535    signers: &Path,
536    principal: Option<&str>,
537    require_platform: Option<&str>,
538    anywhere: &[String],
539) -> Option<String> {
540    covered_in(here(), signers, principal, require_platform, anywhere)
541}
542
543/// [`covered`] for the tree checked out in `dir`: a detached checkout of some
544/// other tree answers for that tree (`amont stamps --tree`). The verifier
545/// judges the tree it is pointed at and syncs the notes from origin, so a
546/// caller that can answer without it should not ask.
547pub fn covered_in(
548    dir: &Path,
549    signers: &Path,
550    principal: Option<&str>,
551    require_platform: Option<&str>,
552    anywhere: &[String],
553) -> Option<String> {
554    covered_report(dir, signers, principal, require_platform, anywhere).gates
555}
556
557/// What `amont attest covered` found: the gates a valid attestation covers,
558/// and every attestation that exists for this tree but whose signature did
559/// not verify (amont#271). The two "nothing" cases, no attestation and a
560/// rejected one, are told apart by `rejected`.
561#[derive(Debug, Clone, PartialEq, Eq, Default)]
562pub struct Covered {
563    pub gates: Option<String>,
564    pub rejected: Vec<String>,
565}
566
567/// [`covered_in`], keeping the rejections. Each one is also said on stderr,
568/// whatever the caller does with it: a bad signature is the absence worth
569/// alarming about, and stdout keeps its covered-names-only contract.
570pub fn covered_report(
571    dir: &Path,
572    signers: &Path,
573    principal: Option<&str>,
574    require_platform: Option<&str>,
575    anywhere: &[String],
576) -> Covered {
577    let verdict =
578        git_attest::verify::evaluate(dir, signers, principal, require_platform, anywhere, false);
579    for line in verdict.loud.iter().chain(&verdict.warnings) {
580        eprintln!("{BIN}: {line}");
581    }
582    for line in verified_lines(&verdict) {
583        eprintln!("{BIN}: {line}");
584    }
585    let rejected = signature_rejections(&verdict.trail);
586    for why in &rejected {
587        eprintln!("{BIN}: an attestation was found but did not verify: {why}");
588    }
589    Covered {
590        gates: (!verdict.gates.is_empty()).then(|| verdict.gates.join(" ")),
591        rejected,
592    }
593}
594
595/// One `verified under <namespace>` line per name set a covering block
596/// verified under, in git-attest's own wording, so a count of those lines
597/// covers greengate's verifications too.
598fn verified_lines(verdict: &git_attest::verify::Verdict) -> Vec<String> {
599    verdict
600        .verified_under
601        .iter()
602        .map(|ns| format!("verified under {ns}"))
603        .collect()
604}
605
606/// The verifier's trail lines that say a note's signature did not verify:
607/// `note on <where>: <why>` (git-attest 1.6 `verify`). The other lines about a
608/// note (`… carries no signature block`, `… has more than N blocks`) carry no
609/// `: `, and a tree that moved is not a `note on` line at all.
610fn signature_rejections(trail: &[String]) -> Vec<String> {
611    trail
612        .iter()
613        .filter(|line| line.starts_with("note on ") && line.contains(": "))
614        .cloned()
615        .collect()
616}
617
618/// A block the in-cluster signer wrote (`greengate cluster sign`), checked.
619#[derive(Debug, Clone, PartialEq, Eq)]
620pub(crate) struct SignerBlock {
621    /// Who the signature verified as.
622    pub principal: String,
623    /// The gates its payload names.
624    pub gates: Vec<String>,
625    /// The block as a note holds it.
626    pub body: String,
627    /// The name set its header named, which its signature verified under.
628    pub names: git_attest::format::Names,
629}
630
631impl SignerBlock {
632    /// Whether the block is of the name set this greengate publishes
633    /// (`WRITE`): one of the other set would sit under a ref whose header is
634    /// not its own.
635    pub(crate) fn is_publishable(&self) -> bool {
636        self.names == git_attest::format::WRITE
637    }
638}
639
640/// Why a signer block is refused, by cause: what a person checks next
641/// differs.
642#[derive(Debug, Clone, PartialEq, Eq)]
643pub(crate) enum BlockRefusal {
644    /// The signature does not verify against the repository's
645    /// `allowed_signers`, it has none, or the principal is not bound to the
646    /// cluster's platform: the signers file is what to check.
647    Signer(String),
648    /// A block about something else: not one block of this format, another
649    /// platform or tree, or a gate missing. The ConfigMap is what to read.
650    Content(String),
651}
652
653impl BlockRefusal {
654    /// The reason, as said.
655    pub(crate) fn reason(&self) -> &str {
656        match self {
657            BlockRefusal::Signer(why) | BlockRefusal::Content(why) => why,
658        }
659    }
660}
661
662/// `body` as a signer block for `tree`: exactly one git-attest block, of
663/// this format, on the cluster's platform, for `tree`, whose signature
664/// verifies against `signers` (attest's verifier, platform-bound principals
665/// enforced) as a principal bound to the cluster's platform. `Err` is the
666/// reason it is refused, by cause. Every read of the format is attest's.
667pub(crate) fn signer_block(
668    body: &str,
669    tree: &str,
670    signers: &Path,
671) -> Result<SignerBlock, BlockRefusal> {
672    use git_attest::format::{bound_platform, field, split_blocks};
673    use BlockRefusal::{Content, Signer};
674    let (mut blocks, _) = split_blocks(body);
675    if blocks.len() != 1 {
676        return Err(Content(format!("{} signed blocks, not one", blocks.len())));
677    }
678    let signed_block = blocks.remove(0);
679    // The header names the set; the namespace follows it, never the other
680    // set's (ADR-0068): an old signature cannot pass as a new one.
681    let header = signed_block.payload.split('\n').next();
682    let Some(names) = READ_NAMES.into_iter().find(|n| Some(n.format) == header) else {
683        return Err(Content(format!(
684            "not an {} or {} payload",
685            git_attest::format::GREEN.format,
686            git_attest::format::LEGACY.format
687        )));
688    };
689    let on = field(&signed_block.payload, "platform");
690    if on != Some(crate::cluster::PLATFORM) {
691        return Err(Content(format!(
692            "its platform is {}, not {}",
693            on.unwrap_or("missing"),
694            crate::cluster::PLATFORM
695        )));
696    }
697    let claimed = field(&signed_block.payload, "tree");
698    if claimed != Some(tree) {
699        // The signer signed another run: the block's content, not the key.
700        return Err(Content(format!(
701            "it is for tree {}, not {tree}",
702            claimed.unwrap_or("missing")
703        )));
704    }
705    let principal = git_attest::sign::verify(
706        names.namespace,
707        &signed_block.payload,
708        &signed_block.signature,
709        signers,
710        None,
711    )
712    .map_err(|e| Signer(e.to_string()))?;
713    if bound_platform(&principal) != Some(crate::cluster::PLATFORM) {
714        return Err(Signer(format!(
715            "{principal} is not a principal bound to {}",
716            crate::cluster::PLATFORM
717        )));
718    }
719    Ok(SignerBlock {
720        principal,
721        gates: field(&signed_block.payload, "gates")
722            .unwrap_or("")
723            .split_whitespace()
724            .map(str::to_string)
725            .collect(),
726        body: block(&signed_block.payload, &signed_block.signature),
727        names,
728    })
729}
730
731/// Where `cluster collect` files a checked signer block until a push
732/// publishes it: attest's local-only notes (`refs/notes/attest-local/
733/// amont-attest`, SPEC "origin never saw them"). Not the local [`NOTES_REF`],
734/// which mirrors origin's and is replaced whenever it is synced.
735fn signer_notes_ref() -> String {
736    format!("{}{NOTES_REF}", git_attest::format::LOCAL_PREFIX)
737}
738
739/// File a checked signer block in the local-only notes ([`signer_notes_ref`])
740/// under each of `keys` (the tree, and the commit when known), where the next
741/// push finds it. Never pushed from here: the push publishes it to the
742/// remote's [`NOTES_REF`] with its own blocks. `Err` names the key and the
743/// ref git could not write: attest's `publish_local` says no more than that.
744pub(crate) fn file_signer_block(body: &str, keys: &[&str]) -> Result<(), String> {
745    let notes_ref = signer_notes_ref();
746    for key in keys {
747        let entry = [((*key).to_string(), body.to_string())];
748        if matches!(
749            git_attest::notes::publish_local(here(), None, &notes_ref, &entry),
750            Published::Error
751        ) {
752            return Err(format!(
753                "git could not write the note on {key} in {notes_ref}"
754            ));
755        }
756    }
757    Ok(())
758}
759
760/// The signer blocks filed on `tree` (by a collect) that still
761/// check, those on another platform or tree skipped before any signature is
762/// verified.
763fn filed_signer_blocks(tree: &str) -> Vec<SignerBlock> {
764    use git_attest::format::{field, split_blocks};
765    let Some(signers) = default_signers() else {
766        return Vec::new();
767    };
768    let notes_ref = signer_notes_ref();
769    let Some(note) = crate::git::stdout(&["notes", "--ref", &notes_ref, "show", tree]) else {
770        return Vec::new();
771    };
772    split_blocks(&note)
773        .0
774        .iter()
775        .filter(|b| {
776            field(&b.payload, "platform") == Some(crate::cluster::PLATFORM)
777                && field(&b.payload, "tree") == Some(tree)
778        })
779        .filter_map(|b| signer_block(&block(&b.payload, &b.signature), tree, &signers).ok())
780        // Published under the written ref, so only a block of the written set.
781        .filter(SignerBlock::is_publishable)
782        .collect()
783}
784
785/// Where the repository keeps its `allowed_signers`, resolved from the
786/// repository root as attest resolves it.
787pub fn default_signers() -> Option<PathBuf> {
788    git_attest::verify::default_signers(here())
789}
790
791/// A ref oid that is all zeros — git's spelling of "no object" in the
792/// pre-push ref list, for any hash width.
793fn is_zero(oid: &str) -> bool {
794    !oid.is_empty() && oid.bytes().all(|b| b == b'0')
795}
796
797/// uninstall: forget the local notes refs of both name sets. The copies already pushed to remotes are
798/// statements we made and stand by; only OUR bookkeeping is removed — the
799/// same line `gate_stamp::forget` draws.
800pub fn forget() -> bool {
801    let mut deleted = false;
802    for names in READ_NAMES {
803        let full = format!("refs/notes/{}", names.notes_ref);
804        deleted |= crate::git::succeeds(&["update-ref", "-d", &full]);
805    }
806    deleted
807}
808
809/// The same, for a repository this process is not standing in.
810pub fn forget_in(repo: &std::path::Path) -> bool {
811    let mut deleted = false;
812    for names in READ_NAMES {
813        let full = format!("refs/notes/{}", names.notes_ref);
814        deleted |= crate::git::succeeds_in(repo, &["update-ref", "-d", &full]);
815    }
816    deleted
817}
818
819#[cfg(test)]
820pub(crate) mod tests {
821    use super::*;
822
823    use std::process::Stdio;
824
825    fn canon(tree: &str) -> Option<String> {
826        git_attest::fingerprint::canon(here(), tree).ok()
827    }
828
829    fn sign(payload: &str, key: &Path) -> Option<String> {
830        git_attest::sign::sign(NAMESPACE, payload, key).ok()
831    }
832
833    fn verify(payload: &str, sig: &str, signers: &Path, principal: &str) -> bool {
834        verify_in(NAMESPACE, payload, sig, signers, principal)
835    }
836
837    fn verify_in(
838        namespace: &str,
839        payload: &str,
840        sig: &str,
841        signers: &Path,
842        principal: &str,
843    ) -> bool {
844        git_attest::sign::verify(namespace, payload, sig, signers, Some(principal)).is_ok()
845    }
846
847    /// `greengate.attest` and the key path come from git config, which each test
848    /// sets on its own repo; no policy is in play.
849    fn test_settings() -> crate::config::Settings {
850        crate::config::Settings::default()
851    }
852
853    use std::io::Write;
854    use std::path::Path;
855
856    /// Real repositories and real keys: every function here is a conversation
857    /// with git or ssh-keygen, and a mocked conversation tests the one we
858    /// imagined. Same doctrine as `gate_stamp`'s tests.
859    pub(crate) fn dir(name: &str) -> PathBuf {
860        let d = std::env::temp_dir().join(format!("attest-{name}-{}", std::process::id()));
861        let _ = std::fs::remove_dir_all(&d);
862        std::fs::create_dir_all(&d).unwrap();
863        d
864    }
865
866    /// A fixture git call that FAILS where it fails.
867    ///
868    /// This used to discard the exit status, and that is how a rare flake
869    /// stayed unreadable for a day: if the setup `git commit` did not
870    /// happen, the test carried on to an unborn HEAD, and the panic landed
871    /// three lines later on a missing gate stamp — a product-shaped
872    /// failure for a fixture-shaped cause. Same rule the checks obey:
873    /// git failing is not git answering.
874    fn git(dir: &Path, args: &[&str]) -> String {
875        let out = std::process::Command::new("git")
876            .arg("-C")
877            .arg(dir)
878            .args(args)
879            .output()
880            .expect("git");
881        assert!(
882            out.status.success(),
883            "fixture: git {args:?} in {} exited {:?}: {}",
884            dir.display(),
885            out.status.code(),
886            String::from_utf8_lossy(&out.stderr).trim()
887        );
888        String::from_utf8_lossy(&out.stdout).trim().to_string()
889    }
890
891    fn repo(name: &str) -> PathBuf {
892        let d = dir(name);
893        git(&d, &["init", "-q", "--template=", "."]);
894        git(&d, &["config", "user.email", "t@t.test"]);
895        git(&d, &["config", "user.name", "t"]);
896        d
897    }
898
899    /// A throwaway ed25519 key plus the `allowed_signers` line CI would
900    /// commit for it, namespace-pinned exactly as the docs instruct.
901    fn keypair(d: &Path) -> (PathBuf, PathBuf) {
902        let key = d.join("attest_key");
903        let ok = std::process::Command::new("ssh-keygen")
904            .args(["-q", "-t", "ed25519", "-N", "", "-C", "test", "-f"])
905            .arg(&key)
906            .status()
907            .expect("ssh-keygen must exist for these tests")
908            .success();
909        assert!(ok, "keygen failed");
910        let pubkey = std::fs::read_to_string(key.with_extension("pub")).unwrap();
911        let signers = d.join("allowed_signers");
912        std::fs::write(
913            &signers,
914            format!("t@t.test namespaces=\"{NAMESPACE}\" {pubkey}"),
915        )
916        .unwrap();
917        (key, signers)
918    }
919
920    /// The module talks to the repo at the process cwd; serialised against
921    /// every other cwd-moving test via the crate-wide lock.
922    fn in_repo<T>(dir: &Path, f: impl FnOnce() -> T) -> T {
923        let _guard = crate::TEST_CWD.lock().unwrap_or_else(|p| p.into_inner());
924        let prev = std::env::current_dir().unwrap();
925        std::env::set_current_dir(dir).unwrap();
926        let r = f();
927        std::env::set_current_dir(prev).unwrap();
928        r
929    }
930
931    /// A bare remote plus a work repo opted in, ready to push.
932    fn remote_and_work(name: &str) -> (PathBuf, PathBuf, PathBuf, PathBuf) {
933        let d = dir(name);
934        let (key, signers) = keypair(&d);
935        let remote = d.join("remote.git");
936        std::fs::create_dir_all(&remote).unwrap();
937        git(&remote, &["init", "-q", "--bare", "--template=", "."]);
938        let work = repo(&format!("{name}-work"));
939        git(
940            &work,
941            &["remote", "add", "origin", remote.to_str().unwrap()],
942        );
943        git(&work, &["config", "greengate.attest", "true"]);
944        git(
945            &work,
946            &["config", "greengate.attestKey", key.to_str().unwrap()],
947        );
948        std::fs::write(work.join("a.ts"), "x").unwrap();
949        git(&work, &["add", "a.ts"]);
950        git(&work, &["commit", "-qm", "chore: a"]);
951        (d, work, remote, signers)
952    }
953
954    fn push_ref_for(work: &Path) -> PushRef {
955        PushRef {
956            local_ref: "refs/heads/main".into(),
957            local_oid: git(work, &["rev-parse", "HEAD"]),
958            remote_ref: "refs/heads/main".into(),
959            remote_oid: "0".repeat(40),
960        }
961    }
962
963    #[test]
964    fn the_provenance_dir_is_resolved_like_amont_agents_config_dir() {
965        use std::ffi::OsString;
966        let env = |pairs: &'static [(&'static str, &'static str)]| {
967            move |k: &str| {
968                pairs
969                    .iter()
970                    .find(|(n, _)| *n == k)
971                    .map(|(_, v)| OsString::from(v))
972            }
973        };
974        assert_eq!(
975            provenance_dir(env(&[("CLAUDE_CONFIG_DIR", "/c"), ("HOME", "/h")])),
976            Some(PathBuf::from("/c/amont-agent/provenance"))
977        );
978        assert_eq!(
979            provenance_dir(env(&[("HOME", "/h"), ("USERPROFILE", "/u")])),
980            Some(PathBuf::from("/h/.claude/amont-agent/provenance"))
981        );
982        assert_eq!(
983            provenance_dir(env(&[("USERPROFILE", "/u")])),
984            Some(PathBuf::from("/u/.claude/amont-agent/provenance"))
985        );
986        assert_eq!(provenance_dir(env(&[])), None);
987    }
988
989    /// A repository with a bare origin, the toggle on and a key; one commit
990    /// that carries a plan. Returns (scratch, work, remote, head, tree,
991    /// signers).
992    fn provenance_world(name: &str) -> (PathBuf, PathBuf, PathBuf, String, String, PathBuf) {
993        provenance_world_in(name, None)
994    }
995
996    /// [`provenance_world`] in a repository of `object_format`.
997    fn provenance_world_in(
998        name: &str,
999        object_format: Option<&str>,
1000    ) -> (PathBuf, PathBuf, PathBuf, String, String, PathBuf) {
1001        let d = dir(name);
1002        let (key, _) = keypair(&d);
1003        let pubkey = std::fs::read_to_string(key.with_extension("pub")).unwrap();
1004        let signers = d.join("allowed_signers_provenance");
1005        std::fs::write(
1006            &signers,
1007            format!("t@t.test namespaces=\"{NAMESPACE},{PROVENANCE_NAMESPACE}\" {pubkey}"),
1008        )
1009        .unwrap();
1010        let remote = d.join("remote.git");
1011        std::fs::create_dir_all(&remote).unwrap();
1012        let fmt = format!("--object-format={}", object_format.unwrap_or("sha1"));
1013        git(&remote, &["init", "-q", "--bare", "--template=", &fmt, "."]);
1014        let work = match object_format {
1015            None => repo(&format!("{name}-work")),
1016            Some(f) => {
1017                let w = dir(&format!("{name}-work"));
1018                let fmt = format!("--object-format={f}");
1019                git(&w, &["init", "-q", "--template=", &fmt, "."]);
1020                git(&w, &["config", "user.email", "t@t.test"]);
1021                git(&w, &["config", "user.name", "t"]);
1022                w
1023            }
1024        };
1025        git(
1026            &work,
1027            &["remote", "add", "origin", remote.to_str().unwrap()],
1028        );
1029        git(&work, &["config", "greengate.attest", "true"]);
1030        git(
1031            &work,
1032            &["config", "greengate.attestKey", key.to_str().unwrap()],
1033        );
1034        std::fs::write(work.join("README.md"), "words").unwrap();
1035        std::fs::create_dir_all(work.join("docs/plans")).unwrap();
1036        std::fs::write(work.join("docs/plans/p.md"), "# P\n").unwrap();
1037        git(&work, &["add", "README.md", "docs/plans/p.md"]);
1038        git(&work, &["commit", "-qm", "docs: words"]);
1039        let head = git(&work, &["rev-parse", "HEAD"]);
1040        let tree = git(&work, &["rev-parse", "HEAD^{tree}"]);
1041        (d, work, remote, head, tree, signers)
1042    }
1043
1044    fn record(head: &str, tree: &str) -> String {
1045        format!(
1046            "{PROVENANCE_FORMAT}\ncommit {head}\ntree {tree}\n\
1047             plan docs/plans/p.md {}\nreview reviewed {}\npreview not-required\n\
1048             producer amont-agent 0.0.0\n",
1049            "a".repeat(64),
1050            "c".repeat(64)
1051        )
1052    }
1053
1054    /// canon(T) as attest SPEC defines it, by hand and independent of
1055    /// `attest_inputs`: the quoted listing, the oid of every regular file
1056    /// under the top-level `docs/plans/` zeroed, through `git hash-object`.
1057    fn canon_by_hand(work: &Path, tree: &str) -> String {
1058        let listing = git(
1059            work,
1060            &[
1061                "-c",
1062                "core.quotePath=true",
1063                "ls-tree",
1064                "-r",
1065                "--full-tree",
1066                tree,
1067            ],
1068        );
1069        let mut text = String::new();
1070        for line in listing.lines() {
1071            let (head, path) = line.split_once('\t').unwrap();
1072            let f: Vec<&str> = head.split(' ').collect();
1073            let plan = matches!(f[0], "100644" | "100755")
1074                && (path.starts_with("docs/plans/") || path.starts_with("\"docs/plans/"));
1075            if plan {
1076                text.push_str(&format!(
1077                    "{} {} {}\t{path}\n",
1078                    f[0],
1079                    f[1],
1080                    "0".repeat(f[2].len())
1081                ));
1082            } else {
1083                text.push_str(&format!("{line}\n"));
1084            }
1085        }
1086        let mut child = std::process::Command::new("git")
1087            .arg("-C")
1088            .arg(work)
1089            .args(["hash-object", "--stdin"])
1090            .stdin(Stdio::piped())
1091            .stdout(Stdio::piped())
1092            .spawn()
1093            .unwrap();
1094        child
1095            .stdin
1096            .take()
1097            .unwrap()
1098            .write_all(text.as_bytes())
1099            .unwrap();
1100        let out = child.wait_with_output().unwrap();
1101        String::from_utf8_lossy(&out.stdout).trim().to_string()
1102    }
1103
1104    /// The signed payload of `object` in the remote's provenance ref.
1105    fn provenance_payload(remote: &Path, object: &str) -> (String, String) {
1106        let note = git(remote, &["notes", "--ref", PROVENANCE_REF, "show", object]);
1107        let (p, sig) = note
1108            .split_once("\n\n")
1109            .expect("payload, blank line, signature");
1110        (format!("{p}\n"), sig.to_string())
1111    }
1112
1113    fn push_of(head: &str) -> PushRef {
1114        PushRef {
1115            local_ref: "refs/heads/feat/x".into(),
1116            local_oid: head.to_string(),
1117            remote_ref: "refs/heads/feat/x".into(),
1118            remote_oid: "0".repeat(40),
1119        }
1120    }
1121
1122    /// A payload left by amont-agent reaches the remote as a note on both
1123    /// the tree and the commit, verifies under its own namespace only, and
1124    /// leaves the attestation ref alone. The file is gone once published.
1125    #[test]
1126    fn a_provenance_payload_is_signed_and_published_by_tree_and_commit() {
1127        let (d, work, remote, head, tree, signers) = provenance_world("prov-e2e");
1128        let payloads = d.join("payloads");
1129        std::fs::create_dir_all(&payloads).unwrap();
1130        let file = payloads.join(&head);
1131        let body = record(&head, &tree);
1132        std::fs::write(&file, &body).unwrap();
1133        let gates = ["pre-push-cargo-test".to_string()];
1134        in_repo(&work, || {
1135            attest_push(&test_settings(), "origin", &[push_of(&head)], &gates, &[])
1136        });
1137        let attested = git(&remote, &["notes", "--ref", NOTES_REF, "show", &head]);
1138        in_repo(&work, || {
1139            provenance_push_from(&payloads, "origin", &[push_of(&head)])
1140        });
1141        // The signer inserts canon(T) right after `tree`; everything else is
1142        // amont-agent's payload byte for byte.
1143        let canon = canon_by_hand(&work, &tree);
1144        assert_ne!(
1145            canon, tree,
1146            "the tree carries a plan, so canon(T) is not its oid"
1147        );
1148        let signed = body.replacen(
1149            &format!("tree {tree}\n"),
1150            &format!("tree {tree}\ncanon {canon}\n"),
1151            1,
1152        );
1153        for object in [&head, &tree] {
1154            let (p, sig) = provenance_payload(&remote, object);
1155            assert_eq!(p, signed, "the payload, with canon(T) inserted, is signed");
1156            assert_eq!(p.lines().nth(3), Some(format!("canon {canon}").as_str()));
1157            assert!(verify_in(
1158                PROVENANCE_NAMESPACE,
1159                &p,
1160                &sig,
1161                &signers,
1162                "t@t.test"
1163            ));
1164            assert!(
1165                !verify_in(NAMESPACE, &p, &sig, &signers, "t@t.test"),
1166                "a provenance signature is never an attestation"
1167            );
1168        }
1169        assert!(!file.exists(), "a published payload is deleted");
1170        assert_eq!(
1171            git(&remote, &["notes", "--ref", NOTES_REF, "show", &head]),
1172            attested,
1173            "the attestation note is byte-identical with a provenance payload present"
1174        );
1175        let _ = std::fs::remove_dir_all(&d);
1176        let _ = std::fs::remove_dir_all(&work);
1177    }
1178
1179    #[test]
1180    fn a_payload_for_another_tree_is_neither_signed_nor_deleted() {
1181        let (d, work, remote, head, _tree, _) = provenance_world("prov-mismatch");
1182        let payloads = d.join("payloads");
1183        std::fs::create_dir_all(&payloads).unwrap();
1184        let file = payloads.join(&head);
1185        std::fs::write(&file, record(&head, &"b".repeat(40))).unwrap();
1186        in_repo(&work, || {
1187            provenance_push_from(&payloads, "origin", &[push_of(&head)])
1188        });
1189        assert!(file.exists(), "a mismatched payload is kept");
1190        let refs = git(&remote, &["for-each-ref", PROVENANCE_FULL_REF]);
1191        assert!(refs.is_empty(), "nothing was published: {refs}");
1192        let _ = std::fs::remove_dir_all(&d);
1193        let _ = std::fs::remove_dir_all(&work);
1194    }
1195
1196    /// A payload that already states a canonical tree was written by a
1197    /// pre-release amont-agent: it is refused, never signed, never removed.
1198    #[test]
1199    fn a_payload_with_a_canon_line_is_refused_and_kept() {
1200        let (d, work, remote, head, tree, _) = provenance_world("prov-canon");
1201        let payloads = d.join("payloads");
1202        std::fs::create_dir_all(&payloads).unwrap();
1203        let file = payloads.join(&head);
1204        let old = record(&head, &tree).replacen(
1205            &format!("tree {tree}\n"),
1206            &format!("tree {tree}\ncanon {}\n", "c".repeat(64)),
1207            1,
1208        );
1209        std::fs::write(&file, &old).unwrap();
1210        in_repo(&work, || {
1211            provenance_push_from(&payloads, "origin", &[push_of(&head)])
1212        });
1213        assert_eq!(
1214            std::fs::read_to_string(&file).unwrap(),
1215            old,
1216            "kept as it was"
1217        );
1218        let refs = git(&remote, &["for-each-ref", PROVENANCE_FULL_REF]);
1219        assert!(refs.is_empty(), "nothing was published: {refs}");
1220        let _ = std::fs::remove_dir_all(&d);
1221        let _ = std::fs::remove_dir_all(&work);
1222    }
1223
1224    /// The refusal names the reason, the file and the fix, in lines of at
1225    /// most 80 columns for a usual path, a sha256 commit included.
1226    #[test]
1227    fn the_canon_refusal_fits_in_80_columns() {
1228        for commit in [
1229            "9f1c2ab0d6e4c1b2a3f405e6d7c8b9a0f1e2d3c4".to_string(),
1230            "e".repeat(64),
1231        ] {
1232            let file = PathBuf::from("/Users/someone/.claude/amont-agent/provenance/amont-agent")
1233                .join(&commit);
1234            let lines = canon_refusal(&commit, &file);
1235            assert!(lines[0].starts_with("  provenance for "), "{lines:?}");
1236            assert!(lines[0].contains(&commit[..7]), "{lines:?}");
1237            let all = lines.join("\n");
1238            assert!(all.contains("canon line") && all.contains("pre-release amont-agent"));
1239            assert!(all.contains(&format!("    {commit} in\n")), "{all}");
1240            assert!(all.contains("upgrade amont-agent"), "{all}");
1241            for l in &lines {
1242                assert!(
1243                    l.chars().count() <= 80,
1244                    "{} columns: {l}",
1245                    l.chars().count()
1246                );
1247            }
1248        }
1249    }
1250
1251    /// No canon(T), no signature: the payload waits for the next push.
1252    #[test]
1253    fn a_failed_canon_keeps_the_payload() {
1254        let (d, work, remote, head, tree, _) = provenance_world("prov-nocanon");
1255        // The commit and its tree still resolve; listing the tree does not.
1256        let docs = git(&work, &["rev-parse", &format!("{tree}:docs")]);
1257        let objects = PathBuf::from(git(&work, &["rev-parse", "--git-path", "objects"]));
1258        let objects = if objects.is_absolute() {
1259            objects
1260        } else {
1261            work.join(objects)
1262        };
1263        std::fs::remove_file(objects.join(&docs[..2]).join(&docs[2..])).unwrap();
1264        let payloads = d.join("payloads");
1265        std::fs::create_dir_all(&payloads).unwrap();
1266        let file = payloads.join(&head);
1267        std::fs::write(&file, record(&head, &tree)).unwrap();
1268        in_repo(&work, || {
1269            assert_eq!(canon(&tree), None);
1270            provenance_push_from(&payloads, "origin", &[push_of(&head)])
1271        });
1272        assert!(file.exists(), "a payload without a canon is kept");
1273        let refs = git(&remote, &["for-each-ref", PROVENANCE_FULL_REF]);
1274        assert!(refs.is_empty(), "nothing was published: {refs}");
1275        let _ = std::fs::remove_dir_all(&d);
1276        let _ = std::fs::remove_dir_all(&work);
1277    }
1278
1279    /// The hook's cwd is the worktree, so canon(T) is of the repository's own
1280    /// object format: 64 hex in a sha256 repository.
1281    #[test]
1282    fn a_sha256_repository_signs_a_64_hex_canon() {
1283        let (d, work, remote, head, tree, _) = provenance_world_in("prov-sha256", Some("sha256"));
1284        assert_eq!(tree.len(), 64);
1285        let payloads = d.join("payloads");
1286        std::fs::create_dir_all(&payloads).unwrap();
1287        std::fs::write(payloads.join(&head), record(&head, &tree)).unwrap();
1288        in_repo(&work, || {
1289            provenance_push_from(&payloads, "origin", &[push_of(&head)])
1290        });
1291        let (p, _) = provenance_payload(&remote, &head);
1292        let canon = canon_by_hand(&work, &tree);
1293        assert_eq!(canon.len(), 64);
1294        assert_eq!(
1295            p.lines().nth(3),
1296            Some(format!("canon {canon}").as_str()),
1297            "{p}"
1298        );
1299        let _ = std::fs::remove_dir_all(&d);
1300        let _ = std::fs::remove_dir_all(&work);
1301    }
1302
1303    #[test]
1304    fn a_failed_publish_keeps_the_payload_for_the_next_push() {
1305        let (d, work, _remote, head, tree, _) = provenance_world("prov-fail");
1306        git(
1307            &work,
1308            &[
1309                "remote",
1310                "set-url",
1311                "origin",
1312                d.join("gone.git").to_str().unwrap(),
1313            ],
1314        );
1315        let payloads = d.join("payloads");
1316        std::fs::create_dir_all(&payloads).unwrap();
1317        let file = payloads.join(&head);
1318        std::fs::write(&file, record(&head, &tree)).unwrap();
1319        in_repo(&work, || {
1320            provenance_push_from(&payloads, "origin", &[push_of(&head)])
1321        });
1322        assert!(file.exists(), "an unpublished payload is kept");
1323        let _ = std::fs::remove_dir_all(&d);
1324        let _ = std::fs::remove_dir_all(&work);
1325    }
1326
1327    /// The payload directory comes from the environment only: a git config
1328    /// key naming a directory full of payloads is never read.
1329    #[test]
1330    fn a_config_key_cannot_point_amont_at_other_payloads() {
1331        let (d, work, remote, head, tree, _) = provenance_world("prov-config");
1332        let elsewhere = d.join("elsewhere");
1333        let name = work.file_name().unwrap().to_string_lossy().into_owned();
1334        std::fs::create_dir_all(elsewhere.join(&name)).unwrap();
1335        std::fs::write(elsewhere.join(&name).join(&head), record(&head, &tree)).unwrap();
1336        for key in ["greengate.provenanceDir", "amont.agent.provenanceDir"] {
1337            git(&work, &["config", key, elsewhere.to_str().unwrap()]);
1338        }
1339        in_repo(&work, || {
1340            provenance_push(&test_settings(), "origin", &[push_of(&head)])
1341        });
1342        let refs = git(&remote, &["for-each-ref", PROVENANCE_FULL_REF]);
1343        assert!(refs.is_empty(), "a configured directory was read: {refs}");
1344        let _ = std::fs::remove_dir_all(&d);
1345        let _ = std::fs::remove_dir_all(&work);
1346    }
1347
1348    #[test]
1349    fn no_payload_publishes_nothing() {
1350        let (d, work, remote, head, _, _) = provenance_world("prov-none");
1351        let payloads = d.join("payloads");
1352        std::fs::create_dir_all(&payloads).unwrap();
1353        in_repo(&work, || {
1354            provenance_push_from(&payloads, "origin", &[push_of(&head)])
1355        });
1356        let refs = git(&remote, &["for-each-ref", PROVENANCE_FULL_REF]);
1357        assert!(refs.is_empty(), "{refs}");
1358        let _ = std::fs::remove_dir_all(&d);
1359        let _ = std::fs::remove_dir_all(&work);
1360    }
1361
1362    #[test]
1363    fn a_missing_key_signs_nothing() {
1364        assert!(sign("anything", Path::new("/nonexistent/key")).is_none());
1365    }
1366
1367    /// The full journey: a repo with the toggle on pushes, and the BARE
1368    /// remote ends up holding a note whose payload verifies and matches the
1369    /// pushed tree. This is everything CI relies on, minus CI.
1370    #[test]
1371    fn an_enabled_push_leaves_a_verifiable_note_on_the_remote() {
1372        let d = dir("e2e");
1373        let (key, signers) = keypair(&d);
1374        let remote = d.join("remote.git");
1375        std::fs::create_dir_all(&remote).unwrap();
1376        git(&remote, &["init", "-q", "--bare", "--template=", "."]);
1377        let work = repo("e2e-work");
1378        git(
1379            &work,
1380            &["remote", "add", "origin", remote.to_str().unwrap()],
1381        );
1382        git(&work, &["config", "greengate.attest", "true"]);
1383        git(
1384            &work,
1385            &["config", "greengate.attestKey", key.to_str().unwrap()],
1386        );
1387        std::fs::write(work.join("a.ts"), "x").unwrap();
1388        git(&work, &["add", "a.ts"]);
1389        git(&work, &["commit", "-qm", "chore: a"]);
1390        let head = git(&work, &["rev-parse", "HEAD"]);
1391        let tree = git(&work, &["rev-parse", "HEAD^{tree}"]);
1392        let push_ref = PushRef {
1393            local_ref: "refs/heads/main".into(),
1394            local_oid: head.clone(),
1395            remote_ref: "refs/heads/main".into(),
1396            remote_oid: "0".repeat(40),
1397        };
1398        in_repo(&work, || {
1399            attest_push(
1400                &test_settings(),
1401                "origin",
1402                &[push_ref],
1403                &["pre-push-run-tests-js".into()],
1404                &[],
1405            );
1406        });
1407        // The note exists on the REMOTE — the whole point is that it travels.
1408        let body = git(&remote, &["notes", "--ref", NOTES_REF, "show", &head]);
1409        assert!(!body.is_empty(), "no note reached the remote");
1410        let (p, sig) = body
1411            .split_once("\n\n")
1412            .expect("payload, blank line, signature");
1413        let p = format!("{p}\n"); // the blank-line split ate payload's trailing newline
1414        assert!(p.starts_with(FORMAT));
1415        assert!(
1416            p.contains(&format!("tree {tree}")),
1417            "attests the pushed tree"
1418        );
1419        assert!(
1420            verify(&p, sig, &signers, "t@t.test"),
1421            "the remote copy verifies"
1422        );
1423        let _ = std::fs::remove_dir_all(&d);
1424        let _ = std::fs::remove_dir_all(&work);
1425    }
1426
1427    /// Off by default: a repo that never opted in makes no statement, even
1428    /// with everything else in place.
1429    /// amont's half of input fingerprints: a push from a repository with a
1430    /// spec publishes the inputs ref too, and counts what it filed. What
1431    /// the block says (the `input` lines, the fingerprint, the key) is
1432    /// attest's, tested there (decisions ADR-0037).
1433    #[test]
1434    fn a_push_with_a_spec_publishes_the_inputs_ref() {
1435        let (_d, work, remote, _) = remote_and_work("inputs");
1436        std::fs::create_dir_all(work.join(".github")).unwrap();
1437        std::fs::write(
1438            work.join(".github/attest-inputs"),
1439            "pre-push-run-tests-js a.ts\n",
1440        )
1441        .unwrap();
1442        git(&work, &["add", ".github/attest-inputs"]);
1443        git(&work, &["commit", "-qm", "chore: spec"]);
1444        in_repo(&work, || {
1445            attest_push(
1446                &test_settings(),
1447                "origin",
1448                &[push_ref_for(&work)],
1449                &["pre-push-run-tests-js".into()],
1450                &[],
1451            );
1452        });
1453        let listed = git(&remote, &["notes", "--ref", INPUTS_REF, "list"]);
1454        // How many keys (the input's, the canonical tree's) is attest's.
1455        assert!(
1456            !listed.trim().is_empty(),
1457            "the inputs ref reached the remote"
1458        );
1459    }
1460
1461    #[test]
1462    fn no_opt_in_means_no_note() {
1463        let d = dir("optout");
1464        let (key, _) = keypair(&d);
1465        let remote = d.join("remote.git");
1466        std::fs::create_dir_all(&remote).unwrap();
1467        git(&remote, &["init", "-q", "--bare", "--template=", "."]);
1468        let work = repo("optout-work");
1469        git(
1470            &work,
1471            &["remote", "add", "origin", remote.to_str().unwrap()],
1472        );
1473        git(
1474            &work,
1475            &["config", "greengate.attestKey", key.to_str().unwrap()],
1476        );
1477        std::fs::write(work.join("a.ts"), "x").unwrap();
1478        git(&work, &["add", "a.ts"]);
1479        git(&work, &["commit", "-qm", "chore: a"]);
1480        let head = git(&work, &["rev-parse", "HEAD"]);
1481        let push_ref = PushRef {
1482            local_ref: "refs/heads/main".into(),
1483            local_oid: head.clone(),
1484            remote_ref: "refs/heads/main".into(),
1485            remote_oid: "0".repeat(40),
1486        };
1487        in_repo(&work, || {
1488            attest_push(
1489                &test_settings(),
1490                "origin",
1491                &[push_ref],
1492                &["pre-push-run-tests-js".into()],
1493                &[],
1494            );
1495        });
1496        assert!(
1497            git(&remote, &["notes", "--ref", NOTES_REF, "list"]).is_empty(),
1498            "an un-opted-in repo attested something"
1499        );
1500        let _ = std::fs::remove_dir_all(&d);
1501        let _ = std::fs::remove_dir_all(&work);
1502    }
1503
1504    /// A deletion pushes no code; an empty gate list says nothing. Neither
1505    /// may produce a note even in an enabled repo.
1506    #[test]
1507    fn deletions_and_empty_gates_attest_nothing() {
1508        let d = dir("nothing");
1509        let (key, _) = keypair(&d);
1510        let remote = d.join("remote.git");
1511        std::fs::create_dir_all(&remote).unwrap();
1512        git(&remote, &["init", "-q", "--bare", "--template=", "."]);
1513        let work = repo("nothing-work");
1514        git(
1515            &work,
1516            &["remote", "add", "origin", remote.to_str().unwrap()],
1517        );
1518        git(&work, &["config", "greengate.attest", "true"]);
1519        git(
1520            &work,
1521            &["config", "greengate.attestKey", key.to_str().unwrap()],
1522        );
1523        std::fs::write(work.join("a.ts"), "x").unwrap();
1524        git(&work, &["add", "a.ts"]);
1525        git(&work, &["commit", "-qm", "chore: a"]);
1526        let head = git(&work, &["rev-parse", "HEAD"]);
1527        let deletion = PushRef {
1528            local_ref: "(delete)".into(),
1529            local_oid: "0".repeat(40),
1530            remote_ref: "refs/heads/gone".into(),
1531            remote_oid: head.clone(),
1532        };
1533        let real = PushRef {
1534            local_ref: "refs/heads/main".into(),
1535            local_oid: head,
1536            remote_ref: "refs/heads/main".into(),
1537            remote_oid: "0".repeat(40),
1538        };
1539        in_repo(&work, || {
1540            attest_push(
1541                &test_settings(),
1542                "origin",
1543                &[deletion],
1544                &["pre-push-pytest".into()],
1545                &[],
1546            );
1547            attest_push(&test_settings(), "origin", &[real], &[], &[]);
1548        });
1549        assert!(git(&remote, &["notes", "--ref", NOTES_REF, "list"]).is_empty());
1550        let _ = std::fs::remove_dir_all(&d);
1551        let _ = std::fs::remove_dir_all(&work);
1552    }
1553
1554    /// The half CI actually calls, from CI's own vantage point: a fresh
1555    /// clone. `covered` fetches the notes ref itself, verifies, and answers
1556    /// with the gates — then stops answering the moment the tree drifts or
1557    /// the note is replaced by something unsigned.
1558    /// Only a signature that did not verify counts as a rejection (amont#271);
1559    /// a note with no signature, or a tree that moved, does not.
1560    #[test]
1561    fn a_rejection_is_a_note_whose_signature_did_not_verify() {
1562        let trail: Vec<String> = [
1563            "note on abc123: signature did not verify for principal t@t.test",
1564            "note on abc123 block 2: no principal matched",
1565            "note on def456 carries no signature block",
1566            "attested tree abc is not the checked-out tree def and neither its canonical tree nor an input fingerprint of abc123 matches",
1567            "no attestation found for tree abc",
1568        ]
1569        .iter()
1570        .map(|s| s.to_string())
1571        .collect();
1572        assert_eq!(
1573            signature_rejections(&trail),
1574            vec![
1575                "note on abc123: signature did not verify for principal t@t.test".to_string(),
1576                "note on abc123 block 2: no principal matched".to_string(),
1577            ]
1578        );
1579    }
1580
1581    #[test]
1582    fn covered_answers_in_a_fresh_clone_and_rejects_drift_and_forgery() {
1583        let d = dir("covered");
1584        let (key, signers) = keypair(&d);
1585        let remote = d.join("remote.git");
1586        std::fs::create_dir_all(&remote).unwrap();
1587        git(&remote, &["init", "-q", "--bare", "--template=", "."]);
1588        // The fixture pushes to `main`; a bare init on a machine whose
1589        // init.defaultBranch is the historical default leaves HEAD on
1590        // `master`, and a clone of that repository checks out NOTHING —
1591        // `covered` then answers None with a perfectly good note sitting in
1592        // the ref. Caught only in CI: dev machines set main globally.
1593        git(&remote, &["symbolic-ref", "HEAD", "refs/heads/main"]);
1594        let work = repo("covered-work");
1595        git(
1596            &work,
1597            &["remote", "add", "origin", remote.to_str().unwrap()],
1598        );
1599        git(&work, &["config", "greengate.attest", "true"]);
1600        git(
1601            &work,
1602            &["config", "greengate.attestKey", key.to_str().unwrap()],
1603        );
1604        std::fs::write(work.join("a.ts"), "x").unwrap();
1605        git(&work, &["add", "a.ts"]);
1606        git(&work, &["commit", "-qm", "chore: a"]);
1607        git(&work, &["push", "-q", "origin", "HEAD:main"]);
1608        let head = git(&work, &["rev-parse", "HEAD"]);
1609        let push_ref = PushRef {
1610            local_ref: "refs/heads/main".into(),
1611            local_oid: head.clone(),
1612            remote_ref: "refs/heads/main".into(),
1613            remote_oid: "0".repeat(40),
1614        };
1615        in_repo(&work, || {
1616            attest_push(
1617                &test_settings(),
1618                "origin",
1619                &[push_ref],
1620                &["pre-push-pytest".into()],
1621                &[],
1622            );
1623        });
1624        let clone = d.join("ci-checkout");
1625        git(
1626            &d,
1627            &[
1628                "clone",
1629                "-q",
1630                "--template=",
1631                remote.to_str().unwrap(),
1632                clone.to_str().unwrap(),
1633            ],
1634        );
1635        in_repo(&clone, || {
1636            assert_eq!(
1637                covered(&signers, Some("t@t.test"), Some(&platform()), &[]).as_deref(),
1638                Some("pre-push-pytest"),
1639                "a fresh clone verifies the attestation and reads the gates"
1640            );
1641            assert_eq!(
1642                covered(&signers, Some("t@t.test"), None, &[]).as_deref(),
1643                Some("pre-push-pytest"),
1644                "`any` covers a platform-independent suite"
1645            );
1646            // The matrix case this exists for: another leg asking about a
1647            // suite that never ran there.
1648            assert_eq!(
1649                covered(&signers, Some("t@t.test"), Some("s390x-aix"), &[]),
1650                None,
1651                "a pass on one platform is not evidence about another"
1652            );
1653            assert_eq!(
1654                covered(&signers, Some("someone@else.test"), None, &[]),
1655                None,
1656                "an unlisted principal covers nothing"
1657            );
1658        });
1659        // Tree drift: a new commit in the checkout is not the attested tree.
1660        std::fs::write(clone.join("b.ts"), "y").unwrap();
1661        git(&clone, &["config", "user.email", "t@t.test"]);
1662        git(&clone, &["config", "user.name", "t"]);
1663        git(&clone, &["add", "b.ts"]);
1664        git(&clone, &["commit", "-qm", "chore: b"]);
1665        in_repo(&clone, || {
1666            assert_eq!(
1667                covered(&signers, Some("t@t.test"), None, &[]),
1668                None,
1669                "drifted tree"
1670            );
1671        });
1672        // Forgery: replace the remote's notes with unsigned ones. covered's
1673        // own fetch pulls them in, and they must read as "no attestation".
1674        //
1675        // BOTH keys, because an attestation is now findable by the tree as
1676        // well as by the commit. Forging one and leaving the other is not a
1677        // forgery — it is a genuine signed note the attacker failed to
1678        // reach, and covered is right to honour it. The test said "a foreign
1679        // note is not a stamp" and has to forge every place a note lives to
1680        // mean that.
1681        let head_tree = git(&work, &["rev-parse", "HEAD^{tree}"]);
1682        for object in [&head, &head_tree] {
1683            git(
1684                &work,
1685                &[
1686                    "notes", "--ref", NOTES_REF, "add", "-f", "-m", "garbage", object,
1687                ],
1688            );
1689        }
1690        git(
1691            &work,
1692            &[
1693                "push",
1694                "-q",
1695                "origin",
1696                &format!("+{NOTES_FULL_REF}:{NOTES_FULL_REF}"),
1697            ],
1698        );
1699        // The genuine block is also filed under the canonical tree's key in
1700        // the inputs ref, which attest's verifier reads (the frozen copy here
1701        // never did): every place a note lives includes that ref.
1702        git(
1703            &work,
1704            &["push", "-q", "origin", &format!(":{INPUTS_FULL_REF}")],
1705        );
1706        git(&clone, &["reset", "-q", "--hard", &head]);
1707        in_repo(&clone, || {
1708            assert_eq!(
1709                covered(&signers, Some("t@t.test"), None, &[]),
1710                None,
1711                "a foreign note is not a stamp"
1712            );
1713        });
1714        let _ = std::fs::remove_dir_all(&d);
1715        let _ = std::fs::remove_dir_all(&work);
1716    }
1717
1718    /// The silent-death case: a workflow step running with a
1719    /// `working-directory` inside the repo must still find the committed
1720    /// signers file. Before this, `default_signers` looked relative to the
1721    /// cwd, found nothing, and every such repo fail-opened forever with no
1722    /// symptom — CI stayed green and the gate simply never fired.
1723    #[test]
1724    fn default_signers_is_found_from_a_subdirectory() {
1725        let work = repo("signers-subdir");
1726        std::fs::create_dir_all(work.join(".forgejo")).unwrap();
1727        std::fs::write(work.join(".forgejo/allowed_signers"), "t@t.test x\n").unwrap();
1728        let sub = work.join("packages").join("thing");
1729        std::fs::create_dir_all(&sub).unwrap();
1730        in_repo(&sub, || {
1731            let found = default_signers().expect("resolved from the repo root, not the cwd");
1732            assert!(found.ends_with(".forgejo/allowed_signers"));
1733            assert!(found.exists(), "the path it returns must be usable as-is");
1734        });
1735        let _ = std::fs::remove_dir_all(&work);
1736    }
1737
1738    #[test]
1739    fn zero_oids_of_any_width_are_zero() {
1740        assert!(is_zero(&"0".repeat(40)));
1741        assert!(is_zero(&"0".repeat(64)));
1742        assert!(!is_zero("0a0000"));
1743        assert!(!is_zero(""));
1744    }
1745
1746    #[test]
1747    fn forget_removes_the_local_ref() {
1748        let work = repo("forget");
1749        std::fs::write(work.join("a.ts"), "x").unwrap();
1750        git(&work, &["add", "a.ts"]);
1751        git(&work, &["commit", "-qm", "chore: a"]);
1752        git(
1753            &work,
1754            &["notes", "--ref", NOTES_REF, "add", "-m", "x", "HEAD"],
1755        );
1756        in_repo(&work, forget);
1757        assert!(git(&work, &["notes", "--ref", NOTES_REF, "list"]).is_empty());
1758        let _ = std::fs::remove_dir_all(&work);
1759    }
1760
1761    // --- attest 1.4.0 parity: optional paths --------------------------------
1762
1763    // --- attest 1.4.0 parity: the notes ref is origin's mirror --------------
1764
1765    // Both name sets (decisions ADR-0068): a signer block's header picks the
1766    // set and the namespace its signature is checked under follows, never
1767    // the other set's.
1768
1769    /// A key the signers file lists, bound to the cluster's platform, under
1770    /// BOTH namespaces: a refusal below comes from the header-to-namespace
1771    /// binding, not from the signers file.
1772    pub(crate) fn both_names_signer(dir: &Path) -> (PathBuf, PathBuf) {
1773        let key = dir.join("signer_key");
1774        let ok = std::process::Command::new("ssh-keygen")
1775            .args(["-q", "-t", "ed25519", "-N", "", "-C", "test", "-f"])
1776            .arg(&key)
1777            .status()
1778            .expect("ssh-keygen must exist for these tests")
1779            .success();
1780        assert!(ok, "keygen failed");
1781        let pubkey = std::fs::read_to_string(key.with_extension("pub")).unwrap();
1782        let signers = dir.join("allowed_signers");
1783        std::fs::write(
1784            &signers,
1785            format!(
1786                "cluster-signer@{} namespaces=\"{},{}\" {pubkey}",
1787                crate::cluster::PLATFORM,
1788                git_attest::format::LEGACY.namespace,
1789                git_attest::format::GREEN.namespace
1790            ),
1791        )
1792        .unwrap();
1793        (key, signers)
1794    }
1795
1796    /// One block whose payload starts with `header`, signed under `namespace`.
1797    pub(crate) fn block_with(header: &str, namespace: &str, tree: &str, key: &Path) -> String {
1798        let payload = format!(
1799            "{header}\ntree {tree}\ngates suite\nplatform {}\ngreengate 0.0.0\n",
1800            crate::cluster::PLATFORM
1801        );
1802        let sig = git_attest::sign::sign(namespace, &payload, key).expect("sign");
1803        block(&payload, &sig)
1804    }
1805
1806    #[test]
1807    fn a_signer_block_is_checked_under_the_namespace_its_header_names() {
1808        use git_attest::format::{GREEN, LEGACY};
1809        let scratch = dir("signer-names");
1810        let (key, signers) = both_names_signer(&scratch);
1811        let tree = "0123456789012345678901234567890123456789";
1812        for set in [GREEN, LEGACY] {
1813            let body = block_with(set.format, set.namespace, tree, &key);
1814            let checked = signer_block(&body, tree, &signers)
1815                .unwrap_or_else(|e| panic!("{}: {}", set.format, e.reason()));
1816            assert_eq!(checked.names, set);
1817            assert_eq!(checked.gates, ["suite"]);
1818        }
1819        for (header, signed_under) in [(LEGACY, GREEN), (GREEN, LEGACY)] {
1820            let body = block_with(header.format, signed_under.namespace, tree, &key);
1821            assert!(
1822                matches!(
1823                    signer_block(&body, tree, &signers),
1824                    Err(BlockRefusal::Signer(_))
1825                ),
1826                "a {} block signed under {} must be refused",
1827                header.format,
1828                signed_under.namespace
1829            );
1830        }
1831        let _ = std::fs::remove_dir_all(&scratch); // best-effort temp cleanup; a leftover dir cannot change the verdict
1832    }
1833
1834    #[test]
1835    fn forget_in_removes_the_notes_ref_of_both_name_sets() {
1836        let repo_dir = repo("forget-both");
1837        git(&repo_dir, &["commit", "-q", "--allow-empty", "-m", "c"]);
1838        for names in READ_NAMES {
1839            git(
1840                &repo_dir,
1841                &["notes", "--ref", names.notes_ref, "add", "-m", "x", "HEAD"],
1842            );
1843        }
1844        assert!(forget_in(&repo_dir));
1845        for names in READ_NAMES {
1846            let full = format!("refs/notes/{}", names.notes_ref);
1847            let out = std::process::Command::new("git")
1848                .arg("-C")
1849                .arg(&repo_dir)
1850                .args(["rev-parse", "--verify", "-q", &full])
1851                .output()
1852                .unwrap();
1853            assert!(!out.status.success(), "{full} survived forget_in");
1854        }
1855        let _ = std::fs::remove_dir_all(&repo_dir); // best-effort temp cleanup; a leftover dir cannot change the verdict
1856    }
1857
1858    // holds-until: Phase 4 flips `WRITE` to `GREEN`; this test then swaps the sets.
1859    #[test]
1860    fn filed_signer_blocks_drops_a_block_of_the_other_name_set() {
1861        use git_attest::format::{GREEN, LEGACY};
1862        let work = repo("filed-names");
1863        std::fs::write(work.join("a.txt"), "x").unwrap();
1864        git(&work, &["add", "a.txt"]);
1865        git(&work, &["commit", "-qm", "chore: a"]);
1866        let (key, signers) = both_names_signer(&work);
1867        std::fs::create_dir_all(work.join(".forgejo")).unwrap();
1868        std::fs::copy(&signers, work.join(".forgejo/allowed_signers")).unwrap();
1869        let tree = git(&work, &["rev-parse", "HEAD^{tree}"]);
1870        let green = block_with(GREEN.format, GREEN.namespace, &tree, &key);
1871        let legacy = block_with(LEGACY.format, LEGACY.namespace, &tree, &key);
1872        in_repo(&work, || {
1873            file_signer_block(&green, &[&tree]).expect("file the green block");
1874            assert!(
1875                filed_signer_blocks(&tree).is_empty(),
1876                "a green block is not publishable while WRITE is legacy"
1877            );
1878            file_signer_block(&format!("{green}\n{legacy}"), &[&tree]).expect("file both");
1879            let kept = filed_signer_blocks(&tree);
1880            assert_eq!(kept.len(), 1, "{kept:?}");
1881            assert_eq!(kept[0].names, git_attest::format::WRITE);
1882            assert!(kept[0].is_publishable());
1883        });
1884        let _ = std::fs::remove_dir_all(&work); // best-effort temp cleanup; a leftover dir cannot change the verdict
1885    }
1886
1887    #[test]
1888    fn a_verification_says_which_name_it_went_through() {
1889        let mut verdict = git_attest::verify::Verdict::nothing("test");
1890        assert!(verified_lines(&verdict).is_empty());
1891        verdict.verified_under = vec![
1892            git_attest::format::GREEN.namespace.to_string(),
1893            git_attest::format::LEGACY.namespace.to_string(),
1894        ];
1895        assert_eq!(
1896            verified_lines(&verdict),
1897            [
1898                format!("verified under {}", git_attest::format::GREEN.namespace),
1899                format!("verified under {}", git_attest::format::LEGACY.namespace),
1900            ]
1901        );
1902    }
1903}