Skip to main content

greengate_runtime/
attest.rs

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