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