Skip to main content

greengate_runtime/
attest.rs

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