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