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 = "AMONT_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 = "amont.attest";
75
76/// Where the signing key lives when the repository does not say.
77const KEY_CONFIG: &str = "amont.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: `amont.attestKey`, else `~/.ssh/amont-attest`.
91///
92/// Read like `amont.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    /// `amont.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", "amont.attest", "true"]);
718        git(&work, &["config", "amont.attestKey", key.to_str().unwrap()]);
719        std::fs::write(work.join("a.ts"), "x").unwrap();
720        git(&work, &["add", "a.ts"]);
721        git(&work, &["commit", "-qm", "chore: a"]);
722        (d, work, remote, signers)
723    }
724
725    fn push_ref_for(work: &Path) -> PushRef {
726        PushRef {
727            local_ref: "refs/heads/main".into(),
728            local_oid: git(work, &["rev-parse", "HEAD"]),
729            remote_ref: "refs/heads/main".into(),
730            remote_oid: "0".repeat(40),
731        }
732    }
733
734    #[test]
735    fn the_provenance_dir_is_resolved_like_amont_agents_config_dir() {
736        use std::ffi::OsString;
737        let env = |pairs: &'static [(&'static str, &'static str)]| {
738            move |k: &str| {
739                pairs
740                    .iter()
741                    .find(|(n, _)| *n == k)
742                    .map(|(_, v)| OsString::from(v))
743            }
744        };
745        assert_eq!(
746            provenance_dir(env(&[("CLAUDE_CONFIG_DIR", "/c"), ("HOME", "/h")])),
747            Some(PathBuf::from("/c/amont-agent/provenance"))
748        );
749        assert_eq!(
750            provenance_dir(env(&[("HOME", "/h"), ("USERPROFILE", "/u")])),
751            Some(PathBuf::from("/h/.claude/amont-agent/provenance"))
752        );
753        assert_eq!(
754            provenance_dir(env(&[("USERPROFILE", "/u")])),
755            Some(PathBuf::from("/u/.claude/amont-agent/provenance"))
756        );
757        assert_eq!(provenance_dir(env(&[])), None);
758    }
759
760    /// A repository with a bare origin, the toggle on and a key; one commit
761    /// that carries a plan. Returns (scratch, work, remote, head, tree,
762    /// signers).
763    fn provenance_world(name: &str) -> (PathBuf, PathBuf, PathBuf, String, String, PathBuf) {
764        provenance_world_in(name, None)
765    }
766
767    /// [`provenance_world`] in a repository of `object_format`.
768    fn provenance_world_in(
769        name: &str,
770        object_format: Option<&str>,
771    ) -> (PathBuf, PathBuf, PathBuf, String, String, PathBuf) {
772        let d = dir(name);
773        let (key, _) = keypair(&d);
774        let pubkey = std::fs::read_to_string(key.with_extension("pub")).unwrap();
775        let signers = d.join("allowed_signers_provenance");
776        std::fs::write(
777            &signers,
778            format!("t@t.test namespaces=\"{NAMESPACE},{PROVENANCE_NAMESPACE}\" {pubkey}"),
779        )
780        .unwrap();
781        let remote = d.join("remote.git");
782        std::fs::create_dir_all(&remote).unwrap();
783        let fmt = format!("--object-format={}", object_format.unwrap_or("sha1"));
784        git(&remote, &["init", "-q", "--bare", "--template=", &fmt, "."]);
785        let work = match object_format {
786            None => repo(&format!("{name}-work")),
787            Some(f) => {
788                let w = dir(&format!("{name}-work"));
789                let fmt = format!("--object-format={f}");
790                git(&w, &["init", "-q", "--template=", &fmt, "."]);
791                git(&w, &["config", "user.email", "t@t.test"]);
792                git(&w, &["config", "user.name", "t"]);
793                w
794            }
795        };
796        git(
797            &work,
798            &["remote", "add", "origin", remote.to_str().unwrap()],
799        );
800        git(&work, &["config", "amont.attest", "true"]);
801        git(&work, &["config", "amont.attestKey", key.to_str().unwrap()]);
802        std::fs::write(work.join("README.md"), "words").unwrap();
803        std::fs::create_dir_all(work.join("docs/plans")).unwrap();
804        std::fs::write(work.join("docs/plans/p.md"), "# P\n").unwrap();
805        git(&work, &["add", "README.md", "docs/plans/p.md"]);
806        git(&work, &["commit", "-qm", "docs: words"]);
807        let head = git(&work, &["rev-parse", "HEAD"]);
808        let tree = git(&work, &["rev-parse", "HEAD^{tree}"]);
809        (d, work, remote, head, tree, signers)
810    }
811
812    fn record(head: &str, tree: &str) -> String {
813        format!(
814            "{PROVENANCE_FORMAT}\ncommit {head}\ntree {tree}\n\
815             plan docs/plans/p.md {}\nreview reviewed {}\npreview not-required\n\
816             producer amont-agent 0.0.0\n",
817            "a".repeat(64),
818            "c".repeat(64)
819        )
820    }
821
822    /// canon(T) as attest SPEC defines it, by hand and independent of
823    /// `attest_inputs`: the quoted listing, the oid of every regular file
824    /// under the top-level `docs/plans/` zeroed, through `git hash-object`.
825    fn canon_by_hand(work: &Path, tree: &str) -> String {
826        let listing = git(
827            work,
828            &[
829                "-c",
830                "core.quotePath=true",
831                "ls-tree",
832                "-r",
833                "--full-tree",
834                tree,
835            ],
836        );
837        let mut text = String::new();
838        for line in listing.lines() {
839            let (head, path) = line.split_once('\t').unwrap();
840            let f: Vec<&str> = head.split(' ').collect();
841            let plan = matches!(f[0], "100644" | "100755")
842                && (path.starts_with("docs/plans/") || path.starts_with("\"docs/plans/"));
843            if plan {
844                text.push_str(&format!(
845                    "{} {} {}\t{path}\n",
846                    f[0],
847                    f[1],
848                    "0".repeat(f[2].len())
849                ));
850            } else {
851                text.push_str(&format!("{line}\n"));
852            }
853        }
854        let mut child = std::process::Command::new("git")
855            .arg("-C")
856            .arg(work)
857            .args(["hash-object", "--stdin"])
858            .stdin(Stdio::piped())
859            .stdout(Stdio::piped())
860            .spawn()
861            .unwrap();
862        child
863            .stdin
864            .take()
865            .unwrap()
866            .write_all(text.as_bytes())
867            .unwrap();
868        let out = child.wait_with_output().unwrap();
869        String::from_utf8_lossy(&out.stdout).trim().to_string()
870    }
871
872    /// The signed payload of `object` in the remote's provenance ref.
873    fn provenance_payload(remote: &Path, object: &str) -> (String, String) {
874        let note = git(remote, &["notes", "--ref", PROVENANCE_REF, "show", object]);
875        let (p, sig) = note
876            .split_once("\n\n")
877            .expect("payload, blank line, signature");
878        (format!("{p}\n"), sig.to_string())
879    }
880
881    fn push_of(head: &str) -> PushRef {
882        PushRef {
883            local_ref: "refs/heads/feat/x".into(),
884            local_oid: head.to_string(),
885            remote_ref: "refs/heads/feat/x".into(),
886            remote_oid: "0".repeat(40),
887        }
888    }
889
890    /// A payload left by amont-agent reaches the remote as a note on both
891    /// the tree and the commit, verifies under its own namespace only, and
892    /// leaves the attestation ref alone. The file is gone once published.
893    #[test]
894    fn a_provenance_payload_is_signed_and_published_by_tree_and_commit() {
895        let (d, work, remote, head, tree, signers) = provenance_world("prov-e2e");
896        let payloads = d.join("payloads");
897        std::fs::create_dir_all(&payloads).unwrap();
898        let file = payloads.join(&head);
899        let body = record(&head, &tree);
900        std::fs::write(&file, &body).unwrap();
901        let gates = ["pre-push-cargo-test".to_string()];
902        in_repo(&work, || {
903            attest_push(&test_settings(), "origin", &[push_of(&head)], &gates, &[])
904        });
905        let attested = git(&remote, &["notes", "--ref", NOTES_REF, "show", &head]);
906        in_repo(&work, || {
907            provenance_push_from(&payloads, "origin", &[push_of(&head)])
908        });
909        // The signer inserts canon(T) right after `tree`; everything else is
910        // amont-agent's payload byte for byte.
911        let canon = canon_by_hand(&work, &tree);
912        assert_ne!(
913            canon, tree,
914            "the tree carries a plan, so canon(T) is not its oid"
915        );
916        let signed = body.replacen(
917            &format!("tree {tree}\n"),
918            &format!("tree {tree}\ncanon {canon}\n"),
919            1,
920        );
921        for object in [&head, &tree] {
922            let (p, sig) = provenance_payload(&remote, object);
923            assert_eq!(p, signed, "the payload, with canon(T) inserted, is signed");
924            assert_eq!(p.lines().nth(3), Some(format!("canon {canon}").as_str()));
925            assert!(verify_in(
926                PROVENANCE_NAMESPACE,
927                &p,
928                &sig,
929                &signers,
930                "t@t.test"
931            ));
932            assert!(
933                !verify_in(NAMESPACE, &p, &sig, &signers, "t@t.test"),
934                "a provenance signature is never an attestation"
935            );
936        }
937        assert!(!file.exists(), "a published payload is deleted");
938        assert_eq!(
939            git(&remote, &["notes", "--ref", NOTES_REF, "show", &head]),
940            attested,
941            "the attestation note is byte-identical with a provenance payload present"
942        );
943        let _ = std::fs::remove_dir_all(&d);
944        let _ = std::fs::remove_dir_all(&work);
945    }
946
947    #[test]
948    fn a_payload_for_another_tree_is_neither_signed_nor_deleted() {
949        let (d, work, remote, head, _tree, _) = provenance_world("prov-mismatch");
950        let payloads = d.join("payloads");
951        std::fs::create_dir_all(&payloads).unwrap();
952        let file = payloads.join(&head);
953        std::fs::write(&file, record(&head, &"b".repeat(40))).unwrap();
954        in_repo(&work, || {
955            provenance_push_from(&payloads, "origin", &[push_of(&head)])
956        });
957        assert!(file.exists(), "a mismatched payload is kept");
958        let refs = git(&remote, &["for-each-ref", PROVENANCE_FULL_REF]);
959        assert!(refs.is_empty(), "nothing was published: {refs}");
960        let _ = std::fs::remove_dir_all(&d);
961        let _ = std::fs::remove_dir_all(&work);
962    }
963
964    /// A payload that already states a canonical tree was written by a
965    /// pre-release amont-agent: it is refused, never signed, never removed.
966    #[test]
967    fn a_payload_with_a_canon_line_is_refused_and_kept() {
968        let (d, work, remote, head, tree, _) = provenance_world("prov-canon");
969        let payloads = d.join("payloads");
970        std::fs::create_dir_all(&payloads).unwrap();
971        let file = payloads.join(&head);
972        let old = record(&head, &tree).replacen(
973            &format!("tree {tree}\n"),
974            &format!("tree {tree}\ncanon {}\n", "c".repeat(64)),
975            1,
976        );
977        std::fs::write(&file, &old).unwrap();
978        in_repo(&work, || {
979            provenance_push_from(&payloads, "origin", &[push_of(&head)])
980        });
981        assert_eq!(
982            std::fs::read_to_string(&file).unwrap(),
983            old,
984            "kept as it was"
985        );
986        let refs = git(&remote, &["for-each-ref", PROVENANCE_FULL_REF]);
987        assert!(refs.is_empty(), "nothing was published: {refs}");
988        let _ = std::fs::remove_dir_all(&d);
989        let _ = std::fs::remove_dir_all(&work);
990    }
991
992    /// The refusal names the reason, the file and the fix, in lines of at
993    /// most 80 columns for a usual path, a sha256 commit included.
994    #[test]
995    fn the_canon_refusal_fits_in_80_columns() {
996        for commit in [
997            "9f1c2ab0d6e4c1b2a3f405e6d7c8b9a0f1e2d3c4".to_string(),
998            "e".repeat(64),
999        ] {
1000            let file = PathBuf::from("/Users/someone/.claude/amont-agent/provenance/amont-agent")
1001                .join(&commit);
1002            let lines = canon_refusal(&commit, &file);
1003            assert!(lines[0].starts_with("  provenance for "), "{lines:?}");
1004            assert!(lines[0].contains(&commit[..7]), "{lines:?}");
1005            let all = lines.join("\n");
1006            assert!(all.contains("canon line") && all.contains("pre-release amont-agent"));
1007            assert!(all.contains(&format!("    {commit} in\n")), "{all}");
1008            assert!(all.contains("upgrade amont-agent"), "{all}");
1009            for l in &lines {
1010                assert!(
1011                    l.chars().count() <= 80,
1012                    "{} columns: {l}",
1013                    l.chars().count()
1014                );
1015            }
1016        }
1017    }
1018
1019    /// No canon(T), no signature: the payload waits for the next push.
1020    #[test]
1021    fn a_failed_canon_keeps_the_payload() {
1022        let (d, work, remote, head, tree, _) = provenance_world("prov-nocanon");
1023        // The commit and its tree still resolve; listing the tree does not.
1024        let docs = git(&work, &["rev-parse", &format!("{tree}:docs")]);
1025        let objects = PathBuf::from(git(&work, &["rev-parse", "--git-path", "objects"]));
1026        let objects = if objects.is_absolute() {
1027            objects
1028        } else {
1029            work.join(objects)
1030        };
1031        std::fs::remove_file(objects.join(&docs[..2]).join(&docs[2..])).unwrap();
1032        let payloads = d.join("payloads");
1033        std::fs::create_dir_all(&payloads).unwrap();
1034        let file = payloads.join(&head);
1035        std::fs::write(&file, record(&head, &tree)).unwrap();
1036        in_repo(&work, || {
1037            assert_eq!(canon(&tree), None);
1038            provenance_push_from(&payloads, "origin", &[push_of(&head)])
1039        });
1040        assert!(file.exists(), "a payload without a canon is kept");
1041        let refs = git(&remote, &["for-each-ref", PROVENANCE_FULL_REF]);
1042        assert!(refs.is_empty(), "nothing was published: {refs}");
1043        let _ = std::fs::remove_dir_all(&d);
1044        let _ = std::fs::remove_dir_all(&work);
1045    }
1046
1047    /// The hook's cwd is the worktree, so canon(T) is of the repository's own
1048    /// object format: 64 hex in a sha256 repository.
1049    #[test]
1050    fn a_sha256_repository_signs_a_64_hex_canon() {
1051        let (d, work, remote, head, tree, _) = provenance_world_in("prov-sha256", Some("sha256"));
1052        assert_eq!(tree.len(), 64);
1053        let payloads = d.join("payloads");
1054        std::fs::create_dir_all(&payloads).unwrap();
1055        std::fs::write(payloads.join(&head), record(&head, &tree)).unwrap();
1056        in_repo(&work, || {
1057            provenance_push_from(&payloads, "origin", &[push_of(&head)])
1058        });
1059        let (p, _) = provenance_payload(&remote, &head);
1060        let canon = canon_by_hand(&work, &tree);
1061        assert_eq!(canon.len(), 64);
1062        assert_eq!(
1063            p.lines().nth(3),
1064            Some(format!("canon {canon}").as_str()),
1065            "{p}"
1066        );
1067        let _ = std::fs::remove_dir_all(&d);
1068        let _ = std::fs::remove_dir_all(&work);
1069    }
1070
1071    #[test]
1072    fn a_failed_publish_keeps_the_payload_for_the_next_push() {
1073        let (d, work, _remote, head, tree, _) = provenance_world("prov-fail");
1074        git(
1075            &work,
1076            &[
1077                "remote",
1078                "set-url",
1079                "origin",
1080                d.join("gone.git").to_str().unwrap(),
1081            ],
1082        );
1083        let payloads = d.join("payloads");
1084        std::fs::create_dir_all(&payloads).unwrap();
1085        let file = payloads.join(&head);
1086        std::fs::write(&file, record(&head, &tree)).unwrap();
1087        in_repo(&work, || {
1088            provenance_push_from(&payloads, "origin", &[push_of(&head)])
1089        });
1090        assert!(file.exists(), "an unpublished payload is kept");
1091        let _ = std::fs::remove_dir_all(&d);
1092        let _ = std::fs::remove_dir_all(&work);
1093    }
1094
1095    /// The payload directory comes from the environment only: a git config
1096    /// key naming a directory full of payloads is never read.
1097    #[test]
1098    fn a_config_key_cannot_point_amont_at_other_payloads() {
1099        let (d, work, remote, head, tree, _) = provenance_world("prov-config");
1100        let elsewhere = d.join("elsewhere");
1101        let name = work.file_name().unwrap().to_string_lossy().into_owned();
1102        std::fs::create_dir_all(elsewhere.join(&name)).unwrap();
1103        std::fs::write(elsewhere.join(&name).join(&head), record(&head, &tree)).unwrap();
1104        for key in ["amont.provenanceDir", "amont.agent.provenanceDir"] {
1105            git(&work, &["config", key, elsewhere.to_str().unwrap()]);
1106        }
1107        in_repo(&work, || {
1108            provenance_push(&test_settings(), "origin", &[push_of(&head)])
1109        });
1110        let refs = git(&remote, &["for-each-ref", PROVENANCE_FULL_REF]);
1111        assert!(refs.is_empty(), "a configured directory was read: {refs}");
1112        let _ = std::fs::remove_dir_all(&d);
1113        let _ = std::fs::remove_dir_all(&work);
1114    }
1115
1116    #[test]
1117    fn no_payload_publishes_nothing() {
1118        let (d, work, remote, head, _, _) = provenance_world("prov-none");
1119        let payloads = d.join("payloads");
1120        std::fs::create_dir_all(&payloads).unwrap();
1121        in_repo(&work, || {
1122            provenance_push_from(&payloads, "origin", &[push_of(&head)])
1123        });
1124        let refs = git(&remote, &["for-each-ref", PROVENANCE_FULL_REF]);
1125        assert!(refs.is_empty(), "{refs}");
1126        let _ = std::fs::remove_dir_all(&d);
1127        let _ = std::fs::remove_dir_all(&work);
1128    }
1129
1130    #[test]
1131    fn a_missing_key_signs_nothing() {
1132        assert!(sign("anything", Path::new("/nonexistent/key")).is_none());
1133    }
1134
1135    /// The full journey: a repo with the toggle on pushes, and the BARE
1136    /// remote ends up holding a note whose payload verifies and matches the
1137    /// pushed tree. This is everything CI relies on, minus CI.
1138    #[test]
1139    fn an_enabled_push_leaves_a_verifiable_note_on_the_remote() {
1140        let d = dir("e2e");
1141        let (key, signers) = keypair(&d);
1142        let remote = d.join("remote.git");
1143        std::fs::create_dir_all(&remote).unwrap();
1144        git(&remote, &["init", "-q", "--bare", "--template=", "."]);
1145        let work = repo("e2e-work");
1146        git(
1147            &work,
1148            &["remote", "add", "origin", remote.to_str().unwrap()],
1149        );
1150        git(&work, &["config", "amont.attest", "true"]);
1151        git(&work, &["config", "amont.attestKey", key.to_str().unwrap()]);
1152        std::fs::write(work.join("a.ts"), "x").unwrap();
1153        git(&work, &["add", "a.ts"]);
1154        git(&work, &["commit", "-qm", "chore: a"]);
1155        let head = git(&work, &["rev-parse", "HEAD"]);
1156        let tree = git(&work, &["rev-parse", "HEAD^{tree}"]);
1157        let push_ref = PushRef {
1158            local_ref: "refs/heads/main".into(),
1159            local_oid: head.clone(),
1160            remote_ref: "refs/heads/main".into(),
1161            remote_oid: "0".repeat(40),
1162        };
1163        in_repo(&work, || {
1164            attest_push(
1165                &test_settings(),
1166                "origin",
1167                &[push_ref],
1168                &["pre-push-run-tests-js".into()],
1169                &[],
1170            );
1171        });
1172        // The note exists on the REMOTE — the whole point is that it travels.
1173        let body = git(&remote, &["notes", "--ref", NOTES_REF, "show", &head]);
1174        assert!(!body.is_empty(), "no note reached the remote");
1175        let (p, sig) = body
1176            .split_once("\n\n")
1177            .expect("payload, blank line, signature");
1178        let p = format!("{p}\n"); // the blank-line split ate payload's trailing newline
1179        assert!(p.starts_with(FORMAT));
1180        assert!(
1181            p.contains(&format!("tree {tree}")),
1182            "attests the pushed tree"
1183        );
1184        assert!(
1185            verify(&p, sig, &signers, "t@t.test"),
1186            "the remote copy verifies"
1187        );
1188        let _ = std::fs::remove_dir_all(&d);
1189        let _ = std::fs::remove_dir_all(&work);
1190    }
1191
1192    /// Off by default: a repo that never opted in makes no statement, even
1193    /// with everything else in place.
1194    /// amont's half of input fingerprints: a push from a repository with a
1195    /// spec publishes the inputs ref too, and counts what it filed. What
1196    /// the block says (the `input` lines, the fingerprint, the key) is
1197    /// attest's, tested there (decisions ADR-0037).
1198    #[test]
1199    fn a_push_with_a_spec_publishes_the_inputs_ref() {
1200        let (_d, work, remote, _) = remote_and_work("inputs");
1201        std::fs::create_dir_all(work.join(".github")).unwrap();
1202        std::fs::write(
1203            work.join(".github/attest-inputs"),
1204            "pre-push-run-tests-js a.ts\n",
1205        )
1206        .unwrap();
1207        git(&work, &["add", ".github/attest-inputs"]);
1208        git(&work, &["commit", "-qm", "chore: spec"]);
1209        in_repo(&work, || {
1210            attest_push(
1211                &test_settings(),
1212                "origin",
1213                &[push_ref_for(&work)],
1214                &["pre-push-run-tests-js".into()],
1215                &[],
1216            );
1217        });
1218        let listed = git(&remote, &["notes", "--ref", INPUTS_REF, "list"]);
1219        // How many keys (the input's, the canonical tree's) is attest's.
1220        assert!(
1221            !listed.trim().is_empty(),
1222            "the inputs ref reached the remote"
1223        );
1224    }
1225
1226    #[test]
1227    fn no_opt_in_means_no_note() {
1228        let d = dir("optout");
1229        let (key, _) = keypair(&d);
1230        let remote = d.join("remote.git");
1231        std::fs::create_dir_all(&remote).unwrap();
1232        git(&remote, &["init", "-q", "--bare", "--template=", "."]);
1233        let work = repo("optout-work");
1234        git(
1235            &work,
1236            &["remote", "add", "origin", remote.to_str().unwrap()],
1237        );
1238        git(&work, &["config", "amont.attestKey", key.to_str().unwrap()]);
1239        std::fs::write(work.join("a.ts"), "x").unwrap();
1240        git(&work, &["add", "a.ts"]);
1241        git(&work, &["commit", "-qm", "chore: a"]);
1242        let head = git(&work, &["rev-parse", "HEAD"]);
1243        let push_ref = PushRef {
1244            local_ref: "refs/heads/main".into(),
1245            local_oid: head.clone(),
1246            remote_ref: "refs/heads/main".into(),
1247            remote_oid: "0".repeat(40),
1248        };
1249        in_repo(&work, || {
1250            attest_push(
1251                &test_settings(),
1252                "origin",
1253                &[push_ref],
1254                &["pre-push-run-tests-js".into()],
1255                &[],
1256            );
1257        });
1258        assert!(
1259            git(&remote, &["notes", "--ref", NOTES_REF, "list"]).is_empty(),
1260            "an un-opted-in repo attested something"
1261        );
1262        let _ = std::fs::remove_dir_all(&d);
1263        let _ = std::fs::remove_dir_all(&work);
1264    }
1265
1266    /// A deletion pushes no code; an empty gate list says nothing. Neither
1267    /// may produce a note even in an enabled repo.
1268    #[test]
1269    fn deletions_and_empty_gates_attest_nothing() {
1270        let d = dir("nothing");
1271        let (key, _) = keypair(&d);
1272        let remote = d.join("remote.git");
1273        std::fs::create_dir_all(&remote).unwrap();
1274        git(&remote, &["init", "-q", "--bare", "--template=", "."]);
1275        let work = repo("nothing-work");
1276        git(
1277            &work,
1278            &["remote", "add", "origin", remote.to_str().unwrap()],
1279        );
1280        git(&work, &["config", "amont.attest", "true"]);
1281        git(&work, &["config", "amont.attestKey", key.to_str().unwrap()]);
1282        std::fs::write(work.join("a.ts"), "x").unwrap();
1283        git(&work, &["add", "a.ts"]);
1284        git(&work, &["commit", "-qm", "chore: a"]);
1285        let head = git(&work, &["rev-parse", "HEAD"]);
1286        let deletion = PushRef {
1287            local_ref: "(delete)".into(),
1288            local_oid: "0".repeat(40),
1289            remote_ref: "refs/heads/gone".into(),
1290            remote_oid: head.clone(),
1291        };
1292        let real = PushRef {
1293            local_ref: "refs/heads/main".into(),
1294            local_oid: head,
1295            remote_ref: "refs/heads/main".into(),
1296            remote_oid: "0".repeat(40),
1297        };
1298        in_repo(&work, || {
1299            attest_push(
1300                &test_settings(),
1301                "origin",
1302                &[deletion],
1303                &["pre-push-pytest".into()],
1304                &[],
1305            );
1306            attest_push(&test_settings(), "origin", &[real], &[], &[]);
1307        });
1308        assert!(git(&remote, &["notes", "--ref", NOTES_REF, "list"]).is_empty());
1309        let _ = std::fs::remove_dir_all(&d);
1310        let _ = std::fs::remove_dir_all(&work);
1311    }
1312
1313    /// The half CI actually calls, from CI's own vantage point: a fresh
1314    /// clone. `covered` fetches the notes ref itself, verifies, and answers
1315    /// with the gates — then stops answering the moment the tree drifts or
1316    /// the note is replaced by something unsigned.
1317    /// Only a signature that did not verify counts as a rejection (amont#271);
1318    /// a note with no signature, or a tree that moved, does not.
1319    #[test]
1320    fn a_rejection_is_a_note_whose_signature_did_not_verify() {
1321        let trail: Vec<String> = [
1322            "note on abc123: signature did not verify for principal t@t.test",
1323            "note on abc123 block 2: no principal matched",
1324            "note on def456 carries no signature block",
1325            "attested tree abc is not the checked-out tree def and neither its canonical tree nor an input fingerprint of abc123 matches",
1326            "no attestation found for tree abc",
1327        ]
1328        .iter()
1329        .map(|s| s.to_string())
1330        .collect();
1331        assert_eq!(
1332            signature_rejections(&trail),
1333            vec![
1334                "note on abc123: signature did not verify for principal t@t.test".to_string(),
1335                "note on abc123 block 2: no principal matched".to_string(),
1336            ]
1337        );
1338    }
1339
1340    #[test]
1341    fn covered_answers_in_a_fresh_clone_and_rejects_drift_and_forgery() {
1342        let d = dir("covered");
1343        let (key, signers) = keypair(&d);
1344        let remote = d.join("remote.git");
1345        std::fs::create_dir_all(&remote).unwrap();
1346        git(&remote, &["init", "-q", "--bare", "--template=", "."]);
1347        // The fixture pushes to `main`; a bare init on a machine whose
1348        // init.defaultBranch is the historical default leaves HEAD on
1349        // `master`, and a clone of that repository checks out NOTHING —
1350        // `covered` then answers None with a perfectly good note sitting in
1351        // the ref. Caught only in CI: dev machines set main globally.
1352        git(&remote, &["symbolic-ref", "HEAD", "refs/heads/main"]);
1353        let work = repo("covered-work");
1354        git(
1355            &work,
1356            &["remote", "add", "origin", remote.to_str().unwrap()],
1357        );
1358        git(&work, &["config", "amont.attest", "true"]);
1359        git(&work, &["config", "amont.attestKey", key.to_str().unwrap()]);
1360        std::fs::write(work.join("a.ts"), "x").unwrap();
1361        git(&work, &["add", "a.ts"]);
1362        git(&work, &["commit", "-qm", "chore: a"]);
1363        git(&work, &["push", "-q", "origin", "HEAD:main"]);
1364        let head = git(&work, &["rev-parse", "HEAD"]);
1365        let push_ref = PushRef {
1366            local_ref: "refs/heads/main".into(),
1367            local_oid: head.clone(),
1368            remote_ref: "refs/heads/main".into(),
1369            remote_oid: "0".repeat(40),
1370        };
1371        in_repo(&work, || {
1372            attest_push(
1373                &test_settings(),
1374                "origin",
1375                &[push_ref],
1376                &["pre-push-pytest".into()],
1377                &[],
1378            );
1379        });
1380        let clone = d.join("ci-checkout");
1381        git(
1382            &d,
1383            &[
1384                "clone",
1385                "-q",
1386                "--template=",
1387                remote.to_str().unwrap(),
1388                clone.to_str().unwrap(),
1389            ],
1390        );
1391        in_repo(&clone, || {
1392            assert_eq!(
1393                covered(&signers, Some("t@t.test"), Some(&platform()), &[]).as_deref(),
1394                Some("pre-push-pytest"),
1395                "a fresh clone verifies the attestation and reads the gates"
1396            );
1397            assert_eq!(
1398                covered(&signers, Some("t@t.test"), None, &[]).as_deref(),
1399                Some("pre-push-pytest"),
1400                "`any` covers a platform-independent suite"
1401            );
1402            // The matrix case this exists for: another leg asking about a
1403            // suite that never ran there.
1404            assert_eq!(
1405                covered(&signers, Some("t@t.test"), Some("s390x-aix"), &[]),
1406                None,
1407                "a pass on one platform is not evidence about another"
1408            );
1409            assert_eq!(
1410                covered(&signers, Some("someone@else.test"), None, &[]),
1411                None,
1412                "an unlisted principal covers nothing"
1413            );
1414        });
1415        // Tree drift: a new commit in the checkout is not the attested tree.
1416        std::fs::write(clone.join("b.ts"), "y").unwrap();
1417        git(&clone, &["config", "user.email", "t@t.test"]);
1418        git(&clone, &["config", "user.name", "t"]);
1419        git(&clone, &["add", "b.ts"]);
1420        git(&clone, &["commit", "-qm", "chore: b"]);
1421        in_repo(&clone, || {
1422            assert_eq!(
1423                covered(&signers, Some("t@t.test"), None, &[]),
1424                None,
1425                "drifted tree"
1426            );
1427        });
1428        // Forgery: replace the remote's notes with unsigned ones. covered's
1429        // own fetch pulls them in, and they must read as "no attestation".
1430        //
1431        // BOTH keys, because an attestation is now findable by the tree as
1432        // well as by the commit. Forging one and leaving the other is not a
1433        // forgery — it is a genuine signed note the attacker failed to
1434        // reach, and covered is right to honour it. The test said "a foreign
1435        // note is not a stamp" and has to forge every place a note lives to
1436        // mean that.
1437        let head_tree = git(&work, &["rev-parse", "HEAD^{tree}"]);
1438        for object in [&head, &head_tree] {
1439            git(
1440                &work,
1441                &[
1442                    "notes", "--ref", NOTES_REF, "add", "-f", "-m", "garbage", object,
1443                ],
1444            );
1445        }
1446        git(
1447            &work,
1448            &[
1449                "push",
1450                "-q",
1451                "origin",
1452                &format!("+{NOTES_FULL_REF}:{NOTES_FULL_REF}"),
1453            ],
1454        );
1455        // The genuine block is also filed under the canonical tree's key in
1456        // the inputs ref, which attest's verifier reads (the frozen copy here
1457        // never did): every place a note lives includes that ref.
1458        git(
1459            &work,
1460            &["push", "-q", "origin", &format!(":{INPUTS_FULL_REF}")],
1461        );
1462        git(&clone, &["reset", "-q", "--hard", &head]);
1463        in_repo(&clone, || {
1464            assert_eq!(
1465                covered(&signers, Some("t@t.test"), None, &[]),
1466                None,
1467                "a foreign note is not a stamp"
1468            );
1469        });
1470        let _ = std::fs::remove_dir_all(&d);
1471        let _ = std::fs::remove_dir_all(&work);
1472    }
1473
1474    /// The silent-death case: a workflow step running with a
1475    /// `working-directory` inside the repo must still find the committed
1476    /// signers file. Before this, `default_signers` looked relative to the
1477    /// cwd, found nothing, and every such repo fail-opened forever with no
1478    /// symptom — CI stayed green and the gate simply never fired.
1479    #[test]
1480    fn default_signers_is_found_from_a_subdirectory() {
1481        let work = repo("signers-subdir");
1482        std::fs::create_dir_all(work.join(".forgejo")).unwrap();
1483        std::fs::write(work.join(".forgejo/allowed_signers"), "t@t.test x\n").unwrap();
1484        let sub = work.join("packages").join("thing");
1485        std::fs::create_dir_all(&sub).unwrap();
1486        in_repo(&sub, || {
1487            let found = default_signers().expect("resolved from the repo root, not the cwd");
1488            assert!(found.ends_with(".forgejo/allowed_signers"));
1489            assert!(found.exists(), "the path it returns must be usable as-is");
1490        });
1491        let _ = std::fs::remove_dir_all(&work);
1492    }
1493
1494    #[test]
1495    fn zero_oids_of_any_width_are_zero() {
1496        assert!(is_zero(&"0".repeat(40)));
1497        assert!(is_zero(&"0".repeat(64)));
1498        assert!(!is_zero("0a0000"));
1499        assert!(!is_zero(""));
1500    }
1501
1502    #[test]
1503    fn forget_removes_the_local_ref() {
1504        let work = repo("forget");
1505        std::fs::write(work.join("a.ts"), "x").unwrap();
1506        git(&work, &["add", "a.ts"]);
1507        git(&work, &["commit", "-qm", "chore: a"]);
1508        git(
1509            &work,
1510            &["notes", "--ref", NOTES_REF, "add", "-m", "x", "HEAD"],
1511        );
1512        in_repo(&work, forget);
1513        assert!(git(&work, &["notes", "--ref", NOTES_REF, "list"]).is_empty());
1514        let _ = std::fs::remove_dir_all(&work);
1515    }
1516
1517    // --- attest 1.4.0 parity: optional paths --------------------------------
1518
1519    // --- attest 1.4.0 parity: the notes ref is origin's mirror --------------
1520}