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