1use 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
49pub const NOTES_FULL_REF: &str = "refs/notes/amont-attest";
51pub const INPUTS_FULL_REF: &str = "refs/notes/amont-attest-inputs";
52
53pub 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
62pub const PUSH_GUARD: &str = "AMONT_ATTEST_PUSH";
65
66fn here() -> &'static Path {
68 Path::new(".")
69}
70
71const TOGGLE: &str = "amont.attest";
75
76const KEY_CONFIG: &str = "amont.attestKey";
78const KEY_DEFAULT: &str = ".ssh/amont-attest";
79
80pub fn push_guard_active() -> bool {
82 std::env::var_os(PUSH_GUARD).is_some()
83}
84
85pub fn enabled(settings: &crate::config::Settings) -> bool {
87 crate::config::boolean_or(settings, TOGGLE, false)
88}
89
90fn 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
105pub 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
139pub 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 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; }
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 let mut counted = false;
198 for (on, line, linux_names) in platforms {
199 if line.is_empty() {
200 continue;
201 }
202 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 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 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
281fn 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
297fn 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
320pub 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
334fn 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; };
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 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 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
423fn 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
441fn 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
462const PUSH_ATTEMPTS: u32 = 4;
464
465fn 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
487pub 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
508pub 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#[derive(Debug, Clone, PartialEq, Eq, Default)]
527pub struct Covered {
528 pub gates: Option<String>,
529 pub rejected: Vec<String>,
530}
531
532pub 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
557fn 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
569pub fn default_signers() -> Option<PathBuf> {
572 git_attest::verify::default_signers(here())
573}
574
575fn is_zero(oid: &str) -> bool {
578 !oid.is_empty() && oid.bytes().all(|b| b == b'0')
579}
580
581pub fn forget() -> bool {
585 crate::git::succeeds(&["update-ref", "-d", NOTES_FULL_REF])
586}
587
588pub 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 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 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 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 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 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 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 fn provenance_world(name: &str) -> (PathBuf, PathBuf, PathBuf, String, String, PathBuf) {
764 provenance_world_in(name, None)
765 }
766
767 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 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 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 #[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 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 #[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 #[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 #[test]
1021 fn a_failed_canon_keeps_the_payload() {
1022 let (d, work, remote, head, tree, _) = provenance_world("prov-nocanon");
1023 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 #[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 #[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 #[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 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"); 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 #[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 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 #[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 #[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 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 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 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 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 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 #[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 }