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 = "GREENGATE_ATTEST_PUSH";
65
66fn here() -> &'static Path {
68 Path::new(".")
69}
70
71const TOGGLE: &str = "greengate.attest";
75
76const KEY_CONFIG: &str = "greengate.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(
133 settings: &crate::config::Settings,
134 remote: &str,
135 refs: &[PushRef],
136 gates: &[String],
137 cluster_gates: &[String],
138) {
139 attest_push_per_tip(settings, remote, refs, &|_| gates.to_vec(), cluster_gates);
140}
141
142pub fn attest_push_per_tip(
147 settings: &crate::config::Settings,
148 remote: &str,
149 refs: &[PushRef],
150 gates_for: &dyn Fn(&str) -> Vec<String>,
151 cluster_gates: &[String],
152) {
153 if remote.is_empty() || !enabled(settings) {
154 return;
155 }
156 let Some(key) = key_path() else { return };
157 if !key.exists() {
158 crate::config::complain(
159 TOGGLE,
160 &format!("signing key {} does not exist", key.display()),
161 "no attestation (CI will run the tests)",
162 );
163 return;
164 }
165 let producer = env!("CARGO_PKG_VERSION");
166 let mut laptop_signed: Vec<String> = Vec::new();
168 let mut blocks: Vec<(String, String)> = Vec::new();
169 let mut input_blocks: Vec<(String, String)> = Vec::new();
170 let mut linux_signed: Vec<String> = Vec::new();
171 let (mut n_inputs, mut n_canon) = (0, 0);
172 let in_cluster = std::cell::OnceCell::new();
174 for r in refs {
175 if is_zero(&r.local_oid) {
176 continue; }
178 let gates = gates_for(&r.local_oid);
179 if gates.is_empty() && cluster_gates.is_empty() {
180 continue;
181 }
182 let gates_line = gates.join(" ");
183 let spec = format!("{}^{{tree}}", r.local_oid);
184 let Some(tree) = crate::git::stdout(&["rev-parse", &spec]) else {
185 continue;
186 };
187 let mut proved_here: Vec<String> = cluster_gates
188 .iter()
189 .filter(|g| crate::cluster::proved(g, &tree))
190 .cloned()
191 .collect();
192 if !proved_here.is_empty()
196 && *in_cluster.get_or_init(|| crate::cluster::in_cluster_signer().is_some())
197 {
198 for signed in filed_signer_blocks(&tree) {
199 let (covered, rest): (Vec<String>, Vec<String>) = proved_here
200 .into_iter()
201 .partition(|g| signed.gates.contains(g));
202 proved_here = rest;
203 if covered.is_empty() {
204 continue;
205 }
206 for name in covered {
207 if !linux_signed.contains(&name) {
208 linux_signed.push(name);
209 }
210 }
211 blocks.push((tree.clone(), signed.body.clone()));
212 blocks.push((r.local_oid.clone(), signed.body));
213 }
214 }
215 let platforms = [
216 (platform(), gates_line.clone(), Vec::new()),
217 (
218 crate::cluster::PLATFORM.to_string(),
219 proved_here.join(" "),
220 proved_here,
221 ),
222 ];
223 let mut counted = false;
226 for (on, line, linux_names) in platforms {
227 if line.is_empty() {
228 continue;
229 }
230 let mut reasons = Vec::new();
233 let att = attestation(here(), &tree, &line, &on, producer, &mut reasons);
234 let Ok(sig) = git_attest::sign::sign(NAMESPACE, &att.payload, &key) else {
235 continue;
236 };
237 let body = block(&att.payload, &sig);
238 if !counted {
239 n_inputs += att.inputs.len();
240 n_canon += usize::from(att.canon.is_some());
241 counted = true;
242 }
243 for k in &att.input_keys {
244 input_blocks.push((k.clone(), body.clone()));
245 }
246 blocks.push((tree.clone(), body.clone()));
247 blocks.push((r.local_oid.clone(), body));
248 if linux_names.is_empty() {
249 for name in &gates {
250 if !laptop_signed.contains(name) {
251 laptop_signed.push(name.clone());
252 }
253 }
254 }
255 for name in linux_names {
256 if !linux_signed.contains(&name) {
257 linux_signed.push(name);
258 }
259 }
260 }
261 }
262 if blocks.is_empty() {
263 return;
264 }
265 let main_ok = publish(remote, NOTES_REF, &blocks);
269 let inputs_ok = input_blocks.is_empty() || publish(remote, INPUTS_REF, &input_blocks);
270 if main_ok {
271 let mut signed_on = Vec::new();
274 if !laptop_signed.is_empty() {
275 signed_on.push(format!(
276 "{} on {}",
277 crate::ui::highlight(&laptop_signed.join(" ")),
278 platform()
279 ));
280 }
281 if !linux_signed.is_empty() {
282 signed_on.push(format!(
283 "{} on {}",
284 crate::ui::highlight(&linux_signed.join(" ")),
285 crate::cluster::PLATFORM
286 ));
287 }
288 let what = signed_on.join("; ");
289 crate::say!(
290 "{} attested {} for CI ({}{})",
291 crate::ui::valid_sign(),
292 what,
293 NOTES_REF,
294 if input_blocks.is_empty() {
295 String::new()
296 } else if inputs_ok {
297 match (n_inputs, n_canon) {
298 (0, _) => ", canonical tree".to_string(),
299 (n, 0) => format!(", {n} input fingerprints"),
300 (n, _) => format!(", {n} input fingerprints, canonical tree"),
301 }
302 } else {
303 ", input fingerprints not published".to_string()
304 },
305 );
306 }
307}
308
309fn provenance_dir(env: impl Fn(&str) -> Option<std::ffi::OsString>) -> Option<PathBuf> {
318 let config = match env("CLAUDE_CONFIG_DIR") {
319 Some(d) => PathBuf::from(d),
320 None => PathBuf::from(env("HOME").or_else(|| env("USERPROFILE"))?).join(".claude"),
321 };
322 Some(config.join("amont-agent").join("provenance"))
323}
324
325fn repo_name() -> Option<String> {
330 let common = crate::git::stdout(&["rev-parse", "--git-common-dir"])?;
331 if common.is_empty() {
332 return None;
333 }
334 let common = PathBuf::from(common);
335 let common = if common.is_absolute() {
336 common
337 } else {
338 std::env::current_dir().ok()?.join(common)
339 };
340 let common = std::fs::canonicalize(&common).unwrap_or(common);
341 common
342 .parent()
343 .and_then(std::path::Path::file_name)
344 .map(|n| n.to_string_lossy().into_owned())
345 .filter(|n| !n.is_empty())
346}
347
348pub fn provenance_push(settings: &crate::config::Settings, remote: &str, refs: &[PushRef]) {
353 if remote.is_empty() || !enabled(settings) {
354 return;
355 }
356 let (Some(dir), Some(name)) = (provenance_dir(|k| std::env::var_os(k)), repo_name()) else {
357 return;
358 };
359 provenance_push_from(&dir.join(name), remote, refs);
360}
361
362fn provenance_push_from(dir: &std::path::Path, remote: &str, refs: &[PushRef]) {
364 let mut found: Vec<(PathBuf, String, String, String)> = Vec::new();
365 for r in refs {
366 if is_zero(&r.local_oid) {
367 continue;
368 }
369 let file = dir.join(&r.local_oid);
370 let Ok(payload) = std::fs::read_to_string(&file) else {
371 continue; };
373 let spec = format!("{}^{{tree}}", r.local_oid);
374 let Some(tree) = crate::git::stdout(&["rev-parse", &spec]) else {
375 continue;
376 };
377 let first = payload.lines().next().unwrap_or_default();
378 let claimed = payload.lines().find_map(|l| l.strip_prefix("tree "));
379 if first != PROVENANCE_FORMAT || claimed != Some(tree.as_str()) {
380 crate::say!(
381 " provenance for {} not signed: its payload is not an {PROVENANCE_FORMAT} record of this tree",
382 &r.local_oid[..r.local_oid.len().min(7)]
383 );
384 continue;
385 }
386 if payload
390 .lines()
391 .any(|l| l.split_ascii_whitespace().next() == Some("canon"))
392 {
393 for line in canon_refusal(&r.local_oid, &file) {
394 crate::say!("{line}");
395 }
396 continue;
397 }
398 let Ok(canon) = git_attest::fingerprint::canon(here(), &tree) else {
401 crate::say!(
402 " provenance for {} not signed: its canonical tree cannot be computed;",
403 &r.local_oid[..r.local_oid.len().min(7)]
404 );
405 crate::say!(" the payload is kept for the next push");
406 continue;
407 };
408 let payload = with_canon(&payload, &canon);
409 found.push((file, r.local_oid.clone(), tree, payload));
410 }
411 if found.is_empty() {
412 return;
413 }
414 let Some(key) = key_path().filter(|k| k.exists()) else {
415 crate::say!(" provenance not signed: no signing key");
416 return;
417 };
418 let mut blocks: Vec<(String, String)> = Vec::new();
419 let mut signed: Vec<PathBuf> = Vec::new();
420 for (file, commit, tree, payload) in found {
421 let Ok(sig) = git_attest::sign::sign(PROVENANCE_NAMESPACE, &payload, &key) else {
422 continue;
423 };
424 let body = block(&payload, &sig);
425 blocks.push((tree, body.clone()));
426 blocks.push((commit, body));
427 signed.push(file);
428 }
429 if blocks.is_empty() {
430 crate::say!(" provenance not signed: the signer refused");
431 return;
432 }
433 if publish(remote, PROVENANCE_REF, &blocks) {
434 for file in &signed {
435 if std::fs::remove_file(file).is_err() {
436 crate::say!(
437 " provenance published, but its payload {} could not be removed",
438 file.display()
439 );
440 }
441 }
442 crate::say!(
443 "{} provenance published ({PROVENANCE_REF})",
444 crate::ui::valid_sign()
445 );
446 } else {
447 crate::say!(" provenance not published: kept for the next push");
448 }
449}
450
451fn with_canon(payload: &str, canon: &str) -> String {
454 let mut out = String::with_capacity(payload.len() + canon.len() + 7);
455 let mut done = false;
456 for line in payload.split_inclusive('\n') {
457 out.push_str(line);
458 if !done && line.starts_with("tree ") {
459 if !line.ends_with('\n') {
460 out.push('\n');
461 }
462 out.push_str(&format!("canon {canon}\n"));
463 done = true;
464 }
465 }
466 out
467}
468
469fn canon_refusal(commit: &str, file: &std::path::Path) -> Vec<String> {
473 let dir = file.parent().unwrap_or(file).display().to_string();
474 let name = file
475 .file_name()
476 .map(|n| n.to_string_lossy().into_owned())
477 .unwrap_or_default();
478 vec![
479 format!(
480 " provenance for {} not signed: its payload carries a canon line",
481 &commit[..commit.len().min(7)]
482 ),
483 " (a pre-release amont-agent wrote it); delete the file".to_string(),
484 format!(" {name} in"),
485 format!(" {dir}"),
486 " and upgrade amont-agent".to_string(),
487 ]
488}
489
490const PUSH_ATTEMPTS: u32 = 4;
492
493fn publish(remote: &str, notes_ref: &str, blocks: &[(String, String)]) -> bool {
501 let how = Publish {
502 remote,
503 attempts: PUSH_ATTEMPTS,
504 pause: false,
505 identity: None,
506 push_env: &[(PUSH_GUARD, "1")],
507 };
508 let mut log = Vec::new();
509 matches!(
510 publish_notes(here(), &how, notes_ref, blocks, &mut log),
511 Published::Pushed | Published::AlreadyPresent
512 )
513}
514
515pub fn covered(
528 signers: &Path,
529 principal: Option<&str>,
530 require_platform: Option<&str>,
531 anywhere: &[String],
532) -> Option<String> {
533 covered_in(here(), signers, principal, require_platform, anywhere)
534}
535
536pub fn covered_in(
541 dir: &Path,
542 signers: &Path,
543 principal: Option<&str>,
544 require_platform: Option<&str>,
545 anywhere: &[String],
546) -> Option<String> {
547 covered_report(dir, signers, principal, require_platform, anywhere).gates
548}
549
550#[derive(Debug, Clone, PartialEq, Eq, Default)]
555pub struct Covered {
556 pub gates: Option<String>,
557 pub rejected: Vec<String>,
558}
559
560pub fn covered_report(
564 dir: &Path,
565 signers: &Path,
566 principal: Option<&str>,
567 require_platform: Option<&str>,
568 anywhere: &[String],
569) -> Covered {
570 let v =
571 git_attest::verify::evaluate(dir, signers, principal, require_platform, anywhere, false);
572 for line in v.loud.iter().chain(&v.warnings) {
573 eprintln!("{BIN}: {line}");
574 }
575 let rejected = signature_rejections(&v.trail);
576 for why in &rejected {
577 eprintln!("{BIN}: an attestation was found but did not verify: {why}");
578 }
579 Covered {
580 gates: (!v.gates.is_empty()).then(|| v.gates.join(" ")),
581 rejected,
582 }
583}
584
585fn signature_rejections(trail: &[String]) -> Vec<String> {
590 trail
591 .iter()
592 .filter(|line| line.starts_with("note on ") && line.contains(": "))
593 .cloned()
594 .collect()
595}
596
597#[derive(Debug, Clone, PartialEq, Eq)]
599pub(crate) struct SignerBlock {
600 pub principal: String,
602 pub gates: Vec<String>,
604 pub body: String,
606}
607
608#[derive(Debug, Clone, PartialEq, Eq)]
611pub(crate) enum BlockRefusal {
612 Signer(String),
616 Content(String),
619}
620
621impl BlockRefusal {
622 pub(crate) fn reason(&self) -> &str {
624 match self {
625 BlockRefusal::Signer(why) | BlockRefusal::Content(why) => why,
626 }
627 }
628}
629
630pub(crate) fn signer_block(
636 body: &str,
637 tree: &str,
638 signers: &Path,
639) -> Result<SignerBlock, BlockRefusal> {
640 use git_attest::format::{bound_platform, field, split_blocks};
641 use BlockRefusal::{Content, Signer};
642 let (mut blocks, _) = split_blocks(body);
643 if blocks.len() != 1 {
644 return Err(Content(format!("{} signed blocks, not one", blocks.len())));
645 }
646 let signed_block = blocks.remove(0);
647 if signed_block.payload.split('\n').next() != Some(FORMAT) {
648 return Err(Content(format!("not an {FORMAT} payload")));
649 }
650 let on = field(&signed_block.payload, "platform");
651 if on != Some(crate::cluster::PLATFORM) {
652 return Err(Content(format!(
653 "its platform is {}, not {}",
654 on.unwrap_or("missing"),
655 crate::cluster::PLATFORM
656 )));
657 }
658 let claimed = field(&signed_block.payload, "tree");
659 if claimed != Some(tree) {
660 return Err(Content(format!(
662 "it is for tree {}, not {tree}",
663 claimed.unwrap_or("missing")
664 )));
665 }
666 let principal = git_attest::sign::verify(
667 NAMESPACE,
668 &signed_block.payload,
669 &signed_block.signature,
670 signers,
671 None,
672 )
673 .map_err(|e| Signer(e.to_string()))?;
674 if bound_platform(&principal) != Some(crate::cluster::PLATFORM) {
675 return Err(Signer(format!(
676 "{principal} is not a principal bound to {}",
677 crate::cluster::PLATFORM
678 )));
679 }
680 Ok(SignerBlock {
681 principal,
682 gates: field(&signed_block.payload, "gates")
683 .unwrap_or("")
684 .split_whitespace()
685 .map(str::to_string)
686 .collect(),
687 body: block(&signed_block.payload, &signed_block.signature),
688 })
689}
690
691fn signer_notes_ref() -> String {
696 format!("{}{NOTES_REF}", git_attest::format::LOCAL_PREFIX)
697}
698
699pub(crate) fn file_signer_block(body: &str, keys: &[&str]) -> Result<(), String> {
705 let notes_ref = signer_notes_ref();
706 for key in keys {
707 let entry = [((*key).to_string(), body.to_string())];
708 if matches!(
709 git_attest::notes::publish_local(here(), None, ¬es_ref, &entry),
710 Published::Error
711 ) {
712 return Err(format!(
713 "git could not write the note on {key} in {notes_ref}"
714 ));
715 }
716 }
717 Ok(())
718}
719
720fn filed_signer_blocks(tree: &str) -> Vec<SignerBlock> {
724 use git_attest::format::{field, split_blocks};
725 let Some(signers) = default_signers() else {
726 return Vec::new();
727 };
728 let notes_ref = signer_notes_ref();
729 let Some(note) = crate::git::stdout(&["notes", "--ref", ¬es_ref, "show", tree]) else {
730 return Vec::new();
731 };
732 split_blocks(¬e)
733 .0
734 .iter()
735 .filter(|b| {
736 field(&b.payload, "platform") == Some(crate::cluster::PLATFORM)
737 && field(&b.payload, "tree") == Some(tree)
738 })
739 .filter_map(|b| signer_block(&block(&b.payload, &b.signature), tree, &signers).ok())
740 .collect()
741}
742
743pub fn default_signers() -> Option<PathBuf> {
746 git_attest::verify::default_signers(here())
747}
748
749fn is_zero(oid: &str) -> bool {
752 !oid.is_empty() && oid.bytes().all(|b| b == b'0')
753}
754
755pub fn forget() -> bool {
759 crate::git::succeeds(&["update-ref", "-d", NOTES_FULL_REF])
760}
761
762pub fn forget_in(repo: &std::path::Path) -> bool {
764 crate::git::succeeds_in(repo, &["update-ref", "-d", NOTES_FULL_REF])
765}
766
767#[cfg(test)]
768mod tests {
769 use super::*;
770
771 use std::process::Stdio;
772
773 fn canon(tree: &str) -> Option<String> {
774 git_attest::fingerprint::canon(here(), tree).ok()
775 }
776
777 fn sign(payload: &str, key: &Path) -> Option<String> {
778 git_attest::sign::sign(NAMESPACE, payload, key).ok()
779 }
780
781 fn verify(payload: &str, sig: &str, signers: &Path, principal: &str) -> bool {
782 verify_in(NAMESPACE, payload, sig, signers, principal)
783 }
784
785 fn verify_in(
786 namespace: &str,
787 payload: &str,
788 sig: &str,
789 signers: &Path,
790 principal: &str,
791 ) -> bool {
792 git_attest::sign::verify(namespace, payload, sig, signers, Some(principal)).is_ok()
793 }
794
795 fn test_settings() -> crate::config::Settings {
798 crate::config::Settings::default()
799 }
800
801 use std::io::Write;
802 use std::path::Path;
803
804 fn dir(name: &str) -> PathBuf {
808 let d = std::env::temp_dir().join(format!("attest-{name}-{}", std::process::id()));
809 let _ = std::fs::remove_dir_all(&d);
810 std::fs::create_dir_all(&d).unwrap();
811 d
812 }
813
814 fn git(dir: &Path, args: &[&str]) -> String {
823 let out = std::process::Command::new("git")
824 .arg("-C")
825 .arg(dir)
826 .args(args)
827 .output()
828 .expect("git");
829 assert!(
830 out.status.success(),
831 "fixture: git {args:?} in {} exited {:?}: {}",
832 dir.display(),
833 out.status.code(),
834 String::from_utf8_lossy(&out.stderr).trim()
835 );
836 String::from_utf8_lossy(&out.stdout).trim().to_string()
837 }
838
839 fn repo(name: &str) -> PathBuf {
840 let d = dir(name);
841 git(&d, &["init", "-q", "--template=", "."]);
842 git(&d, &["config", "user.email", "t@t.test"]);
843 git(&d, &["config", "user.name", "t"]);
844 d
845 }
846
847 fn keypair(d: &Path) -> (PathBuf, PathBuf) {
850 let key = d.join("attest_key");
851 let ok = std::process::Command::new("ssh-keygen")
852 .args(["-q", "-t", "ed25519", "-N", "", "-C", "test", "-f"])
853 .arg(&key)
854 .status()
855 .expect("ssh-keygen must exist for these tests")
856 .success();
857 assert!(ok, "keygen failed");
858 let pubkey = std::fs::read_to_string(key.with_extension("pub")).unwrap();
859 let signers = d.join("allowed_signers");
860 std::fs::write(
861 &signers,
862 format!("t@t.test namespaces=\"{NAMESPACE}\" {pubkey}"),
863 )
864 .unwrap();
865 (key, signers)
866 }
867
868 fn in_repo<T>(dir: &Path, f: impl FnOnce() -> T) -> T {
871 let _guard = crate::TEST_CWD.lock().unwrap_or_else(|p| p.into_inner());
872 let prev = std::env::current_dir().unwrap();
873 std::env::set_current_dir(dir).unwrap();
874 let r = f();
875 std::env::set_current_dir(prev).unwrap();
876 r
877 }
878
879 fn remote_and_work(name: &str) -> (PathBuf, PathBuf, PathBuf, PathBuf) {
881 let d = dir(name);
882 let (key, signers) = keypair(&d);
883 let remote = d.join("remote.git");
884 std::fs::create_dir_all(&remote).unwrap();
885 git(&remote, &["init", "-q", "--bare", "--template=", "."]);
886 let work = repo(&format!("{name}-work"));
887 git(
888 &work,
889 &["remote", "add", "origin", remote.to_str().unwrap()],
890 );
891 git(&work, &["config", "greengate.attest", "true"]);
892 git(
893 &work,
894 &["config", "greengate.attestKey", key.to_str().unwrap()],
895 );
896 std::fs::write(work.join("a.ts"), "x").unwrap();
897 git(&work, &["add", "a.ts"]);
898 git(&work, &["commit", "-qm", "chore: a"]);
899 (d, work, remote, signers)
900 }
901
902 fn push_ref_for(work: &Path) -> PushRef {
903 PushRef {
904 local_ref: "refs/heads/main".into(),
905 local_oid: git(work, &["rev-parse", "HEAD"]),
906 remote_ref: "refs/heads/main".into(),
907 remote_oid: "0".repeat(40),
908 }
909 }
910
911 #[test]
912 fn the_provenance_dir_is_resolved_like_amont_agents_config_dir() {
913 use std::ffi::OsString;
914 let env = |pairs: &'static [(&'static str, &'static str)]| {
915 move |k: &str| {
916 pairs
917 .iter()
918 .find(|(n, _)| *n == k)
919 .map(|(_, v)| OsString::from(v))
920 }
921 };
922 assert_eq!(
923 provenance_dir(env(&[("CLAUDE_CONFIG_DIR", "/c"), ("HOME", "/h")])),
924 Some(PathBuf::from("/c/amont-agent/provenance"))
925 );
926 assert_eq!(
927 provenance_dir(env(&[("HOME", "/h"), ("USERPROFILE", "/u")])),
928 Some(PathBuf::from("/h/.claude/amont-agent/provenance"))
929 );
930 assert_eq!(
931 provenance_dir(env(&[("USERPROFILE", "/u")])),
932 Some(PathBuf::from("/u/.claude/amont-agent/provenance"))
933 );
934 assert_eq!(provenance_dir(env(&[])), None);
935 }
936
937 fn provenance_world(name: &str) -> (PathBuf, PathBuf, PathBuf, String, String, PathBuf) {
941 provenance_world_in(name, None)
942 }
943
944 fn provenance_world_in(
946 name: &str,
947 object_format: Option<&str>,
948 ) -> (PathBuf, PathBuf, PathBuf, String, String, PathBuf) {
949 let d = dir(name);
950 let (key, _) = keypair(&d);
951 let pubkey = std::fs::read_to_string(key.with_extension("pub")).unwrap();
952 let signers = d.join("allowed_signers_provenance");
953 std::fs::write(
954 &signers,
955 format!("t@t.test namespaces=\"{NAMESPACE},{PROVENANCE_NAMESPACE}\" {pubkey}"),
956 )
957 .unwrap();
958 let remote = d.join("remote.git");
959 std::fs::create_dir_all(&remote).unwrap();
960 let fmt = format!("--object-format={}", object_format.unwrap_or("sha1"));
961 git(&remote, &["init", "-q", "--bare", "--template=", &fmt, "."]);
962 let work = match object_format {
963 None => repo(&format!("{name}-work")),
964 Some(f) => {
965 let w = dir(&format!("{name}-work"));
966 let fmt = format!("--object-format={f}");
967 git(&w, &["init", "-q", "--template=", &fmt, "."]);
968 git(&w, &["config", "user.email", "t@t.test"]);
969 git(&w, &["config", "user.name", "t"]);
970 w
971 }
972 };
973 git(
974 &work,
975 &["remote", "add", "origin", remote.to_str().unwrap()],
976 );
977 git(&work, &["config", "greengate.attest", "true"]);
978 git(
979 &work,
980 &["config", "greengate.attestKey", key.to_str().unwrap()],
981 );
982 std::fs::write(work.join("README.md"), "words").unwrap();
983 std::fs::create_dir_all(work.join("docs/plans")).unwrap();
984 std::fs::write(work.join("docs/plans/p.md"), "# P\n").unwrap();
985 git(&work, &["add", "README.md", "docs/plans/p.md"]);
986 git(&work, &["commit", "-qm", "docs: words"]);
987 let head = git(&work, &["rev-parse", "HEAD"]);
988 let tree = git(&work, &["rev-parse", "HEAD^{tree}"]);
989 (d, work, remote, head, tree, signers)
990 }
991
992 fn record(head: &str, tree: &str) -> String {
993 format!(
994 "{PROVENANCE_FORMAT}\ncommit {head}\ntree {tree}\n\
995 plan docs/plans/p.md {}\nreview reviewed {}\npreview not-required\n\
996 producer amont-agent 0.0.0\n",
997 "a".repeat(64),
998 "c".repeat(64)
999 )
1000 }
1001
1002 fn canon_by_hand(work: &Path, tree: &str) -> String {
1006 let listing = git(
1007 work,
1008 &[
1009 "-c",
1010 "core.quotePath=true",
1011 "ls-tree",
1012 "-r",
1013 "--full-tree",
1014 tree,
1015 ],
1016 );
1017 let mut text = String::new();
1018 for line in listing.lines() {
1019 let (head, path) = line.split_once('\t').unwrap();
1020 let f: Vec<&str> = head.split(' ').collect();
1021 let plan = matches!(f[0], "100644" | "100755")
1022 && (path.starts_with("docs/plans/") || path.starts_with("\"docs/plans/"));
1023 if plan {
1024 text.push_str(&format!(
1025 "{} {} {}\t{path}\n",
1026 f[0],
1027 f[1],
1028 "0".repeat(f[2].len())
1029 ));
1030 } else {
1031 text.push_str(&format!("{line}\n"));
1032 }
1033 }
1034 let mut child = std::process::Command::new("git")
1035 .arg("-C")
1036 .arg(work)
1037 .args(["hash-object", "--stdin"])
1038 .stdin(Stdio::piped())
1039 .stdout(Stdio::piped())
1040 .spawn()
1041 .unwrap();
1042 child
1043 .stdin
1044 .take()
1045 .unwrap()
1046 .write_all(text.as_bytes())
1047 .unwrap();
1048 let out = child.wait_with_output().unwrap();
1049 String::from_utf8_lossy(&out.stdout).trim().to_string()
1050 }
1051
1052 fn provenance_payload(remote: &Path, object: &str) -> (String, String) {
1054 let note = git(remote, &["notes", "--ref", PROVENANCE_REF, "show", object]);
1055 let (p, sig) = note
1056 .split_once("\n\n")
1057 .expect("payload, blank line, signature");
1058 (format!("{p}\n"), sig.to_string())
1059 }
1060
1061 fn push_of(head: &str) -> PushRef {
1062 PushRef {
1063 local_ref: "refs/heads/feat/x".into(),
1064 local_oid: head.to_string(),
1065 remote_ref: "refs/heads/feat/x".into(),
1066 remote_oid: "0".repeat(40),
1067 }
1068 }
1069
1070 #[test]
1074 fn a_provenance_payload_is_signed_and_published_by_tree_and_commit() {
1075 let (d, work, remote, head, tree, signers) = provenance_world("prov-e2e");
1076 let payloads = d.join("payloads");
1077 std::fs::create_dir_all(&payloads).unwrap();
1078 let file = payloads.join(&head);
1079 let body = record(&head, &tree);
1080 std::fs::write(&file, &body).unwrap();
1081 let gates = ["pre-push-cargo-test".to_string()];
1082 in_repo(&work, || {
1083 attest_push(&test_settings(), "origin", &[push_of(&head)], &gates, &[])
1084 });
1085 let attested = git(&remote, &["notes", "--ref", NOTES_REF, "show", &head]);
1086 in_repo(&work, || {
1087 provenance_push_from(&payloads, "origin", &[push_of(&head)])
1088 });
1089 let canon = canon_by_hand(&work, &tree);
1092 assert_ne!(
1093 canon, tree,
1094 "the tree carries a plan, so canon(T) is not its oid"
1095 );
1096 let signed = body.replacen(
1097 &format!("tree {tree}\n"),
1098 &format!("tree {tree}\ncanon {canon}\n"),
1099 1,
1100 );
1101 for object in [&head, &tree] {
1102 let (p, sig) = provenance_payload(&remote, object);
1103 assert_eq!(p, signed, "the payload, with canon(T) inserted, is signed");
1104 assert_eq!(p.lines().nth(3), Some(format!("canon {canon}").as_str()));
1105 assert!(verify_in(
1106 PROVENANCE_NAMESPACE,
1107 &p,
1108 &sig,
1109 &signers,
1110 "t@t.test"
1111 ));
1112 assert!(
1113 !verify_in(NAMESPACE, &p, &sig, &signers, "t@t.test"),
1114 "a provenance signature is never an attestation"
1115 );
1116 }
1117 assert!(!file.exists(), "a published payload is deleted");
1118 assert_eq!(
1119 git(&remote, &["notes", "--ref", NOTES_REF, "show", &head]),
1120 attested,
1121 "the attestation note is byte-identical with a provenance payload present"
1122 );
1123 let _ = std::fs::remove_dir_all(&d);
1124 let _ = std::fs::remove_dir_all(&work);
1125 }
1126
1127 #[test]
1128 fn a_payload_for_another_tree_is_neither_signed_nor_deleted() {
1129 let (d, work, remote, head, _tree, _) = provenance_world("prov-mismatch");
1130 let payloads = d.join("payloads");
1131 std::fs::create_dir_all(&payloads).unwrap();
1132 let file = payloads.join(&head);
1133 std::fs::write(&file, record(&head, &"b".repeat(40))).unwrap();
1134 in_repo(&work, || {
1135 provenance_push_from(&payloads, "origin", &[push_of(&head)])
1136 });
1137 assert!(file.exists(), "a mismatched payload is kept");
1138 let refs = git(&remote, &["for-each-ref", PROVENANCE_FULL_REF]);
1139 assert!(refs.is_empty(), "nothing was published: {refs}");
1140 let _ = std::fs::remove_dir_all(&d);
1141 let _ = std::fs::remove_dir_all(&work);
1142 }
1143
1144 #[test]
1147 fn a_payload_with_a_canon_line_is_refused_and_kept() {
1148 let (d, work, remote, head, tree, _) = provenance_world("prov-canon");
1149 let payloads = d.join("payloads");
1150 std::fs::create_dir_all(&payloads).unwrap();
1151 let file = payloads.join(&head);
1152 let old = record(&head, &tree).replacen(
1153 &format!("tree {tree}\n"),
1154 &format!("tree {tree}\ncanon {}\n", "c".repeat(64)),
1155 1,
1156 );
1157 std::fs::write(&file, &old).unwrap();
1158 in_repo(&work, || {
1159 provenance_push_from(&payloads, "origin", &[push_of(&head)])
1160 });
1161 assert_eq!(
1162 std::fs::read_to_string(&file).unwrap(),
1163 old,
1164 "kept as it was"
1165 );
1166 let refs = git(&remote, &["for-each-ref", PROVENANCE_FULL_REF]);
1167 assert!(refs.is_empty(), "nothing was published: {refs}");
1168 let _ = std::fs::remove_dir_all(&d);
1169 let _ = std::fs::remove_dir_all(&work);
1170 }
1171
1172 #[test]
1175 fn the_canon_refusal_fits_in_80_columns() {
1176 for commit in [
1177 "9f1c2ab0d6e4c1b2a3f405e6d7c8b9a0f1e2d3c4".to_string(),
1178 "e".repeat(64),
1179 ] {
1180 let file = PathBuf::from("/Users/someone/.claude/amont-agent/provenance/amont-agent")
1181 .join(&commit);
1182 let lines = canon_refusal(&commit, &file);
1183 assert!(lines[0].starts_with(" provenance for "), "{lines:?}");
1184 assert!(lines[0].contains(&commit[..7]), "{lines:?}");
1185 let all = lines.join("\n");
1186 assert!(all.contains("canon line") && all.contains("pre-release amont-agent"));
1187 assert!(all.contains(&format!(" {commit} in\n")), "{all}");
1188 assert!(all.contains("upgrade amont-agent"), "{all}");
1189 for l in &lines {
1190 assert!(
1191 l.chars().count() <= 80,
1192 "{} columns: {l}",
1193 l.chars().count()
1194 );
1195 }
1196 }
1197 }
1198
1199 #[test]
1201 fn a_failed_canon_keeps_the_payload() {
1202 let (d, work, remote, head, tree, _) = provenance_world("prov-nocanon");
1203 let docs = git(&work, &["rev-parse", &format!("{tree}:docs")]);
1205 let objects = PathBuf::from(git(&work, &["rev-parse", "--git-path", "objects"]));
1206 let objects = if objects.is_absolute() {
1207 objects
1208 } else {
1209 work.join(objects)
1210 };
1211 std::fs::remove_file(objects.join(&docs[..2]).join(&docs[2..])).unwrap();
1212 let payloads = d.join("payloads");
1213 std::fs::create_dir_all(&payloads).unwrap();
1214 let file = payloads.join(&head);
1215 std::fs::write(&file, record(&head, &tree)).unwrap();
1216 in_repo(&work, || {
1217 assert_eq!(canon(&tree), None);
1218 provenance_push_from(&payloads, "origin", &[push_of(&head)])
1219 });
1220 assert!(file.exists(), "a payload without a canon is kept");
1221 let refs = git(&remote, &["for-each-ref", PROVENANCE_FULL_REF]);
1222 assert!(refs.is_empty(), "nothing was published: {refs}");
1223 let _ = std::fs::remove_dir_all(&d);
1224 let _ = std::fs::remove_dir_all(&work);
1225 }
1226
1227 #[test]
1230 fn a_sha256_repository_signs_a_64_hex_canon() {
1231 let (d, work, remote, head, tree, _) = provenance_world_in("prov-sha256", Some("sha256"));
1232 assert_eq!(tree.len(), 64);
1233 let payloads = d.join("payloads");
1234 std::fs::create_dir_all(&payloads).unwrap();
1235 std::fs::write(payloads.join(&head), record(&head, &tree)).unwrap();
1236 in_repo(&work, || {
1237 provenance_push_from(&payloads, "origin", &[push_of(&head)])
1238 });
1239 let (p, _) = provenance_payload(&remote, &head);
1240 let canon = canon_by_hand(&work, &tree);
1241 assert_eq!(canon.len(), 64);
1242 assert_eq!(
1243 p.lines().nth(3),
1244 Some(format!("canon {canon}").as_str()),
1245 "{p}"
1246 );
1247 let _ = std::fs::remove_dir_all(&d);
1248 let _ = std::fs::remove_dir_all(&work);
1249 }
1250
1251 #[test]
1252 fn a_failed_publish_keeps_the_payload_for_the_next_push() {
1253 let (d, work, _remote, head, tree, _) = provenance_world("prov-fail");
1254 git(
1255 &work,
1256 &[
1257 "remote",
1258 "set-url",
1259 "origin",
1260 d.join("gone.git").to_str().unwrap(),
1261 ],
1262 );
1263 let payloads = d.join("payloads");
1264 std::fs::create_dir_all(&payloads).unwrap();
1265 let file = payloads.join(&head);
1266 std::fs::write(&file, record(&head, &tree)).unwrap();
1267 in_repo(&work, || {
1268 provenance_push_from(&payloads, "origin", &[push_of(&head)])
1269 });
1270 assert!(file.exists(), "an unpublished payload is kept");
1271 let _ = std::fs::remove_dir_all(&d);
1272 let _ = std::fs::remove_dir_all(&work);
1273 }
1274
1275 #[test]
1278 fn a_config_key_cannot_point_amont_at_other_payloads() {
1279 let (d, work, remote, head, tree, _) = provenance_world("prov-config");
1280 let elsewhere = d.join("elsewhere");
1281 let name = work.file_name().unwrap().to_string_lossy().into_owned();
1282 std::fs::create_dir_all(elsewhere.join(&name)).unwrap();
1283 std::fs::write(elsewhere.join(&name).join(&head), record(&head, &tree)).unwrap();
1284 for key in ["greengate.provenanceDir", "amont.agent.provenanceDir"] {
1285 git(&work, &["config", key, elsewhere.to_str().unwrap()]);
1286 }
1287 in_repo(&work, || {
1288 provenance_push(&test_settings(), "origin", &[push_of(&head)])
1289 });
1290 let refs = git(&remote, &["for-each-ref", PROVENANCE_FULL_REF]);
1291 assert!(refs.is_empty(), "a configured directory was read: {refs}");
1292 let _ = std::fs::remove_dir_all(&d);
1293 let _ = std::fs::remove_dir_all(&work);
1294 }
1295
1296 #[test]
1297 fn no_payload_publishes_nothing() {
1298 let (d, work, remote, head, _, _) = provenance_world("prov-none");
1299 let payloads = d.join("payloads");
1300 std::fs::create_dir_all(&payloads).unwrap();
1301 in_repo(&work, || {
1302 provenance_push_from(&payloads, "origin", &[push_of(&head)])
1303 });
1304 let refs = git(&remote, &["for-each-ref", PROVENANCE_FULL_REF]);
1305 assert!(refs.is_empty(), "{refs}");
1306 let _ = std::fs::remove_dir_all(&d);
1307 let _ = std::fs::remove_dir_all(&work);
1308 }
1309
1310 #[test]
1311 fn a_missing_key_signs_nothing() {
1312 assert!(sign("anything", Path::new("/nonexistent/key")).is_none());
1313 }
1314
1315 #[test]
1319 fn an_enabled_push_leaves_a_verifiable_note_on_the_remote() {
1320 let d = dir("e2e");
1321 let (key, signers) = keypair(&d);
1322 let remote = d.join("remote.git");
1323 std::fs::create_dir_all(&remote).unwrap();
1324 git(&remote, &["init", "-q", "--bare", "--template=", "."]);
1325 let work = repo("e2e-work");
1326 git(
1327 &work,
1328 &["remote", "add", "origin", remote.to_str().unwrap()],
1329 );
1330 git(&work, &["config", "greengate.attest", "true"]);
1331 git(
1332 &work,
1333 &["config", "greengate.attestKey", key.to_str().unwrap()],
1334 );
1335 std::fs::write(work.join("a.ts"), "x").unwrap();
1336 git(&work, &["add", "a.ts"]);
1337 git(&work, &["commit", "-qm", "chore: a"]);
1338 let head = git(&work, &["rev-parse", "HEAD"]);
1339 let tree = git(&work, &["rev-parse", "HEAD^{tree}"]);
1340 let push_ref = PushRef {
1341 local_ref: "refs/heads/main".into(),
1342 local_oid: head.clone(),
1343 remote_ref: "refs/heads/main".into(),
1344 remote_oid: "0".repeat(40),
1345 };
1346 in_repo(&work, || {
1347 attest_push(
1348 &test_settings(),
1349 "origin",
1350 &[push_ref],
1351 &["pre-push-run-tests-js".into()],
1352 &[],
1353 );
1354 });
1355 let body = git(&remote, &["notes", "--ref", NOTES_REF, "show", &head]);
1357 assert!(!body.is_empty(), "no note reached the remote");
1358 let (p, sig) = body
1359 .split_once("\n\n")
1360 .expect("payload, blank line, signature");
1361 let p = format!("{p}\n"); assert!(p.starts_with(FORMAT));
1363 assert!(
1364 p.contains(&format!("tree {tree}")),
1365 "attests the pushed tree"
1366 );
1367 assert!(
1368 verify(&p, sig, &signers, "t@t.test"),
1369 "the remote copy verifies"
1370 );
1371 let _ = std::fs::remove_dir_all(&d);
1372 let _ = std::fs::remove_dir_all(&work);
1373 }
1374
1375 #[test]
1382 fn a_push_with_a_spec_publishes_the_inputs_ref() {
1383 let (_d, work, remote, _) = remote_and_work("inputs");
1384 std::fs::create_dir_all(work.join(".github")).unwrap();
1385 std::fs::write(
1386 work.join(".github/attest-inputs"),
1387 "pre-push-run-tests-js a.ts\n",
1388 )
1389 .unwrap();
1390 git(&work, &["add", ".github/attest-inputs"]);
1391 git(&work, &["commit", "-qm", "chore: spec"]);
1392 in_repo(&work, || {
1393 attest_push(
1394 &test_settings(),
1395 "origin",
1396 &[push_ref_for(&work)],
1397 &["pre-push-run-tests-js".into()],
1398 &[],
1399 );
1400 });
1401 let listed = git(&remote, &["notes", "--ref", INPUTS_REF, "list"]);
1402 assert!(
1404 !listed.trim().is_empty(),
1405 "the inputs ref reached the remote"
1406 );
1407 }
1408
1409 #[test]
1410 fn no_opt_in_means_no_note() {
1411 let d = dir("optout");
1412 let (key, _) = keypair(&d);
1413 let remote = d.join("remote.git");
1414 std::fs::create_dir_all(&remote).unwrap();
1415 git(&remote, &["init", "-q", "--bare", "--template=", "."]);
1416 let work = repo("optout-work");
1417 git(
1418 &work,
1419 &["remote", "add", "origin", remote.to_str().unwrap()],
1420 );
1421 git(
1422 &work,
1423 &["config", "greengate.attestKey", key.to_str().unwrap()],
1424 );
1425 std::fs::write(work.join("a.ts"), "x").unwrap();
1426 git(&work, &["add", "a.ts"]);
1427 git(&work, &["commit", "-qm", "chore: a"]);
1428 let head = git(&work, &["rev-parse", "HEAD"]);
1429 let push_ref = PushRef {
1430 local_ref: "refs/heads/main".into(),
1431 local_oid: head.clone(),
1432 remote_ref: "refs/heads/main".into(),
1433 remote_oid: "0".repeat(40),
1434 };
1435 in_repo(&work, || {
1436 attest_push(
1437 &test_settings(),
1438 "origin",
1439 &[push_ref],
1440 &["pre-push-run-tests-js".into()],
1441 &[],
1442 );
1443 });
1444 assert!(
1445 git(&remote, &["notes", "--ref", NOTES_REF, "list"]).is_empty(),
1446 "an un-opted-in repo attested something"
1447 );
1448 let _ = std::fs::remove_dir_all(&d);
1449 let _ = std::fs::remove_dir_all(&work);
1450 }
1451
1452 #[test]
1455 fn deletions_and_empty_gates_attest_nothing() {
1456 let d = dir("nothing");
1457 let (key, _) = keypair(&d);
1458 let remote = d.join("remote.git");
1459 std::fs::create_dir_all(&remote).unwrap();
1460 git(&remote, &["init", "-q", "--bare", "--template=", "."]);
1461 let work = repo("nothing-work");
1462 git(
1463 &work,
1464 &["remote", "add", "origin", remote.to_str().unwrap()],
1465 );
1466 git(&work, &["config", "greengate.attest", "true"]);
1467 git(
1468 &work,
1469 &["config", "greengate.attestKey", key.to_str().unwrap()],
1470 );
1471 std::fs::write(work.join("a.ts"), "x").unwrap();
1472 git(&work, &["add", "a.ts"]);
1473 git(&work, &["commit", "-qm", "chore: a"]);
1474 let head = git(&work, &["rev-parse", "HEAD"]);
1475 let deletion = PushRef {
1476 local_ref: "(delete)".into(),
1477 local_oid: "0".repeat(40),
1478 remote_ref: "refs/heads/gone".into(),
1479 remote_oid: head.clone(),
1480 };
1481 let real = PushRef {
1482 local_ref: "refs/heads/main".into(),
1483 local_oid: head,
1484 remote_ref: "refs/heads/main".into(),
1485 remote_oid: "0".repeat(40),
1486 };
1487 in_repo(&work, || {
1488 attest_push(
1489 &test_settings(),
1490 "origin",
1491 &[deletion],
1492 &["pre-push-pytest".into()],
1493 &[],
1494 );
1495 attest_push(&test_settings(), "origin", &[real], &[], &[]);
1496 });
1497 assert!(git(&remote, &["notes", "--ref", NOTES_REF, "list"]).is_empty());
1498 let _ = std::fs::remove_dir_all(&d);
1499 let _ = std::fs::remove_dir_all(&work);
1500 }
1501
1502 #[test]
1509 fn a_rejection_is_a_note_whose_signature_did_not_verify() {
1510 let trail: Vec<String> = [
1511 "note on abc123: signature did not verify for principal t@t.test",
1512 "note on abc123 block 2: no principal matched",
1513 "note on def456 carries no signature block",
1514 "attested tree abc is not the checked-out tree def and neither its canonical tree nor an input fingerprint of abc123 matches",
1515 "no attestation found for tree abc",
1516 ]
1517 .iter()
1518 .map(|s| s.to_string())
1519 .collect();
1520 assert_eq!(
1521 signature_rejections(&trail),
1522 vec![
1523 "note on abc123: signature did not verify for principal t@t.test".to_string(),
1524 "note on abc123 block 2: no principal matched".to_string(),
1525 ]
1526 );
1527 }
1528
1529 #[test]
1530 fn covered_answers_in_a_fresh_clone_and_rejects_drift_and_forgery() {
1531 let d = dir("covered");
1532 let (key, signers) = keypair(&d);
1533 let remote = d.join("remote.git");
1534 std::fs::create_dir_all(&remote).unwrap();
1535 git(&remote, &["init", "-q", "--bare", "--template=", "."]);
1536 git(&remote, &["symbolic-ref", "HEAD", "refs/heads/main"]);
1542 let work = repo("covered-work");
1543 git(
1544 &work,
1545 &["remote", "add", "origin", remote.to_str().unwrap()],
1546 );
1547 git(&work, &["config", "greengate.attest", "true"]);
1548 git(
1549 &work,
1550 &["config", "greengate.attestKey", key.to_str().unwrap()],
1551 );
1552 std::fs::write(work.join("a.ts"), "x").unwrap();
1553 git(&work, &["add", "a.ts"]);
1554 git(&work, &["commit", "-qm", "chore: a"]);
1555 git(&work, &["push", "-q", "origin", "HEAD:main"]);
1556 let head = git(&work, &["rev-parse", "HEAD"]);
1557 let push_ref = PushRef {
1558 local_ref: "refs/heads/main".into(),
1559 local_oid: head.clone(),
1560 remote_ref: "refs/heads/main".into(),
1561 remote_oid: "0".repeat(40),
1562 };
1563 in_repo(&work, || {
1564 attest_push(
1565 &test_settings(),
1566 "origin",
1567 &[push_ref],
1568 &["pre-push-pytest".into()],
1569 &[],
1570 );
1571 });
1572 let clone = d.join("ci-checkout");
1573 git(
1574 &d,
1575 &[
1576 "clone",
1577 "-q",
1578 "--template=",
1579 remote.to_str().unwrap(),
1580 clone.to_str().unwrap(),
1581 ],
1582 );
1583 in_repo(&clone, || {
1584 assert_eq!(
1585 covered(&signers, Some("t@t.test"), Some(&platform()), &[]).as_deref(),
1586 Some("pre-push-pytest"),
1587 "a fresh clone verifies the attestation and reads the gates"
1588 );
1589 assert_eq!(
1590 covered(&signers, Some("t@t.test"), None, &[]).as_deref(),
1591 Some("pre-push-pytest"),
1592 "`any` covers a platform-independent suite"
1593 );
1594 assert_eq!(
1597 covered(&signers, Some("t@t.test"), Some("s390x-aix"), &[]),
1598 None,
1599 "a pass on one platform is not evidence about another"
1600 );
1601 assert_eq!(
1602 covered(&signers, Some("someone@else.test"), None, &[]),
1603 None,
1604 "an unlisted principal covers nothing"
1605 );
1606 });
1607 std::fs::write(clone.join("b.ts"), "y").unwrap();
1609 git(&clone, &["config", "user.email", "t@t.test"]);
1610 git(&clone, &["config", "user.name", "t"]);
1611 git(&clone, &["add", "b.ts"]);
1612 git(&clone, &["commit", "-qm", "chore: b"]);
1613 in_repo(&clone, || {
1614 assert_eq!(
1615 covered(&signers, Some("t@t.test"), None, &[]),
1616 None,
1617 "drifted tree"
1618 );
1619 });
1620 let head_tree = git(&work, &["rev-parse", "HEAD^{tree}"]);
1630 for object in [&head, &head_tree] {
1631 git(
1632 &work,
1633 &[
1634 "notes", "--ref", NOTES_REF, "add", "-f", "-m", "garbage", object,
1635 ],
1636 );
1637 }
1638 git(
1639 &work,
1640 &[
1641 "push",
1642 "-q",
1643 "origin",
1644 &format!("+{NOTES_FULL_REF}:{NOTES_FULL_REF}"),
1645 ],
1646 );
1647 git(
1651 &work,
1652 &["push", "-q", "origin", &format!(":{INPUTS_FULL_REF}")],
1653 );
1654 git(&clone, &["reset", "-q", "--hard", &head]);
1655 in_repo(&clone, || {
1656 assert_eq!(
1657 covered(&signers, Some("t@t.test"), None, &[]),
1658 None,
1659 "a foreign note is not a stamp"
1660 );
1661 });
1662 let _ = std::fs::remove_dir_all(&d);
1663 let _ = std::fs::remove_dir_all(&work);
1664 }
1665
1666 #[test]
1672 fn default_signers_is_found_from_a_subdirectory() {
1673 let work = repo("signers-subdir");
1674 std::fs::create_dir_all(work.join(".forgejo")).unwrap();
1675 std::fs::write(work.join(".forgejo/allowed_signers"), "t@t.test x\n").unwrap();
1676 let sub = work.join("packages").join("thing");
1677 std::fs::create_dir_all(&sub).unwrap();
1678 in_repo(&sub, || {
1679 let found = default_signers().expect("resolved from the repo root, not the cwd");
1680 assert!(found.ends_with(".forgejo/allowed_signers"));
1681 assert!(found.exists(), "the path it returns must be usable as-is");
1682 });
1683 let _ = std::fs::remove_dir_all(&work);
1684 }
1685
1686 #[test]
1687 fn zero_oids_of_any_width_are_zero() {
1688 assert!(is_zero(&"0".repeat(40)));
1689 assert!(is_zero(&"0".repeat(64)));
1690 assert!(!is_zero("0a0000"));
1691 assert!(!is_zero(""));
1692 }
1693
1694 #[test]
1695 fn forget_removes_the_local_ref() {
1696 let work = repo("forget");
1697 std::fs::write(work.join("a.ts"), "x").unwrap();
1698 git(&work, &["add", "a.ts"]);
1699 git(&work, &["commit", "-qm", "chore: a"]);
1700 git(
1701 &work,
1702 &["notes", "--ref", NOTES_REF, "add", "-m", "x", "HEAD"],
1703 );
1704 in_repo(&work, forget);
1705 assert!(git(&work, &["notes", "--ref", NOTES_REF, "list"]).is_empty());
1706 let _ = std::fs::remove_dir_all(&work);
1707 }
1708
1709 }