Skip to main content

amont_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//! Shape of the note, attached to each pushed tip in `refs/notes/amont-attest`:
11//!
12//! ```text
13//! amont-attest-v1
14//! tree <tree the gates ran against>
15//! gates <names of the pre-push checks that PASSED>
16//! amont <version that produced it>
17//!
18//! -----BEGIN SSH SIGNATURE-----
19//! …signature over the four lines above…
20//! -----END SSH SIGNATURE-----
21//! ```
22//!
23//! The signature covers the **tree**, not the commit: tests read content, not
24//! messages, so a reword or a tree-preserving rebase keeps its attestation —
25//! the same reasoning as `gate_stamp`'s tree binding. CI's skip condition is
26//! tree equality with its own checkout plus a valid signature over exactly
27//! that tree, verified with stock `ssh-keygen -Y verify` against an
28//! `allowed_signers` file committed in the consuming repository. amont itself
29//! still never runs in CI (`docs/ci.md`) — CI verifies a document.
30//!
31//! Signing uses `ssh-keygen -Y sign` as a subprocess, like every other tool
32//! this crate talks to. Hand-rolling ed25519 in a zero-dependency crate would
33//! be the one thing worse than a dependency.
34//!
35//! Every failure mode points the same direction as `gate_stamp`'s: no key, a
36//! signer that errors, a note git refused, a notes push the remote rejected —
37//! all mean "no attestation", and no attestation means CI RUNS the tests.
38//! Nothing here can let an untested tree skip CI; it can only cost a
39//! redundant run.
40//!
41//! One sharp edge is the notes push itself: `git push` from inside pre-push
42//! runs pre-push again. The child carries [`PUSH_GUARD`] in its environment
43//! and the dispatcher yields immediately when it sees it — checking a ref
44//! list that is only ever `refs/notes/amont-attest` would be work spent
45//! proving nothing.
46
47use std::path::PathBuf;
48use std::process::{Command, Stdio};
49
50use crate::pushrefs::PushRef;
51
52/// First token of every note body. Versioned like `gate_stamp::FORMAT`: a
53/// future amont that changes the payload bumps this, and CI's verifier reads
54/// an unknown version as "no attestation".
55///
56/// v1 → v2 added the `platform` line. The bump is the point: a v1 verifier
57/// has no idea the tests it is about to skip ran on a different operating
58/// system, and reading v2 as unknown makes it run them. Fail-safe in the
59/// only direction this module ever fails.
60pub const FORMAT: &str = "amont-attest-v2";
61
62/// The notes ref, spelled the way `git notes --ref` wants it.
63pub const NOTES_REF: &str = "amont-attest";
64
65/// The same ref, fully qualified — the push refspec and `update-ref -d` both
66/// need it.
67pub const NOTES_FULL_REF: &str = "refs/notes/amont-attest";
68
69/// The `ssh-keygen -Y` namespace, on both the signing and verifying side.
70/// Namespaces exist so a signature minted for one purpose cannot be replayed
71/// for another; an `allowed_signers` entry pinned to this namespace accepts
72/// nothing else.
73pub const NAMESPACE: &str = "amont-attest";
74
75/// Environment marker carried by the notes push so the recursive pre-push
76/// invocation stands down. See the module doc.
77pub const PUSH_GUARD: &str = "AMONT_ATTEST_PUSH";
78
79/// The opt-in switch. Off by default: an attestation is a statement to
80/// another system, and amont does not speak for a repository that never
81/// asked it to.
82const TOGGLE: &str = "amont.attest";
83
84/// Where the signing key lives when the repository does not say.
85const KEY_CONFIG: &str = "amont.attestKey";
86const KEY_DEFAULT: &str = ".ssh/amont-attest";
87
88/// Is the recursive-push marker set on THIS invocation?
89pub fn push_guard_active() -> bool {
90    std::env::var_os(PUSH_GUARD).is_some()
91}
92
93/// Has this repository opted in?
94pub fn enabled() -> bool {
95    crate::config::boolean_or(TOGGLE, false)
96}
97
98/// The signing key path: `amont.attestKey`, else `~/.ssh/amont-attest`.
99///
100/// Read like `amont.knownIdentity` is — a raw string through git, unset
101/// collapsing to the default — because a path has no shape git could
102/// validate for us anyway.
103fn key_path() -> Option<PathBuf> {
104    if let Some(k) = crate::git::stdout(&["config", "--get", KEY_CONFIG]) {
105        if !k.is_empty() {
106            return Some(PathBuf::from(k));
107        }
108    }
109    let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE"))?;
110    Some(PathBuf::from(home).join(KEY_DEFAULT))
111}
112
113/// Where a suite ran, as `<arch>-<os>` — `aarch64-macos`, `x86_64-linux`,
114/// `x86_64-windows`.
115///
116/// Coarser than a target triple on purpose: the libc flavour is not
117/// something `std` can answer, and the question a CI matrix actually asks is
118/// "did this run on MY leg". Coarse and honest beats precise and guessed.
119pub fn platform() -> String {
120    format!("{}-{}", std::env::consts::ARCH, std::env::consts::OS)
121}
122
123/// The exact bytes the signature covers. One datum per line, trailing
124/// newline included — CI reconstructs this from the note text, so the shape
125/// is a contract, not a convenience.
126///
127/// `platform` is signed alongside the gates because a pass is a pass **on
128/// something**: `cargo test` green on an arm64 Mac says nothing about the
129/// Windows leg of a matrix, and a note that omitted where it ran invited
130/// exactly that skip.
131pub fn payload(tree: &str, gates: &[String]) -> String {
132    format!(
133        "{FORMAT}\ntree {tree}\ngates {}\nplatform {}\namont {}\n",
134        gates.join(" "),
135        platform(),
136        env!("CARGO_PKG_VERSION")
137    )
138}
139
140/// `ssh-keygen -Y sign` over `payload`, armored signature back. `None` for
141/// every failure — a missing binary, a missing key, a signer that said no —
142/// because an attestation we cannot mint is simply one CI never sees.
143fn sign(payload: &str, key: &std::path::Path) -> Option<String> {
144    use std::io::Write;
145    let mut child = Command::new("ssh-keygen")
146        .args(["-Y", "sign", "-n", NAMESPACE, "-f"])
147        .arg(key)
148        .stdin(Stdio::piped())
149        .stdout(Stdio::piped())
150        .stderr(Stdio::null())
151        .spawn()
152        .ok()?;
153    child.stdin.take()?.write_all(payload.as_bytes()).ok()?;
154    let out = child.wait_with_output().ok()?;
155    if !out.status.success() {
156        return None;
157    }
158    let sig = String::from_utf8_lossy(&out.stdout).trim().to_string();
159    sig.starts_with("-----BEGIN SSH SIGNATURE-----")
160        .then_some(sig)
161}
162
163/// `ssh-keygen -Y verify`: is `sig` a valid signature over `payload` by a
164/// `principal` key listed in `allowed_signers` for our namespace?
165///
166/// The runtime never gates on this — CI verifies with its own stock tooling —
167/// but owning the verifying half keeps the roundtrip honest in tests and
168/// gives a future `amont attest verify` its engine.
169pub fn verify(
170    payload: &str,
171    sig: &str,
172    allowed_signers: &std::path::Path,
173    principal: &str,
174) -> bool {
175    use std::io::Write;
176    // -Y verify takes the signature as a FILE; the payload rides stdin.
177    let sig_file = std::env::temp_dir().join(format!(
178        "amont-attest-verify-{}-{:p}.sig",
179        std::process::id(),
180        &sig
181    ));
182    if std::fs::write(&sig_file, format!("{sig}\n")).is_err() {
183        return false;
184    }
185    let ok = (|| {
186        let mut child = Command::new("ssh-keygen")
187            .args(["-Y", "verify", "-n", NAMESPACE, "-I", principal, "-f"])
188            .arg(allowed_signers)
189            .arg("-s")
190            .arg(&sig_file)
191            .stdin(Stdio::piped())
192            .stdout(Stdio::null())
193            .stderr(Stdio::null())
194            .spawn()
195            .ok()?;
196        child.stdin.take()?.write_all(payload.as_bytes()).ok()?;
197        child.wait().ok().map(|s| s.success())
198    })()
199    .unwrap_or(false);
200    let _ = std::fs::remove_file(&sig_file);
201    ok
202}
203
204/// pre-push, after every block gate has passed: attest each pushed tip and
205/// send the notes ref to the remote being pushed.
206///
207/// `gates` is what the dispatcher saw actually PASS — `Warned` and
208/// `Unavailable` never appear in it, because "could not run" is not
209/// "passed". Empty means nothing testlike ran, and an attestation listing
210/// no gates would be a signed way of saying nothing.
211///
212/// Best-effort throughout, and quiet about it: pre-push has already printed
213/// its verdicts, and a push that works minus its CI shortcut is not a
214/// problem anyone needs to solve at push time.
215pub fn attest_push(remote: &str, refs: &[PushRef], gates: &[String]) {
216    if gates.is_empty() || remote.is_empty() || !enabled() {
217        return;
218    }
219    let Some(key) = key_path() else { return };
220    if !key.exists() {
221        crate::config::complain(
222            TOGGLE,
223            &format!("signing key {} does not exist", key.display()),
224            "no attestation (CI will run the tests)",
225        );
226        return;
227    }
228    let mut noted = false;
229    for r in refs {
230        if is_zero(&r.local_oid) {
231            continue; // deleting a ref pushes no code
232        }
233        let spec = format!("{}^{{tree}}", r.local_oid);
234        let Some(tree) = crate::git::stdout(&["rev-parse", &spec]) else {
235            continue;
236        };
237        let body = match sign(&payload(&tree, gates), &key) {
238            Some(sig) => format!("{}\n{sig}", payload(&tree, gates)),
239            None => continue,
240        };
241        if crate::git::succeeds(&[
242            "notes",
243            "--ref",
244            NOTES_REF,
245            "add",
246            "-f",
247            "-m",
248            &body,
249            &r.local_oid,
250        ]) {
251            noted = true;
252        }
253    }
254    if noted && push_notes(remote) {
255        crate::say!(
256            "{} attested {} for CI ({})",
257            crate::ui::valid_sign(),
258            crate::ui::highlight(&gates.join(" ")),
259            NOTES_REF,
260        );
261    }
262}
263
264/// `amont attest covered` — the verifying side, as CI's one-liner.
265///
266/// Answers "which gates does a VALID attestation cover for the tree checked
267/// out here?", doing everything the workflow snippet used to spell out in
268/// sh: freshen the notes ref (best-effort), look for a note on `HEAD` and —
269/// for a PR's merge commit — on `HEAD^2`, insist on the format version,
270/// insist the attested tree is byte-for-byte `HEAD^{tree}`, and verify the
271/// signature against `allowed_signers`. Thirty lines of workflow copied into
272/// every repository is exactly the drift this binary exists to end.
273///
274/// `None` for every failure, and the CLI prints nothing and exits 0 on
275/// `None` — fail-open is the caller's contract, not its option. A CI step
276/// reading empty output runs its tests, which is always the safe answer.
277///
278/// This is amont running in CI, which `docs/ci.md` forbids for CHECKS — the
279/// line held is narrower than the slogan: CI still never runs a check
280/// through amont; this verifies a document about checks that already ran.
281/// `require_platform` is the leg asking. `Some("x86_64-linux")` covers only
282/// a suite that ran there; `None` is the caller stating that this suite's
283/// result does not depend on where it ran (a pure-JS unit run, say) and is
284/// spelled `--platform any` in a committed workflow, where it is reviewed
285/// like any other line of the repository.
286pub fn covered(
287    signers: &std::path::Path,
288    principal: &str,
289    require_platform: Option<&str>,
290) -> Option<String> {
291    let refspec = format!("+{NOTES_FULL_REF}:{NOTES_FULL_REF}");
292    let _ = crate::git::succeeds(&["fetch", "origin", &refspec]);
293    let head_tree = crate::git::stdout(&["rev-parse", "HEAD^{tree}"])?;
294    // HEAD first: a push event's checkout IS the attested commit. HEAD^2
295    // second: a PR checkout is a merge commit git made a moment ago, whose
296    // second parent is the pushed tip that carries the note — and the tree
297    // comparison below still measures against what is ACTUALLY checked out,
298    // so a merge whose tree drifted from the tested tip never skips.
299    for candidate in ["HEAD", "HEAD^2"] {
300        let Some(commit) = crate::git::stdout(&["rev-parse", "--verify", candidate]) else {
301            continue;
302        };
303        let Some(body) = crate::git::stdout(&["notes", "--ref", NOTES_REF, "show", &commit]) else {
304            continue;
305        };
306        let Some((payload, sig)) = split_note(&body) else {
307            continue;
308        };
309        // By prefix, not by position: the payload has grown a line once
310        // already, and a positional reader silently mis-assigns every field
311        // after an insertion rather than failing.
312        let mut lines = payload.lines();
313        if lines.next() != Some(FORMAT) {
314            continue;
315        }
316        let field = |name: &str| {
317            payload
318                .lines()
319                .find_map(|l| l.strip_prefix(name).and_then(|r| r.strip_prefix(' ')))
320                .map(str::trim)
321        };
322        let (Some(tree), Some(gates), Some(ran_on)) =
323            (field("tree"), field("gates"), field("platform"))
324        else {
325            continue;
326        };
327        if tree != head_tree || gates.is_empty() {
328            continue; // wrong content, or a signed way of saying nothing
329        }
330        // The leg asking is not the leg that ran: a macOS `cargo test` is no
331        // evidence about Windows. `None` means the caller has stated this
332        // suite is platform-independent.
333        if require_platform.is_some_and(|want| want != ran_on) {
334            continue;
335        }
336        if verify(&payload, &sig, signers, principal) {
337            return Some(gates.to_string());
338        }
339    }
340    None
341}
342
343/// Where a repository keeps its `allowed_signers` when the caller does not
344/// say — the Forgejo location first, the GitHub one second. `None` when
345/// neither exists, which the CLI reads as "nothing is covered".
346pub fn default_signers() -> Option<PathBuf> {
347    [".forgejo/allowed_signers", ".github/allowed_signers"]
348        .into_iter()
349        .map(PathBuf::from)
350        .find(|p| p.exists())
351}
352
353/// The first principal an `allowed_signers` file names — the identity to
354/// verify against when the caller does not pass `--principal`. One key, one
355/// principal is the overwhelmingly common shape of this file; a multi-signer
356/// team passes the flag.
357pub fn first_principal(signers: &std::path::Path) -> Option<String> {
358    let body = std::fs::read_to_string(signers).ok()?;
359    body.lines()
360        .map(str::trim)
361        .find(|l| !l.is_empty() && !l.starts_with('#'))
362        .and_then(|l| l.split_whitespace().next())
363        .map(str::to_string)
364}
365
366/// A note body back into the exact bytes that were signed, plus the
367/// signature block. The blank-line split ate the payload's trailing newline;
368/// it is part of the signed bytes, so it goes back.
369fn split_note(body: &str) -> Option<(String, String)> {
370    let (payload, sig) = body.split_once("\n\n")?;
371    if !sig.starts_with("-----BEGIN SSH SIGNATURE-----") {
372        return None;
373    }
374    Some((format!("{payload}\n"), sig.to_string()))
375}
376
377/// Push the notes ref, marked so the recursive pre-push yields.
378///
379/// Not `git::succeeds` — that helper cannot set an environment variable, and
380/// the guard is the entire point of this wrapper existing.
381fn push_notes(remote: &str) -> bool {
382    let refspec = format!("{NOTES_FULL_REF}:{NOTES_FULL_REF}");
383    Command::new("git")
384        .args(["push", remote, &refspec])
385        .env(PUSH_GUARD, "1")
386        .stdin(Stdio::null())
387        .stdout(Stdio::null())
388        .stderr(Stdio::null())
389        .status()
390        .map(|s| s.success())
391        .unwrap_or(false)
392}
393
394/// A ref oid that is all zeros — git's spelling of "no object" in the
395/// pre-push ref list, for any hash width.
396fn is_zero(oid: &str) -> bool {
397    !oid.is_empty() && oid.bytes().all(|b| b == b'0')
398}
399
400/// uninstall: forget the local ref. The copies already pushed to remotes are
401/// statements we made and stand by; only OUR bookkeeping is removed — the
402/// same line `gate_stamp::forget` draws.
403pub fn forget() {
404    let _ = crate::git::succeeds(&["update-ref", "-d", NOTES_FULL_REF]);
405}
406
407#[cfg(test)]
408mod tests {
409    use super::*;
410    use std::path::Path;
411
412    /// Real repositories and real keys: every function here is a conversation
413    /// with git or ssh-keygen, and a mocked conversation tests the one we
414    /// imagined. Same doctrine as `gate_stamp`'s tests.
415    fn dir(name: &str) -> PathBuf {
416        let d = std::env::temp_dir().join(format!("attest-{name}-{}", std::process::id()));
417        let _ = std::fs::remove_dir_all(&d);
418        std::fs::create_dir_all(&d).unwrap();
419        d
420    }
421
422    fn git(dir: &Path, args: &[&str]) -> String {
423        let out = std::process::Command::new("git")
424            .arg("-C")
425            .arg(dir)
426            .args(args)
427            .output()
428            .expect("git");
429        String::from_utf8_lossy(&out.stdout).trim().to_string()
430    }
431
432    fn repo(name: &str) -> PathBuf {
433        let d = dir(name);
434        git(&d, &["init", "-q", "--template=", "."]);
435        git(&d, &["config", "user.email", "t@t.test"]);
436        git(&d, &["config", "user.name", "t"]);
437        d
438    }
439
440    /// A throwaway ed25519 key plus the `allowed_signers` line CI would
441    /// commit for it, namespace-pinned exactly as the docs instruct.
442    fn keypair(d: &Path) -> (PathBuf, PathBuf) {
443        let key = d.join("attest_key");
444        let ok = std::process::Command::new("ssh-keygen")
445            .args(["-q", "-t", "ed25519", "-N", "", "-C", "test", "-f"])
446            .arg(&key)
447            .status()
448            .expect("ssh-keygen must exist for these tests")
449            .success();
450        assert!(ok, "keygen failed");
451        let pubkey = std::fs::read_to_string(key.with_extension("pub")).unwrap();
452        let signers = d.join("allowed_signers");
453        std::fs::write(
454            &signers,
455            format!("t@t.test namespaces=\"{NAMESPACE}\" {pubkey}"),
456        )
457        .unwrap();
458        (key, signers)
459    }
460
461    /// The module talks to the repo at the process cwd; serialised against
462    /// every other cwd-moving test via the crate-wide lock.
463    fn in_repo<T>(dir: &Path, f: impl FnOnce() -> T) -> T {
464        let _guard = crate::TEST_CWD.lock().unwrap_or_else(|p| p.into_inner());
465        let prev = std::env::current_dir().unwrap();
466        std::env::set_current_dir(dir).unwrap();
467        let r = f();
468        std::env::set_current_dir(prev).unwrap();
469        r
470    }
471
472    #[test]
473    fn the_payload_is_the_documented_contract() {
474        let p = payload(
475            "abc123",
476            &["pre-push-pytest".into(), "pre-push-cargo-test".into()],
477        );
478        let lines: Vec<&str> = p.lines().collect();
479        assert_eq!(lines[0], FORMAT);
480        assert_eq!(lines[1], "tree abc123");
481        assert_eq!(lines[2], "gates pre-push-pytest pre-push-cargo-test");
482        assert_eq!(lines[3], format!("platform {}", platform()));
483        assert_eq!(lines[4], format!("amont {}", env!("CARGO_PKG_VERSION")));
484        assert!(
485            p.ends_with('\n'),
486            "CI reconstructs these bytes; the trailing newline is part of them"
487        );
488    }
489
490    #[test]
491    fn sign_verify_roundtrip_and_tamper_rejection() {
492        let d = dir("roundtrip");
493        let (key, signers) = keypair(&d);
494        let p = payload("deadbeef", &["pre-push-pytest".into()]);
495        let sig = sign(&p, &key).expect("signing with a real key succeeds");
496        assert!(verify(&p, &sig, &signers, "t@t.test"));
497        // One byte of the tree changed: the signature must not carry over —
498        // this is the entire difference between this module and gate_stamp.
499        let tampered = payload("deadbeee", &["pre-push-pytest".into()]);
500        assert!(!verify(&tampered, &sig, &signers, "t@t.test"));
501        // The right payload under the wrong principal is also no.
502        assert!(!verify(&p, &sig, &signers, "someone@else.test"));
503        let _ = std::fs::remove_dir_all(&d);
504    }
505
506    #[test]
507    fn a_missing_key_signs_nothing() {
508        assert!(sign("anything", Path::new("/nonexistent/key")).is_none());
509    }
510
511    /// The full journey: a repo with the toggle on pushes, and the BARE
512    /// remote ends up holding a note whose payload verifies and matches the
513    /// pushed tree. This is everything CI relies on, minus CI.
514    #[test]
515    fn an_enabled_push_leaves_a_verifiable_note_on_the_remote() {
516        let d = dir("e2e");
517        let (key, signers) = keypair(&d);
518        let remote = d.join("remote.git");
519        std::fs::create_dir_all(&remote).unwrap();
520        git(&remote, &["init", "-q", "--bare", "--template=", "."]);
521        let work = repo("e2e-work");
522        git(
523            &work,
524            &["remote", "add", "origin", remote.to_str().unwrap()],
525        );
526        git(&work, &["config", "amont.attest", "true"]);
527        git(&work, &["config", "amont.attestKey", key.to_str().unwrap()]);
528        std::fs::write(work.join("a.ts"), "x").unwrap();
529        git(&work, &["add", "a.ts"]);
530        git(&work, &["commit", "-qm", "chore: a"]);
531        let head = git(&work, &["rev-parse", "HEAD"]);
532        let tree = git(&work, &["rev-parse", "HEAD^{tree}"]);
533        let push_ref = PushRef {
534            local_ref: "refs/heads/main".into(),
535            local_oid: head.clone(),
536            remote_ref: "refs/heads/main".into(),
537            remote_oid: "0".repeat(40),
538        };
539        in_repo(&work, || {
540            attest_push("origin", &[push_ref], &["pre-push-run-tests-js".into()]);
541        });
542        // The note exists on the REMOTE — the whole point is that it travels.
543        let body = git(&remote, &["notes", "--ref", NOTES_REF, "show", &head]);
544        assert!(!body.is_empty(), "no note reached the remote");
545        let (p, sig) = body
546            .split_once("\n\n")
547            .expect("payload, blank line, signature");
548        let p = format!("{p}\n"); // the blank-line split ate payload's trailing newline
549        assert!(p.starts_with(FORMAT));
550        assert!(
551            p.contains(&format!("tree {tree}")),
552            "attests the pushed tree"
553        );
554        assert!(
555            verify(&p, sig, &signers, "t@t.test"),
556            "the remote copy verifies"
557        );
558        let _ = std::fs::remove_dir_all(&d);
559        let _ = std::fs::remove_dir_all(&work);
560    }
561
562    /// Off by default: a repo that never opted in makes no statement, even
563    /// with everything else in place.
564    #[test]
565    fn no_opt_in_means_no_note() {
566        let d = dir("optout");
567        let (key, _) = keypair(&d);
568        let remote = d.join("remote.git");
569        std::fs::create_dir_all(&remote).unwrap();
570        git(&remote, &["init", "-q", "--bare", "--template=", "."]);
571        let work = repo("optout-work");
572        git(
573            &work,
574            &["remote", "add", "origin", remote.to_str().unwrap()],
575        );
576        git(&work, &["config", "amont.attestKey", key.to_str().unwrap()]);
577        std::fs::write(work.join("a.ts"), "x").unwrap();
578        git(&work, &["add", "a.ts"]);
579        git(&work, &["commit", "-qm", "chore: a"]);
580        let head = git(&work, &["rev-parse", "HEAD"]);
581        let push_ref = PushRef {
582            local_ref: "refs/heads/main".into(),
583            local_oid: head.clone(),
584            remote_ref: "refs/heads/main".into(),
585            remote_oid: "0".repeat(40),
586        };
587        in_repo(&work, || {
588            attest_push("origin", &[push_ref], &["pre-push-run-tests-js".into()]);
589        });
590        assert!(
591            git(&remote, &["notes", "--ref", NOTES_REF, "list"]).is_empty(),
592            "an un-opted-in repo attested something"
593        );
594        let _ = std::fs::remove_dir_all(&d);
595        let _ = std::fs::remove_dir_all(&work);
596    }
597
598    /// A deletion pushes no code; an empty gate list says nothing. Neither
599    /// may produce a note even in an enabled repo.
600    #[test]
601    fn deletions_and_empty_gates_attest_nothing() {
602        let d = dir("nothing");
603        let (key, _) = keypair(&d);
604        let remote = d.join("remote.git");
605        std::fs::create_dir_all(&remote).unwrap();
606        git(&remote, &["init", "-q", "--bare", "--template=", "."]);
607        let work = repo("nothing-work");
608        git(
609            &work,
610            &["remote", "add", "origin", remote.to_str().unwrap()],
611        );
612        git(&work, &["config", "amont.attest", "true"]);
613        git(&work, &["config", "amont.attestKey", key.to_str().unwrap()]);
614        std::fs::write(work.join("a.ts"), "x").unwrap();
615        git(&work, &["add", "a.ts"]);
616        git(&work, &["commit", "-qm", "chore: a"]);
617        let head = git(&work, &["rev-parse", "HEAD"]);
618        let deletion = PushRef {
619            local_ref: "(delete)".into(),
620            local_oid: "0".repeat(40),
621            remote_ref: "refs/heads/gone".into(),
622            remote_oid: head.clone(),
623        };
624        let real = PushRef {
625            local_ref: "refs/heads/main".into(),
626            local_oid: head,
627            remote_ref: "refs/heads/main".into(),
628            remote_oid: "0".repeat(40),
629        };
630        in_repo(&work, || {
631            attest_push("origin", &[deletion], &["pre-push-pytest".into()]);
632            attest_push("origin", &[real], &[]);
633        });
634        assert!(git(&remote, &["notes", "--ref", NOTES_REF, "list"]).is_empty());
635        let _ = std::fs::remove_dir_all(&d);
636        let _ = std::fs::remove_dir_all(&work);
637    }
638
639    /// The half CI actually calls, from CI's own vantage point: a fresh
640    /// clone. `covered` fetches the notes ref itself, verifies, and answers
641    /// with the gates — then stops answering the moment the tree drifts or
642    /// the note is replaced by something unsigned.
643    #[test]
644    fn covered_answers_in_a_fresh_clone_and_rejects_drift_and_forgery() {
645        let d = dir("covered");
646        let (key, signers) = keypair(&d);
647        let remote = d.join("remote.git");
648        std::fs::create_dir_all(&remote).unwrap();
649        git(&remote, &["init", "-q", "--bare", "--template=", "."]);
650        // The fixture pushes to `main`; a bare init on a machine whose
651        // init.defaultBranch is the historical default leaves HEAD on
652        // `master`, and a clone of that repository checks out NOTHING —
653        // `covered` then answers None with a perfectly good note sitting in
654        // the ref. Caught only in CI: dev machines set main globally.
655        git(&remote, &["symbolic-ref", "HEAD", "refs/heads/main"]);
656        let work = repo("covered-work");
657        git(
658            &work,
659            &["remote", "add", "origin", remote.to_str().unwrap()],
660        );
661        git(&work, &["config", "amont.attest", "true"]);
662        git(&work, &["config", "amont.attestKey", key.to_str().unwrap()]);
663        std::fs::write(work.join("a.ts"), "x").unwrap();
664        git(&work, &["add", "a.ts"]);
665        git(&work, &["commit", "-qm", "chore: a"]);
666        git(&work, &["push", "-q", "origin", "HEAD:main"]);
667        let head = git(&work, &["rev-parse", "HEAD"]);
668        let push_ref = PushRef {
669            local_ref: "refs/heads/main".into(),
670            local_oid: head.clone(),
671            remote_ref: "refs/heads/main".into(),
672            remote_oid: "0".repeat(40),
673        };
674        in_repo(&work, || {
675            attest_push("origin", &[push_ref], &["pre-push-pytest".into()]);
676        });
677        let clone = d.join("ci-checkout");
678        git(
679            &d,
680            &[
681                "clone",
682                "-q",
683                "--template=",
684                remote.to_str().unwrap(),
685                clone.to_str().unwrap(),
686            ],
687        );
688        in_repo(&clone, || {
689            assert_eq!(
690                covered(&signers, "t@t.test", Some(&platform())).as_deref(),
691                Some("pre-push-pytest"),
692                "a fresh clone verifies the attestation and reads the gates"
693            );
694            assert_eq!(
695                covered(&signers, "t@t.test", None).as_deref(),
696                Some("pre-push-pytest"),
697                "`any` covers a platform-independent suite"
698            );
699            // The matrix case this exists for: another leg asking about a
700            // suite that never ran there.
701            assert_eq!(
702                covered(&signers, "t@t.test", Some("s390x-aix")),
703                None,
704                "a pass on one platform is not evidence about another"
705            );
706            assert_eq!(
707                covered(&signers, "someone@else.test", None),
708                None,
709                "an unlisted principal covers nothing"
710            );
711        });
712        // Tree drift: a new commit in the checkout is not the attested tree.
713        std::fs::write(clone.join("b.ts"), "y").unwrap();
714        git(&clone, &["config", "user.email", "t@t.test"]);
715        git(&clone, &["config", "user.name", "t"]);
716        git(&clone, &["add", "b.ts"]);
717        git(&clone, &["commit", "-qm", "chore: b"]);
718        in_repo(&clone, || {
719            assert_eq!(covered(&signers, "t@t.test", None), None, "drifted tree");
720        });
721        // Forgery: replace the remote's note with an unsigned one. covered's
722        // own fetch pulls it in, and it must read as "no attestation".
723        git(
724            &work,
725            &[
726                "notes", "--ref", NOTES_REF, "add", "-f", "-m", "garbage", &head,
727            ],
728        );
729        git(
730            &work,
731            &[
732                "push",
733                "-q",
734                "origin",
735                &format!("+{NOTES_FULL_REF}:{NOTES_FULL_REF}"),
736            ],
737        );
738        git(&clone, &["reset", "-q", "--hard", &head]);
739        in_repo(&clone, || {
740            assert_eq!(
741                covered(&signers, "t@t.test", None),
742                None,
743                "a foreign note is not a stamp"
744            );
745        });
746        let _ = std::fs::remove_dir_all(&d);
747        let _ = std::fs::remove_dir_all(&work);
748    }
749
750    #[test]
751    fn zero_oids_of_any_width_are_zero() {
752        assert!(is_zero(&"0".repeat(40)));
753        assert!(is_zero(&"0".repeat(64)));
754        assert!(!is_zero("0a0000"));
755        assert!(!is_zero(""));
756    }
757
758    #[test]
759    fn forget_removes_the_local_ref() {
760        let work = repo("forget");
761        std::fs::write(work.join("a.ts"), "x").unwrap();
762        git(&work, &["add", "a.ts"]);
763        git(&work, &["commit", "-qm", "chore: a"]);
764        git(
765            &work,
766            &["notes", "--ref", NOTES_REF, "add", "-m", "x", "HEAD"],
767        );
768        in_repo(&work, forget);
769        assert!(git(&work, &["notes", "--ref", NOTES_REF, "list"]).is_empty());
770        let _ = std::fs::remove_dir_all(&work);
771    }
772}