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
49const READ_NAMES: [git_attest::format::Names; 2] =
55 [git_attest::format::GREEN, git_attest::format::LEGACY];
56
57pub const NOTES_FULL_REF: &str = "refs/notes/greengate-attest";
60pub const INPUTS_FULL_REF: &str = "refs/notes/greengate-attest-inputs";
61
62const PROVENANCE_LEGACY_FORMAT: &str = "amont-provenance-v1";
67
68pub const PROVENANCE_REF: &str = "greengate-provenance";
74pub const PROVENANCE_FULL_REF: &str = "refs/notes/greengate-provenance";
75pub const PROVENANCE_NAMESPACE: &str = "greengate-provenance";
76pub const PROVENANCE_FORMAT: &str = "greengate-provenance-v1";
77
78pub const PUSH_GUARD: &str = "GREENGATE_ATTEST_PUSH";
81
82fn here() -> &'static Path {
84 Path::new(".")
85}
86
87const TOGGLE: &str = "greengate.attest";
91
92pub(crate) const KEY_CONFIG: &str = "greengate.attestKey";
94const KEY_DEFAULT: &str = ".ssh/greengate-attest";
96const KEY_FALLBACK: &str = ".ssh/amont-attest";
99
100pub fn push_guard_active() -> bool {
102 std::env::var_os(PUSH_GUARD).is_some()
103}
104
105pub fn enabled(settings: &crate::config::Settings) -> bool {
107 crate::config::boolean_or(settings, TOGGLE, false)
108}
109
110fn key_path() -> Option<PathBuf> {
117 if let Some(k) = crate::git::stdout(&["config", "--get", KEY_CONFIG]) {
118 if !k.is_empty() {
119 return Some(PathBuf::from(k));
120 }
121 }
122 let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE"))?;
123 Some(default_key_in(Path::new(&home)))
124}
125
126fn default_key_in(home: &Path) -> PathBuf {
130 let green = home.join(KEY_DEFAULT);
131 let old = home.join(KEY_FALLBACK);
132 if !green.exists() && old.exists() {
133 old
134 } else {
135 green
136 }
137}
138
139pub fn key_move_hint_in(home: &Path) -> Option<String> {
143 (!home.join(KEY_DEFAULT).exists() && home.join(KEY_FALLBACK).exists()).then(|| {
144 format!(
145 "the signing key is still ~/{KEY_FALLBACK}; rename it: mv ~/{KEY_FALLBACK} ~/{KEY_DEFAULT} (and the .pub beside it)"
146 )
147 })
148}
149
150pub fn attest_push(
178 settings: &crate::config::Settings,
179 remote: &str,
180 refs: &[PushRef],
181 gates: &[String],
182 cluster_gates: &[String],
183) {
184 attest_push_per_tip(settings, remote, refs, &|_| gates.to_vec(), cluster_gates);
185}
186
187pub fn attest_push_per_tip(
192 settings: &crate::config::Settings,
193 remote: &str,
194 refs: &[PushRef],
195 gates_for: &dyn Fn(&str) -> Vec<String>,
196 cluster_gates: &[String],
197) {
198 if remote.is_empty() || !enabled(settings) {
199 return;
200 }
201 let Some(key) = key_path() else { return };
202 if !key.exists() {
203 crate::config::complain(
204 TOGGLE,
205 &format!("signing key {} does not exist", key.display()),
206 "no attestation (CI will run the tests)",
207 );
208 return;
209 }
210 let producer = env!("CARGO_PKG_VERSION");
211 let mut laptop_signed: Vec<String> = Vec::new();
213 let mut blocks: Vec<(String, String)> = Vec::new();
214 let mut input_blocks: Vec<(String, String)> = Vec::new();
215 let mut linux_signed: Vec<String> = Vec::new();
216 let (mut n_inputs, mut n_canon) = (0, 0);
217 let in_cluster = std::cell::OnceCell::new();
219 for r in refs {
220 if is_zero(&r.local_oid) {
221 continue; }
223 let gates = gates_for(&r.local_oid);
224 if gates.is_empty() && cluster_gates.is_empty() {
225 continue;
226 }
227 let gates_line = gates.join(" ");
228 let spec = format!("{}^{{tree}}", r.local_oid);
229 let Some(tree) = crate::git::stdout(&["rev-parse", &spec]) else {
230 continue;
231 };
232 let mut proved_here: Vec<String> = cluster_gates
233 .iter()
234 .filter(|g| crate::cluster::proved(g, &tree))
235 .cloned()
236 .collect();
237 if !proved_here.is_empty()
241 && *in_cluster.get_or_init(|| crate::cluster::in_cluster_signer().is_some())
242 {
243 for signed in filed_signer_blocks(&tree) {
244 let (covered, rest): (Vec<String>, Vec<String>) = proved_here
245 .into_iter()
246 .partition(|g| signed.gates.contains(g));
247 proved_here = rest;
248 if covered.is_empty() {
249 continue;
250 }
251 for name in covered {
252 if !linux_signed.contains(&name) {
253 linux_signed.push(name);
254 }
255 }
256 blocks.push((tree.clone(), signed.body.clone()));
257 blocks.push((r.local_oid.clone(), signed.body));
258 }
259 }
260 let platforms = [
261 (platform(), gates_line.clone(), Vec::new()),
262 (
263 crate::cluster::PLATFORM.to_string(),
264 proved_here.join(" "),
265 proved_here,
266 ),
267 ];
268 let mut counted = false;
271 for (on, line, linux_names) in platforms {
272 if line.is_empty() {
273 continue;
274 }
275 let mut reasons = Vec::new();
278 let att = attestation(here(), &tree, &line, &on, producer, &mut reasons);
279 let Ok(sig) = git_attest::sign::sign(NAMESPACE, &att.payload, &key) else {
280 continue;
281 };
282 let body = block(&att.payload, &sig);
283 if !counted {
284 n_inputs += att.inputs.len();
285 n_canon += usize::from(att.canon.is_some());
286 counted = true;
287 }
288 for k in &att.input_keys {
289 input_blocks.push((k.clone(), body.clone()));
290 }
291 blocks.push((tree.clone(), body.clone()));
292 blocks.push((r.local_oid.clone(), body));
293 if linux_names.is_empty() {
294 for name in &gates {
295 if !laptop_signed.contains(name) {
296 laptop_signed.push(name.clone());
297 }
298 }
299 }
300 for name in linux_names {
301 if !linux_signed.contains(&name) {
302 linux_signed.push(name);
303 }
304 }
305 }
306 }
307 if blocks.is_empty() {
308 return;
309 }
310 let main_ok = publish(remote, NOTES_REF, &blocks);
314 let inputs_ok = input_blocks.is_empty() || publish(remote, INPUTS_REF, &input_blocks);
315 if main_ok {
316 let mut signed_on = Vec::new();
319 if !laptop_signed.is_empty() {
320 signed_on.push(format!(
321 "{} on {}",
322 crate::ui::highlight(&laptop_signed.join(" ")),
323 platform()
324 ));
325 }
326 if !linux_signed.is_empty() {
327 signed_on.push(format!(
328 "{} on {}",
329 crate::ui::highlight(&linux_signed.join(" ")),
330 crate::cluster::PLATFORM
331 ));
332 }
333 let what = signed_on.join("; ");
334 crate::say!(
335 "{} attested {} for CI ({}{})",
336 crate::ui::valid_sign(),
337 what,
338 NOTES_REF,
339 if input_blocks.is_empty() {
340 String::new()
341 } else if inputs_ok {
342 match (n_inputs, n_canon) {
343 (0, _) => ", canonical tree".to_string(),
344 (n, 0) => format!(", {n} input fingerprints"),
345 (n, _) => format!(", {n} input fingerprints, canonical tree"),
346 }
347 } else {
348 ", input fingerprints not published".to_string()
349 },
350 );
351 }
352}
353
354fn provenance_dir(env: impl Fn(&str) -> Option<std::ffi::OsString>) -> Option<PathBuf> {
363 let config = match env("CLAUDE_CONFIG_DIR") {
364 Some(d) => PathBuf::from(d),
365 None => PathBuf::from(env("HOME").or_else(|| env("USERPROFILE"))?).join(".claude"),
366 };
367 Some(config.join("amont-agent").join("provenance"))
368}
369
370fn repo_name() -> Option<String> {
375 let common = crate::git::stdout(&["rev-parse", "--git-common-dir"])?;
376 if common.is_empty() {
377 return None;
378 }
379 let common = PathBuf::from(common);
380 let common = if common.is_absolute() {
381 common
382 } else {
383 std::env::current_dir().ok()?.join(common)
384 };
385 let common = std::fs::canonicalize(&common).unwrap_or(common);
386 common
387 .parent()
388 .and_then(std::path::Path::file_name)
389 .map(|n| n.to_string_lossy().into_owned())
390 .filter(|n| !n.is_empty())
391}
392
393pub fn provenance_push(settings: &crate::config::Settings, remote: &str, refs: &[PushRef]) {
398 if remote.is_empty() || !enabled(settings) {
399 return;
400 }
401 let (Some(dir), Some(name)) = (provenance_dir(|k| std::env::var_os(k)), repo_name()) else {
402 return;
403 };
404 provenance_push_from(&dir.join(name), remote, refs);
405}
406
407fn provenance_push_from(dir: &std::path::Path, remote: &str, refs: &[PushRef]) {
409 let mut found: Vec<PendingRecord> = Vec::new();
410 for r in refs {
411 if is_zero(&r.local_oid) {
412 continue;
413 }
414 let file = dir.join(&r.local_oid);
415 let Ok(payload) = std::fs::read_to_string(&file) else {
416 continue; };
418 let spec = format!("{}^{{tree}}", r.local_oid);
419 let Some(tree) = crate::git::stdout(&["rev-parse", &spec]) else {
420 continue;
421 };
422 let first = payload.lines().next().unwrap_or_default();
423 let claimed = payload.lines().find_map(|l| l.strip_prefix("tree "));
424 if first == PROVENANCE_LEGACY_FORMAT {
428 crate::say!("{}", legacy_provenance_line(&r.local_oid, &file));
429 continue;
430 }
431 if first != PROVENANCE_FORMAT || claimed != Some(tree.as_str()) {
432 crate::say!(
433 " provenance for {} not signed: its payload is not a {PROVENANCE_FORMAT} record of this tree",
434 &r.local_oid[..r.local_oid.len().min(7)]
435 );
436 continue;
437 }
438 if payload
442 .lines()
443 .any(|l| l.split_ascii_whitespace().next() == Some("canon"))
444 {
445 for line in canon_refusal(&r.local_oid, &file) {
446 crate::say!("{line}");
447 }
448 continue;
449 }
450 let Ok(canon) = git_attest::fingerprint::canon(here(), &tree) else {
453 crate::say!(
454 " provenance for {} not signed: its canonical tree cannot be computed;",
455 &r.local_oid[..r.local_oid.len().min(7)]
456 );
457 crate::say!(" the payload is kept for the next push");
458 continue;
459 };
460 let payload = with_canon(&payload, &canon);
461 found.push(PendingRecord {
462 file,
463 commit: r.local_oid.clone(),
464 tree,
465 payload,
466 });
467 }
468 if found.is_empty() {
469 return;
470 }
471 let Some(key) = key_path().filter(|k| k.exists()) else {
472 crate::say!(" provenance not signed: no signing key");
473 return;
474 };
475 let mut blocks: Vec<(String, String)> = Vec::new();
476 let mut signed: Vec<PathBuf> = Vec::new();
477 for rec in found {
478 let sig = match git_attest::sign::sign(PROVENANCE_NAMESPACE, &rec.payload, &key) {
479 Ok(sig) => sig,
480 Err(e) => {
481 crate::say!(
482 " provenance for {} not signed: {e}; kept for the next push",
483 &rec.commit[..rec.commit.len().min(7)]
484 );
485 continue;
486 }
487 };
488 let body = block(&rec.payload, &sig);
489 blocks.push((rec.tree, body.clone()));
490 blocks.push((rec.commit, body));
491 signed.push(rec.file);
492 }
493 if blocks.is_empty() {
494 return; }
496 if publish(remote, PROVENANCE_REF, &blocks) {
497 for file in &signed {
498 if std::fs::remove_file(file).is_err() {
499 crate::say!(
500 " provenance published, but its payload {} could not be removed",
501 file.display()
502 );
503 }
504 }
505 crate::say!(
506 "{} provenance published ({PROVENANCE_REF})",
507 crate::ui::valid_sign()
508 );
509 } else {
510 crate::say!(" provenance not published: kept for the next push");
511 }
512}
513
514struct PendingRecord {
516 file: PathBuf,
517 commit: String,
518 tree: String,
519 payload: String,
520}
521
522fn legacy_provenance_line(commit: &str, file: &Path) -> String {
525 format!(
526 " provenance for {} not signed: {} was written by an older greenpiste: upgrade greenpiste, then delete {} or re-run its review",
527 &commit[..commit.len().min(7)],
528 file.display(),
529 file.display()
530 )
531}
532
533fn with_canon(payload: &str, canon: &str) -> String {
536 let mut out = String::with_capacity(payload.len() + canon.len() + 7);
537 let mut done = false;
538 for line in payload.split_inclusive('\n') {
539 out.push_str(line);
540 if !done && line.starts_with("tree ") {
541 if !line.ends_with('\n') {
542 out.push('\n');
543 }
544 out.push_str(&format!("canon {canon}\n"));
545 done = true;
546 }
547 }
548 out
549}
550
551fn canon_refusal(commit: &str, file: &std::path::Path) -> Vec<String> {
555 let dir = file.parent().unwrap_or(file).display().to_string();
556 let name = file
557 .file_name()
558 .map(|n| n.to_string_lossy().into_owned())
559 .unwrap_or_default();
560 vec![
561 format!(
562 " provenance for {} not signed: its payload carries a canon line",
563 &commit[..commit.len().min(7)]
564 ),
565 " (a pre-release amont-agent wrote it); delete the file".to_string(),
566 format!(" {name} in"),
567 format!(" {dir}"),
568 " and upgrade amont-agent".to_string(),
569 ]
570}
571
572const PUSH_ATTEMPTS: u32 = 4;
574
575fn publish(remote: &str, notes_ref: &str, blocks: &[(String, String)]) -> bool {
583 let how = Publish {
584 remote,
585 attempts: PUSH_ATTEMPTS,
586 pause: false,
587 identity: None,
588 push_env: &[(PUSH_GUARD, "1")],
589 };
590 let mut log = Vec::new();
591 matches!(
592 publish_notes(here(), &how, notes_ref, blocks, &mut log),
593 Published::Pushed | Published::AlreadyPresent
594 )
595}
596
597pub fn covered(
610 signers: &Path,
611 principal: Option<&str>,
612 require_platform: Option<&str>,
613 anywhere: &[String],
614) -> Option<String> {
615 covered_in(here(), signers, principal, require_platform, anywhere)
616}
617
618pub fn covered_in(
623 dir: &Path,
624 signers: &Path,
625 principal: Option<&str>,
626 require_platform: Option<&str>,
627 anywhere: &[String],
628) -> Option<String> {
629 covered_report(dir, signers, principal, require_platform, anywhere).gates
630}
631
632#[derive(Debug, Clone, PartialEq, Eq, Default)]
637pub struct Covered {
638 pub gates: Option<String>,
639 pub rejected: Vec<String>,
640}
641
642pub fn covered_report(
646 dir: &Path,
647 signers: &Path,
648 principal: Option<&str>,
649 require_platform: Option<&str>,
650 anywhere: &[String],
651) -> Covered {
652 let verdict =
653 git_attest::verify::evaluate(dir, signers, principal, require_platform, anywhere, false);
654 for line in verdict.loud.iter().chain(&verdict.warnings) {
655 eprintln!("{BIN}: {line}");
656 }
657 for line in verified_lines(&verdict) {
658 eprintln!("{BIN}: {line}");
659 }
660 let rejected = signature_rejections(&verdict.trail);
661 for why in &rejected {
662 eprintln!("{BIN}: an attestation was found but did not verify: {why}");
663 }
664 Covered {
665 gates: (!verdict.gates.is_empty()).then(|| verdict.gates.join(" ")),
666 rejected,
667 }
668}
669
670fn verified_lines(verdict: &git_attest::verify::Verdict) -> Vec<String> {
674 verdict
675 .verified_under
676 .iter()
677 .map(|ns| format!("verified under {ns}"))
678 .collect()
679}
680
681fn signature_rejections(trail: &[String]) -> Vec<String> {
686 trail
687 .iter()
688 .filter(|line| line.starts_with("note on ") && line.contains(": "))
689 .cloned()
690 .collect()
691}
692
693#[derive(Debug, Clone, PartialEq, Eq)]
695pub(crate) struct SignerBlock {
696 pub principal: String,
698 pub gates: Vec<String>,
700 pub body: String,
702 pub names: git_attest::format::Names,
704}
705
706impl SignerBlock {
707 pub(crate) fn is_publishable(&self) -> bool {
711 self.names == git_attest::format::WRITE
712 }
713}
714
715#[derive(Debug, Clone, PartialEq, Eq)]
718pub(crate) enum BlockRefusal {
719 Signer(String),
723 Content(String),
726}
727
728impl BlockRefusal {
729 pub(crate) fn reason(&self) -> &str {
731 match self {
732 BlockRefusal::Signer(why) | BlockRefusal::Content(why) => why,
733 }
734 }
735}
736
737pub(crate) fn signer_block(
743 body: &str,
744 tree: &str,
745 signers: &Path,
746) -> Result<SignerBlock, BlockRefusal> {
747 use git_attest::format::{bound_platform, field, split_blocks};
748 use BlockRefusal::{Content, Signer};
749 let (mut blocks, _) = split_blocks(body);
750 if blocks.len() != 1 {
751 return Err(Content(format!("{} signed blocks, not one", blocks.len())));
752 }
753 let signed_block = blocks.remove(0);
754 let header = signed_block.payload.split('\n').next();
757 let Some(names) = READ_NAMES.into_iter().find(|n| Some(n.format) == header) else {
758 return Err(Content(format!(
759 "not an {} or {} payload",
760 git_attest::format::GREEN.format,
761 git_attest::format::LEGACY.format
762 )));
763 };
764 let on = field(&signed_block.payload, "platform");
765 if on != Some(crate::cluster::PLATFORM) {
766 return Err(Content(format!(
767 "its platform is {}, not {}",
768 on.unwrap_or("missing"),
769 crate::cluster::PLATFORM
770 )));
771 }
772 let claimed = field(&signed_block.payload, "tree");
773 if claimed != Some(tree) {
774 return Err(Content(format!(
776 "it is for tree {}, not {tree}",
777 claimed.unwrap_or("missing")
778 )));
779 }
780 let principal = git_attest::sign::verify(
781 names.namespace,
782 &signed_block.payload,
783 &signed_block.signature,
784 signers,
785 None,
786 )
787 .map_err(|e| Signer(e.to_string()))?;
788 if bound_platform(&principal) != Some(crate::cluster::PLATFORM) {
789 return Err(Signer(format!(
790 "{principal} is not a principal bound to {}",
791 crate::cluster::PLATFORM
792 )));
793 }
794 Ok(SignerBlock {
795 principal,
796 gates: field(&signed_block.payload, "gates")
797 .unwrap_or("")
798 .split_whitespace()
799 .map(str::to_string)
800 .collect(),
801 body: block(&signed_block.payload, &signed_block.signature),
802 names,
803 })
804}
805
806fn signer_notes_ref() -> String {
813 format!("{}{NOTES_REF}", git_attest::format::LOCAL_PREFIX)
814}
815
816pub(crate) fn file_signer_block(body: &str, keys: &[&str]) -> Result<(), String> {
822 let notes_ref = signer_notes_ref();
823 for key in keys {
824 let entry = [((*key).to_string(), body.to_string())];
825 if matches!(
826 git_attest::notes::publish_local(here(), None, ¬es_ref, &entry),
827 Published::Error
828 ) {
829 return Err(format!(
830 "git could not write the note on {key} in {notes_ref}"
831 ));
832 }
833 }
834 Ok(())
835}
836
837fn filed_signer_blocks(tree: &str) -> Vec<SignerBlock> {
841 use git_attest::format::{field, split_blocks};
842 let Some(signers) = default_signers() else {
843 return Vec::new();
844 };
845 let notes_ref = signer_notes_ref();
846 let Some(note) = crate::git::stdout(&["notes", "--ref", ¬es_ref, "show", tree]) else {
847 return Vec::new();
848 };
849 split_blocks(¬e)
850 .0
851 .iter()
852 .filter(|b| {
853 field(&b.payload, "platform") == Some(crate::cluster::PLATFORM)
854 && field(&b.payload, "tree") == Some(tree)
855 })
856 .filter_map(|b| signer_block(&block(&b.payload, &b.signature), tree, &signers).ok())
857 .filter(SignerBlock::is_publishable)
859 .collect()
860}
861
862pub fn default_signers() -> Option<PathBuf> {
865 git_attest::verify::default_signers(here())
866}
867
868fn is_zero(oid: &str) -> bool {
871 !oid.is_empty() && oid.bytes().all(|b| b == b'0')
872}
873
874pub fn forget() -> bool {
878 forget_in(here())
879}
880
881pub fn forget_in(repo: &std::path::Path) -> bool {
883 let mut deleted = false;
884 for names in READ_NAMES {
885 let full = format!("refs/notes/{}", names.notes_ref);
886 deleted |= crate::git::succeeds_in(repo, &["update-ref", "-d", &full]);
887 }
888 deleted
889}
890
891#[cfg(test)]
892pub(crate) mod tests {
893 use super::*;
894
895 use std::process::Stdio;
896
897 pub(crate) fn scratch_cleanup(path: &Path) {
900 let _ = std::fs::remove_dir_all(path); }
902
903 #[test]
907 fn the_written_names_are_green_and_each_full_ref_names_its_ref() {
908 for (full, short) in [
909 (NOTES_FULL_REF, NOTES_REF),
910 (INPUTS_FULL_REF, INPUTS_REF),
911 (PROVENANCE_FULL_REF, PROVENANCE_REF),
912 ] {
913 assert_eq!(full, format!("refs/notes/{short}"));
914 assert!(full.starts_with("refs/notes/greengate-"), "{full}");
915 }
916 assert_eq!(git_attest::format::WRITE, git_attest::format::GREEN);
917 }
918
919 fn canon(tree: &str) -> Option<String> {
920 git_attest::fingerprint::canon(here(), tree).ok()
921 }
922
923 fn sign(payload: &str, key: &Path) -> Option<String> {
924 git_attest::sign::sign(NAMESPACE, payload, key).ok()
925 }
926
927 fn verify(payload: &str, sig: &str, signers: &Path, principal: &str) -> bool {
928 verify_in(NAMESPACE, payload, sig, signers, principal)
929 }
930
931 fn verify_in(
932 namespace: &str,
933 payload: &str,
934 sig: &str,
935 signers: &Path,
936 principal: &str,
937 ) -> bool {
938 git_attest::sign::verify(namespace, payload, sig, signers, Some(principal)).is_ok()
939 }
940
941 fn test_settings() -> crate::config::Settings {
944 crate::config::Settings::default()
945 }
946
947 use std::io::Write;
948 use std::path::Path;
949
950 pub(crate) fn dir(name: &str) -> PathBuf {
954 let d = std::env::temp_dir().join(format!("attest-{name}-{}", std::process::id()));
955 scratch_cleanup(&d);
956 std::fs::create_dir_all(&d).unwrap();
957 d
958 }
959
960 fn git(dir: &Path, args: &[&str]) -> String {
969 let out = std::process::Command::new("git")
970 .arg("-C")
971 .arg(dir)
972 .args(args)
973 .output()
974 .expect("git");
975 assert!(
976 out.status.success(),
977 "fixture: git {args:?} in {} exited {:?}: {}",
978 dir.display(),
979 out.status.code(),
980 String::from_utf8_lossy(&out.stderr).trim()
981 );
982 String::from_utf8_lossy(&out.stdout).trim().to_string()
983 }
984
985 fn repo(name: &str) -> PathBuf {
986 let d = dir(name);
987 git(&d, &["init", "-q", "--template=", "."]);
988 git(&d, &["config", "user.email", "t@t.test"]);
989 git(&d, &["config", "user.name", "t"]);
990 d
991 }
992
993 fn keypair(d: &Path) -> (PathBuf, PathBuf) {
996 let key = d.join("attest_key");
997 let ok = std::process::Command::new("ssh-keygen")
998 .args(["-q", "-t", "ed25519", "-N", "", "-C", "test", "-f"])
999 .arg(&key)
1000 .status()
1001 .expect("ssh-keygen must exist for these tests")
1002 .success();
1003 assert!(ok, "keygen failed");
1004 let pubkey = std::fs::read_to_string(key.with_extension("pub")).unwrap();
1005 let signers = d.join("allowed_signers");
1006 std::fs::write(
1007 &signers,
1008 format!("t@t.test namespaces=\"{NAMESPACE}\" {pubkey}"),
1009 )
1010 .unwrap();
1011 (key, signers)
1012 }
1013
1014 fn in_repo<T>(dir: &Path, f: impl FnOnce() -> T) -> T {
1017 let _guard = crate::TEST_CWD.lock().unwrap_or_else(|p| p.into_inner());
1018 let prev = std::env::current_dir().unwrap();
1019 std::env::set_current_dir(dir).unwrap();
1020 let r = f();
1021 std::env::set_current_dir(prev).unwrap();
1022 r
1023 }
1024
1025 fn remote_and_work(name: &str) -> (PathBuf, PathBuf, PathBuf, PathBuf) {
1027 let d = dir(name);
1028 let (key, signers) = keypair(&d);
1029 let remote = d.join("remote.git");
1030 std::fs::create_dir_all(&remote).unwrap();
1031 git(&remote, &["init", "-q", "--bare", "--template=", "."]);
1032 let work = repo(&format!("{name}-work"));
1033 git(
1034 &work,
1035 &["remote", "add", "origin", remote.to_str().unwrap()],
1036 );
1037 git(&work, &["config", "greengate.attest", "true"]);
1038 git(
1039 &work,
1040 &["config", "greengate.attestKey", key.to_str().unwrap()],
1041 );
1042 std::fs::write(work.join("a.ts"), "x").unwrap();
1043 git(&work, &["add", "a.ts"]);
1044 git(&work, &["commit", "-qm", "chore: a"]);
1045 (d, work, remote, signers)
1046 }
1047
1048 fn push_ref_for(work: &Path) -> PushRef {
1049 PushRef {
1050 local_ref: "refs/heads/main".into(),
1051 local_oid: git(work, &["rev-parse", "HEAD"]),
1052 remote_ref: "refs/heads/main".into(),
1053 remote_oid: "0".repeat(40),
1054 }
1055 }
1056
1057 #[test]
1058 fn the_provenance_dir_is_resolved_like_amont_agents_config_dir() {
1059 use std::ffi::OsString;
1060 let env = |pairs: &'static [(&'static str, &'static str)]| {
1061 move |k: &str| {
1062 pairs
1063 .iter()
1064 .find(|(n, _)| *n == k)
1065 .map(|(_, v)| OsString::from(v))
1066 }
1067 };
1068 assert_eq!(
1069 provenance_dir(env(&[("CLAUDE_CONFIG_DIR", "/c"), ("HOME", "/h")])),
1070 Some(PathBuf::from("/c/amont-agent/provenance"))
1071 );
1072 assert_eq!(
1073 provenance_dir(env(&[("HOME", "/h"), ("USERPROFILE", "/u")])),
1074 Some(PathBuf::from("/h/.claude/amont-agent/provenance"))
1075 );
1076 assert_eq!(
1077 provenance_dir(env(&[("USERPROFILE", "/u")])),
1078 Some(PathBuf::from("/u/.claude/amont-agent/provenance"))
1079 );
1080 assert_eq!(provenance_dir(env(&[])), None);
1081 }
1082
1083 fn provenance_world(name: &str) -> (PathBuf, PathBuf, PathBuf, String, String, PathBuf) {
1087 provenance_world_in(name, None)
1088 }
1089
1090 fn provenance_world_in(
1092 name: &str,
1093 object_format: Option<&str>,
1094 ) -> (PathBuf, PathBuf, PathBuf, String, String, PathBuf) {
1095 let d = dir(name);
1096 let (key, _) = keypair(&d);
1097 let pubkey = std::fs::read_to_string(key.with_extension("pub")).unwrap();
1098 let signers = d.join("allowed_signers_provenance");
1099 std::fs::write(
1100 &signers,
1101 format!("t@t.test namespaces=\"{NAMESPACE},{PROVENANCE_NAMESPACE}\" {pubkey}"),
1102 )
1103 .unwrap();
1104 let remote = d.join("remote.git");
1105 std::fs::create_dir_all(&remote).unwrap();
1106 let fmt = format!("--object-format={}", object_format.unwrap_or("sha1"));
1107 git(&remote, &["init", "-q", "--bare", "--template=", &fmt, "."]);
1108 let work = match object_format {
1109 None => repo(&format!("{name}-work")),
1110 Some(f) => {
1111 let w = dir(&format!("{name}-work"));
1112 let fmt = format!("--object-format={f}");
1113 git(&w, &["init", "-q", "--template=", &fmt, "."]);
1114 git(&w, &["config", "user.email", "t@t.test"]);
1115 git(&w, &["config", "user.name", "t"]);
1116 w
1117 }
1118 };
1119 git(
1120 &work,
1121 &["remote", "add", "origin", remote.to_str().unwrap()],
1122 );
1123 git(&work, &["config", "greengate.attest", "true"]);
1124 git(
1125 &work,
1126 &["config", "greengate.attestKey", key.to_str().unwrap()],
1127 );
1128 std::fs::write(work.join("README.md"), "words").unwrap();
1129 std::fs::create_dir_all(work.join("docs/plans")).unwrap();
1130 std::fs::write(work.join("docs/plans/p.md"), "# P\n").unwrap();
1131 git(&work, &["add", "README.md", "docs/plans/p.md"]);
1132 git(&work, &["commit", "-qm", "docs: words"]);
1133 let head = git(&work, &["rev-parse", "HEAD"]);
1134 let tree = git(&work, &["rev-parse", "HEAD^{tree}"]);
1135 (d, work, remote, head, tree, signers)
1136 }
1137
1138 fn record(head: &str, tree: &str) -> String {
1139 format!(
1140 "{PROVENANCE_FORMAT}\ncommit {head}\ntree {tree}\n\
1141 plan docs/plans/p.md {}\nreview reviewed {}\npreview not-required\n\
1142 producer amont-agent 0.0.0\n",
1143 "a".repeat(64),
1144 "c".repeat(64)
1145 )
1146 }
1147
1148 fn canon_by_hand(work: &Path, tree: &str) -> String {
1152 let listing = git(
1153 work,
1154 &[
1155 "-c",
1156 "core.quotePath=true",
1157 "ls-tree",
1158 "-r",
1159 "--full-tree",
1160 tree,
1161 ],
1162 );
1163 let mut text = String::new();
1164 for line in listing.lines() {
1165 let (head, path) = line.split_once('\t').unwrap();
1166 let f: Vec<&str> = head.split(' ').collect();
1167 let plan = matches!(f[0], "100644" | "100755")
1168 && (path.starts_with("docs/plans/") || path.starts_with("\"docs/plans/"));
1169 if plan {
1170 text.push_str(&format!(
1171 "{} {} {}\t{path}\n",
1172 f[0],
1173 f[1],
1174 "0".repeat(f[2].len())
1175 ));
1176 } else {
1177 text.push_str(&format!("{line}\n"));
1178 }
1179 }
1180 let mut child = std::process::Command::new("git")
1181 .arg("-C")
1182 .arg(work)
1183 .args(["hash-object", "--stdin"])
1184 .stdin(Stdio::piped())
1185 .stdout(Stdio::piped())
1186 .spawn()
1187 .unwrap();
1188 child
1189 .stdin
1190 .take()
1191 .unwrap()
1192 .write_all(text.as_bytes())
1193 .unwrap();
1194 let out = child.wait_with_output().unwrap();
1195 String::from_utf8_lossy(&out.stdout).trim().to_string()
1196 }
1197
1198 fn provenance_payload(remote: &Path, object: &str) -> (String, String) {
1200 let note = git(remote, &["notes", "--ref", PROVENANCE_REF, "show", object]);
1201 let (p, sig) = note
1202 .split_once("\n\n")
1203 .expect("payload, blank line, signature");
1204 (format!("{p}\n"), sig.to_string())
1205 }
1206
1207 fn push_of(head: &str) -> PushRef {
1208 PushRef {
1209 local_ref: "refs/heads/feat/x".into(),
1210 local_oid: head.to_string(),
1211 remote_ref: "refs/heads/feat/x".into(),
1212 remote_oid: "0".repeat(40),
1213 }
1214 }
1215
1216 #[test]
1220 fn a_provenance_payload_is_signed_and_published_by_tree_and_commit() {
1221 let (d, work, remote, head, tree, signers) = provenance_world("prov-e2e");
1222 let payloads = d.join("payloads");
1223 std::fs::create_dir_all(&payloads).unwrap();
1224 let file = payloads.join(&head);
1225 let body = record(&head, &tree);
1226 std::fs::write(&file, &body).unwrap();
1227 let gates = ["pre-push-cargo-test".to_string()];
1228 in_repo(&work, || {
1229 attest_push(&test_settings(), "origin", &[push_of(&head)], &gates, &[])
1230 });
1231 let attested = git(&remote, &["notes", "--ref", NOTES_REF, "show", &head]);
1232 in_repo(&work, || {
1233 provenance_push_from(&payloads, "origin", &[push_of(&head)])
1234 });
1235 let canon = canon_by_hand(&work, &tree);
1238 assert_ne!(
1239 canon, tree,
1240 "the tree carries a plan, so canon(T) is not its oid"
1241 );
1242 let signed = body.replacen(
1243 &format!("tree {tree}\n"),
1244 &format!("tree {tree}\ncanon {canon}\n"),
1245 1,
1246 );
1247 for object in [&head, &tree] {
1248 let (p, sig) = provenance_payload(&remote, object);
1249 assert_eq!(p, signed, "the payload, with canon(T) inserted, is signed");
1250 assert_eq!(p.lines().nth(3), Some(format!("canon {canon}").as_str()));
1251 assert!(verify_in(
1252 PROVENANCE_NAMESPACE,
1253 &p,
1254 &sig,
1255 &signers,
1256 "t@t.test"
1257 ));
1258 assert!(
1259 !verify_in(NAMESPACE, &p, &sig, &signers, "t@t.test"),
1260 "a provenance signature is never an attestation"
1261 );
1262 }
1263 assert!(!file.exists(), "a published payload is deleted");
1264 assert_eq!(
1265 git(&remote, &["notes", "--ref", NOTES_REF, "show", &head]),
1266 attested,
1267 "the attestation note is byte-identical with a provenance payload present"
1268 );
1269 scratch_cleanup(&d);
1270 scratch_cleanup(&work);
1271 }
1272
1273 #[test]
1278 fn a_green_provenance_payload_is_filed_under_the_green_names_alone() {
1279 let (d, work, remote, head, tree, signers) = provenance_world("prov-green-names");
1280 let payloads = d.join("payloads");
1281 std::fs::create_dir_all(&payloads).unwrap();
1282 let body = record(&head, &tree).replacen(PROVENANCE_FORMAT, "greengate-provenance-v1", 1);
1283 assert!(body.starts_with("greengate-provenance-v1\n"));
1284 std::fs::write(payloads.join(&head), &body).unwrap();
1285 in_repo(&work, || {
1286 provenance_push_from(&payloads, "origin", &[push_of(&head)])
1287 });
1288 assert_eq!(
1289 git(
1290 &remote,
1291 &["for-each-ref", "--format=%(refname)", "refs/notes"]
1292 ),
1293 "refs/notes/greengate-provenance"
1294 );
1295 let note = git(
1296 &remote,
1297 &["notes", "--ref", "greengate-provenance", "show", &head],
1298 );
1299 let (p, sig) = note.split_once("\n\n").expect("payload and signature");
1300 let payload = format!("{p}\n");
1301 assert!(payload.starts_with("greengate-provenance-v1\n"));
1302 assert!(verify_in(
1303 "greengate-provenance",
1304 &payload,
1305 sig,
1306 &signers,
1307 "t@t.test"
1308 ));
1309 assert!(!verify_in(
1310 "amont-provenance",
1311 &payload,
1312 sig,
1313 &signers,
1314 "t@t.test"
1315 ));
1316 scratch_cleanup(&d);
1317 scratch_cleanup(&work);
1318 }
1319
1320 #[test]
1326 fn a_waiting_legacy_provenance_payload_is_kept_named_and_not_signed() {
1327 let (d, work, remote, head, tree, _) = provenance_world("prov-legacy-kept");
1328 let payloads = d.join("payloads");
1329 std::fs::create_dir_all(&payloads).unwrap();
1330 let file = payloads.join(&head);
1331 let body = record(&head, &tree).replacen(PROVENANCE_FORMAT, "amont-provenance-v1", 1);
1332 assert!(body.starts_with("amont-provenance-v1\n"));
1333 std::fs::write(&file, &body).unwrap();
1334 in_repo(&work, || {
1335 provenance_push_from(&payloads, "origin", &[push_of(&head)])
1336 });
1337 let said = legacy_provenance_line(&head, &file);
1338 assert!(file.exists(), "a legacy payload is kept, not consumed");
1339 assert_eq!(std::fs::read_to_string(&file).unwrap(), body);
1340 assert_eq!(
1341 git(
1342 &remote,
1343 &["for-each-ref", "--format=%(refname)", "refs/notes"]
1344 ),
1345 "",
1346 "nothing is published for it, under any name"
1347 );
1348 assert_eq!(
1349 git(
1350 &work,
1351 &["for-each-ref", "--format=%(refname)", "refs/notes"]
1352 ),
1353 "",
1354 "nor filed locally"
1355 );
1356 let file_name = file.display().to_string();
1357 assert!(said.contains(&file_name), "names the file: {said}");
1358 assert!(said.contains("written by an older greenpiste"), "{said}");
1359 assert!(said.contains("upgrade greenpiste"), "{said}");
1360 scratch_cleanup(&d);
1361 scratch_cleanup(&work);
1362 }
1363
1364 #[test]
1368 fn an_attestation_push_writes_only_green_refs() {
1369 let (d, work, remote, head, _tree, signers) = provenance_world("attest-green-refs");
1370 let gates = ["pre-push-cargo-test".to_string()];
1371 in_repo(&work, || {
1372 attest_push(&test_settings(), "origin", &[push_of(&head)], &gates, &[])
1373 });
1374 let refs = git(
1375 &remote,
1376 &["for-each-ref", "--format=%(refname)", "refs/notes"],
1377 );
1378 assert!(
1379 refs.lines().any(|r| r == "refs/notes/greengate-attest"),
1380 "{refs}"
1381 );
1382 assert!(
1383 refs.lines().all(|r| r.starts_with("refs/notes/greengate-")),
1384 "an old name was written: {refs}"
1385 );
1386 let note = git(
1387 &remote,
1388 &["notes", "--ref", "greengate-attest", "show", &head],
1389 );
1390 let (p, sig) = note.split_once("\n\n").expect("payload and signature");
1391 let payload = format!("{p}\n");
1392 assert!(payload.starts_with("greengate-attest-v2\n"), "{payload}");
1393 assert!(verify_in(
1394 "greengate-attest",
1395 &payload,
1396 sig,
1397 &signers,
1398 "t@t.test"
1399 ));
1400 assert!(!verify_in(
1401 "amont-attest",
1402 &payload,
1403 sig,
1404 &signers,
1405 "t@t.test"
1406 ));
1407 scratch_cleanup(&d);
1408 scratch_cleanup(&work);
1409 }
1410
1411 #[test]
1415 fn the_default_key_is_the_green_name_with_the_old_one_as_fallback() {
1416 let home = dir("key-default");
1417 std::fs::create_dir_all(home.join(".ssh")).unwrap();
1418 assert_eq!(default_key_in(&home), home.join(".ssh/greengate-attest"));
1420 assert_eq!(key_move_hint_in(&home), None);
1421 std::fs::write(home.join(".ssh/amont-attest"), "k").unwrap();
1423 assert_eq!(default_key_in(&home), home.join(".ssh/amont-attest"));
1424 let hint = key_move_hint_in(&home).expect("a doctor line");
1425 assert!(
1426 hint.contains("mv ~/.ssh/amont-attest ~/.ssh/greengate-attest"),
1427 "{hint}"
1428 );
1429 assert_eq!(hint.lines().count(), 1);
1430 std::fs::write(home.join(".ssh/greengate-attest"), "k").unwrap();
1432 assert_eq!(default_key_in(&home), home.join(".ssh/greengate-attest"));
1433 assert_eq!(key_move_hint_in(&home), None);
1434 scratch_cleanup(&home);
1435 }
1436
1437 #[test]
1438 fn a_payload_for_another_tree_is_neither_signed_nor_deleted() {
1439 let (d, work, remote, head, _tree, _) = provenance_world("prov-mismatch");
1440 let payloads = d.join("payloads");
1441 std::fs::create_dir_all(&payloads).unwrap();
1442 let file = payloads.join(&head);
1443 std::fs::write(&file, record(&head, &"b".repeat(40))).unwrap();
1444 in_repo(&work, || {
1445 provenance_push_from(&payloads, "origin", &[push_of(&head)])
1446 });
1447 assert!(file.exists(), "a mismatched payload is kept");
1448 let refs = git(&remote, &["for-each-ref", PROVENANCE_FULL_REF]);
1449 assert!(refs.is_empty(), "nothing was published: {refs}");
1450 scratch_cleanup(&d);
1451 scratch_cleanup(&work);
1452 }
1453
1454 #[test]
1457 fn a_payload_with_a_canon_line_is_refused_and_kept() {
1458 let (d, work, remote, head, tree, _) = provenance_world("prov-canon");
1459 let payloads = d.join("payloads");
1460 std::fs::create_dir_all(&payloads).unwrap();
1461 let file = payloads.join(&head);
1462 let old = record(&head, &tree).replacen(
1463 &format!("tree {tree}\n"),
1464 &format!("tree {tree}\ncanon {}\n", "c".repeat(64)),
1465 1,
1466 );
1467 std::fs::write(&file, &old).unwrap();
1468 in_repo(&work, || {
1469 provenance_push_from(&payloads, "origin", &[push_of(&head)])
1470 });
1471 assert_eq!(
1472 std::fs::read_to_string(&file).unwrap(),
1473 old,
1474 "kept as it was"
1475 );
1476 let refs = git(&remote, &["for-each-ref", PROVENANCE_FULL_REF]);
1477 assert!(refs.is_empty(), "nothing was published: {refs}");
1478 scratch_cleanup(&d);
1479 scratch_cleanup(&work);
1480 }
1481
1482 #[test]
1485 fn the_canon_refusal_fits_in_80_columns() {
1486 for commit in [
1487 "9f1c2ab0d6e4c1b2a3f405e6d7c8b9a0f1e2d3c4".to_string(),
1488 "e".repeat(64),
1489 ] {
1490 let file = PathBuf::from("/Users/someone/.claude/amont-agent/provenance/amont-agent")
1491 .join(&commit);
1492 let lines = canon_refusal(&commit, &file);
1493 assert!(lines[0].starts_with(" provenance for "), "{lines:?}");
1494 assert!(lines[0].contains(&commit[..7]), "{lines:?}");
1495 let all = lines.join("\n");
1496 assert!(all.contains("canon line") && all.contains("pre-release amont-agent"));
1497 assert!(all.contains(&format!(" {commit} in\n")), "{all}");
1498 assert!(all.contains("upgrade amont-agent"), "{all}");
1499 for l in &lines {
1500 assert!(
1501 l.chars().count() <= 80,
1502 "{} columns: {l}",
1503 l.chars().count()
1504 );
1505 }
1506 }
1507 }
1508
1509 #[test]
1511 fn a_failed_canon_keeps_the_payload() {
1512 let (d, work, remote, head, tree, _) = provenance_world("prov-nocanon");
1513 let docs = git(&work, &["rev-parse", &format!("{tree}:docs")]);
1515 let objects = PathBuf::from(git(&work, &["rev-parse", "--git-path", "objects"]));
1516 let objects = if objects.is_absolute() {
1517 objects
1518 } else {
1519 work.join(objects)
1520 };
1521 std::fs::remove_file(objects.join(&docs[..2]).join(&docs[2..])).unwrap();
1522 let payloads = d.join("payloads");
1523 std::fs::create_dir_all(&payloads).unwrap();
1524 let file = payloads.join(&head);
1525 std::fs::write(&file, record(&head, &tree)).unwrap();
1526 in_repo(&work, || {
1527 assert_eq!(canon(&tree), None);
1528 provenance_push_from(&payloads, "origin", &[push_of(&head)])
1529 });
1530 assert!(file.exists(), "a payload without a canon is kept");
1531 let refs = git(&remote, &["for-each-ref", PROVENANCE_FULL_REF]);
1532 assert!(refs.is_empty(), "nothing was published: {refs}");
1533 scratch_cleanup(&d);
1534 scratch_cleanup(&work);
1535 }
1536
1537 #[test]
1540 fn a_sha256_repository_signs_a_64_hex_canon() {
1541 let (d, work, remote, head, tree, _) = provenance_world_in("prov-sha256", Some("sha256"));
1542 assert_eq!(tree.len(), 64);
1543 let payloads = d.join("payloads");
1544 std::fs::create_dir_all(&payloads).unwrap();
1545 std::fs::write(payloads.join(&head), record(&head, &tree)).unwrap();
1546 in_repo(&work, || {
1547 provenance_push_from(&payloads, "origin", &[push_of(&head)])
1548 });
1549 let (p, _) = provenance_payload(&remote, &head);
1550 let canon = canon_by_hand(&work, &tree);
1551 assert_eq!(canon.len(), 64);
1552 assert_eq!(
1553 p.lines().nth(3),
1554 Some(format!("canon {canon}").as_str()),
1555 "{p}"
1556 );
1557 scratch_cleanup(&d);
1558 scratch_cleanup(&work);
1559 }
1560
1561 #[test]
1562 fn a_failed_publish_keeps_the_payload_for_the_next_push() {
1563 let (d, work, _remote, head, tree, _) = provenance_world("prov-fail");
1564 git(
1565 &work,
1566 &[
1567 "remote",
1568 "set-url",
1569 "origin",
1570 d.join("gone.git").to_str().unwrap(),
1571 ],
1572 );
1573 let payloads = d.join("payloads");
1574 std::fs::create_dir_all(&payloads).unwrap();
1575 let file = payloads.join(&head);
1576 std::fs::write(&file, record(&head, &tree)).unwrap();
1577 in_repo(&work, || {
1578 provenance_push_from(&payloads, "origin", &[push_of(&head)])
1579 });
1580 assert!(file.exists(), "an unpublished payload is kept");
1581 scratch_cleanup(&d);
1582 scratch_cleanup(&work);
1583 }
1584
1585 #[test]
1588 fn a_config_key_cannot_point_amont_at_other_payloads() {
1589 let (d, work, remote, head, tree, _) = provenance_world("prov-config");
1590 let elsewhere = d.join("elsewhere");
1591 let name = work.file_name().unwrap().to_string_lossy().into_owned();
1592 std::fs::create_dir_all(elsewhere.join(&name)).unwrap();
1593 std::fs::write(elsewhere.join(&name).join(&head), record(&head, &tree)).unwrap();
1594 for key in ["greengate.provenanceDir", "amont.agent.provenanceDir"] {
1595 git(&work, &["config", key, elsewhere.to_str().unwrap()]);
1596 }
1597 in_repo(&work, || {
1598 provenance_push(&test_settings(), "origin", &[push_of(&head)])
1599 });
1600 let refs = git(&remote, &["for-each-ref", PROVENANCE_FULL_REF]);
1601 assert!(refs.is_empty(), "a configured directory was read: {refs}");
1602 scratch_cleanup(&d);
1603 scratch_cleanup(&work);
1604 }
1605
1606 #[test]
1607 fn no_payload_publishes_nothing() {
1608 let (d, work, remote, head, _, _) = provenance_world("prov-none");
1609 let payloads = d.join("payloads");
1610 std::fs::create_dir_all(&payloads).unwrap();
1611 in_repo(&work, || {
1612 provenance_push_from(&payloads, "origin", &[push_of(&head)])
1613 });
1614 let refs = git(&remote, &["for-each-ref", PROVENANCE_FULL_REF]);
1615 assert!(refs.is_empty(), "{refs}");
1616 scratch_cleanup(&d);
1617 scratch_cleanup(&work);
1618 }
1619
1620 #[test]
1621 fn a_missing_key_signs_nothing() {
1622 assert!(sign("anything", Path::new("/nonexistent/key")).is_none());
1623 }
1624
1625 #[test]
1629 fn an_enabled_push_leaves_a_verifiable_note_on_the_remote() {
1630 let d = dir("e2e");
1631 let (key, signers) = keypair(&d);
1632 let remote = d.join("remote.git");
1633 std::fs::create_dir_all(&remote).unwrap();
1634 git(&remote, &["init", "-q", "--bare", "--template=", "."]);
1635 let work = repo("e2e-work");
1636 git(
1637 &work,
1638 &["remote", "add", "origin", remote.to_str().unwrap()],
1639 );
1640 git(&work, &["config", "greengate.attest", "true"]);
1641 git(
1642 &work,
1643 &["config", "greengate.attestKey", key.to_str().unwrap()],
1644 );
1645 std::fs::write(work.join("a.ts"), "x").unwrap();
1646 git(&work, &["add", "a.ts"]);
1647 git(&work, &["commit", "-qm", "chore: a"]);
1648 let head = git(&work, &["rev-parse", "HEAD"]);
1649 let tree = git(&work, &["rev-parse", "HEAD^{tree}"]);
1650 let push_ref = PushRef {
1651 local_ref: "refs/heads/main".into(),
1652 local_oid: head.clone(),
1653 remote_ref: "refs/heads/main".into(),
1654 remote_oid: "0".repeat(40),
1655 };
1656 in_repo(&work, || {
1657 attest_push(
1658 &test_settings(),
1659 "origin",
1660 &[push_ref],
1661 &["pre-push-run-tests-js".into()],
1662 &[],
1663 );
1664 });
1665 let body = git(&remote, &["notes", "--ref", NOTES_REF, "show", &head]);
1667 assert!(!body.is_empty(), "no note reached the remote");
1668 let (p, sig) = body
1669 .split_once("\n\n")
1670 .expect("payload, blank line, signature");
1671 let p = format!("{p}\n"); assert!(p.starts_with(FORMAT));
1673 assert!(
1674 p.contains(&format!("tree {tree}")),
1675 "attests the pushed tree"
1676 );
1677 assert!(
1678 verify(&p, sig, &signers, "t@t.test"),
1679 "the remote copy verifies"
1680 );
1681 scratch_cleanup(&d);
1682 scratch_cleanup(&work);
1683 }
1684
1685 #[test]
1692 fn a_push_with_a_spec_publishes_the_inputs_ref() {
1693 let (_d, work, remote, _) = remote_and_work("inputs");
1694 std::fs::create_dir_all(work.join(".github")).unwrap();
1695 std::fs::write(
1696 work.join(".github/attest-inputs"),
1697 "pre-push-run-tests-js a.ts\n",
1698 )
1699 .unwrap();
1700 git(&work, &["add", ".github/attest-inputs"]);
1701 git(&work, &["commit", "-qm", "chore: spec"]);
1702 in_repo(&work, || {
1703 attest_push(
1704 &test_settings(),
1705 "origin",
1706 &[push_ref_for(&work)],
1707 &["pre-push-run-tests-js".into()],
1708 &[],
1709 );
1710 });
1711 let listed = git(&remote, &["notes", "--ref", INPUTS_REF, "list"]);
1712 assert!(
1714 !listed.trim().is_empty(),
1715 "the inputs ref reached the remote"
1716 );
1717 }
1718
1719 #[test]
1720 fn no_opt_in_means_no_note() {
1721 let d = dir("optout");
1722 let (key, _) = keypair(&d);
1723 let remote = d.join("remote.git");
1724 std::fs::create_dir_all(&remote).unwrap();
1725 git(&remote, &["init", "-q", "--bare", "--template=", "."]);
1726 let work = repo("optout-work");
1727 git(
1728 &work,
1729 &["remote", "add", "origin", remote.to_str().unwrap()],
1730 );
1731 git(
1732 &work,
1733 &["config", "greengate.attestKey", key.to_str().unwrap()],
1734 );
1735 std::fs::write(work.join("a.ts"), "x").unwrap();
1736 git(&work, &["add", "a.ts"]);
1737 git(&work, &["commit", "-qm", "chore: a"]);
1738 let head = git(&work, &["rev-parse", "HEAD"]);
1739 let push_ref = PushRef {
1740 local_ref: "refs/heads/main".into(),
1741 local_oid: head.clone(),
1742 remote_ref: "refs/heads/main".into(),
1743 remote_oid: "0".repeat(40),
1744 };
1745 in_repo(&work, || {
1746 attest_push(
1747 &test_settings(),
1748 "origin",
1749 &[push_ref],
1750 &["pre-push-run-tests-js".into()],
1751 &[],
1752 );
1753 });
1754 assert!(
1755 git(&remote, &["notes", "--ref", NOTES_REF, "list"]).is_empty(),
1756 "an un-opted-in repo attested something"
1757 );
1758 scratch_cleanup(&d);
1759 scratch_cleanup(&work);
1760 }
1761
1762 #[test]
1765 fn deletions_and_empty_gates_attest_nothing() {
1766 let d = dir("nothing");
1767 let (key, _) = keypair(&d);
1768 let remote = d.join("remote.git");
1769 std::fs::create_dir_all(&remote).unwrap();
1770 git(&remote, &["init", "-q", "--bare", "--template=", "."]);
1771 let work = repo("nothing-work");
1772 git(
1773 &work,
1774 &["remote", "add", "origin", remote.to_str().unwrap()],
1775 );
1776 git(&work, &["config", "greengate.attest", "true"]);
1777 git(
1778 &work,
1779 &["config", "greengate.attestKey", key.to_str().unwrap()],
1780 );
1781 std::fs::write(work.join("a.ts"), "x").unwrap();
1782 git(&work, &["add", "a.ts"]);
1783 git(&work, &["commit", "-qm", "chore: a"]);
1784 let head = git(&work, &["rev-parse", "HEAD"]);
1785 let deletion = PushRef {
1786 local_ref: "(delete)".into(),
1787 local_oid: "0".repeat(40),
1788 remote_ref: "refs/heads/gone".into(),
1789 remote_oid: head.clone(),
1790 };
1791 let real = PushRef {
1792 local_ref: "refs/heads/main".into(),
1793 local_oid: head,
1794 remote_ref: "refs/heads/main".into(),
1795 remote_oid: "0".repeat(40),
1796 };
1797 in_repo(&work, || {
1798 attest_push(
1799 &test_settings(),
1800 "origin",
1801 &[deletion],
1802 &["pre-push-pytest".into()],
1803 &[],
1804 );
1805 attest_push(&test_settings(), "origin", &[real], &[], &[]);
1806 });
1807 assert!(git(&remote, &["notes", "--ref", NOTES_REF, "list"]).is_empty());
1808 scratch_cleanup(&d);
1809 scratch_cleanup(&work);
1810 }
1811
1812 #[test]
1819 fn a_rejection_is_a_note_whose_signature_did_not_verify() {
1820 let trail: Vec<String> = [
1821 "note on abc123: signature did not verify for principal t@t.test",
1822 "note on abc123 block 2: no principal matched",
1823 "note on def456 carries no signature block",
1824 "attested tree abc is not the checked-out tree def and neither its canonical tree nor an input fingerprint of abc123 matches",
1825 "no attestation found for tree abc",
1826 ]
1827 .iter()
1828 .map(|s| s.to_string())
1829 .collect();
1830 assert_eq!(
1831 signature_rejections(&trail),
1832 vec![
1833 "note on abc123: signature did not verify for principal t@t.test".to_string(),
1834 "note on abc123 block 2: no principal matched".to_string(),
1835 ]
1836 );
1837 }
1838
1839 #[test]
1840 fn covered_answers_in_a_fresh_clone_and_rejects_drift_and_forgery() {
1841 let d = dir("covered");
1842 let (key, signers) = keypair(&d);
1843 let remote = d.join("remote.git");
1844 std::fs::create_dir_all(&remote).unwrap();
1845 git(&remote, &["init", "-q", "--bare", "--template=", "."]);
1846 git(&remote, &["symbolic-ref", "HEAD", "refs/heads/main"]);
1852 let work = repo("covered-work");
1853 git(
1854 &work,
1855 &["remote", "add", "origin", remote.to_str().unwrap()],
1856 );
1857 git(&work, &["config", "greengate.attest", "true"]);
1858 git(
1859 &work,
1860 &["config", "greengate.attestKey", key.to_str().unwrap()],
1861 );
1862 std::fs::write(work.join("a.ts"), "x").unwrap();
1863 git(&work, &["add", "a.ts"]);
1864 git(&work, &["commit", "-qm", "chore: a"]);
1865 git(&work, &["push", "-q", "origin", "HEAD:main"]);
1866 let head = git(&work, &["rev-parse", "HEAD"]);
1867 let push_ref = PushRef {
1868 local_ref: "refs/heads/main".into(),
1869 local_oid: head.clone(),
1870 remote_ref: "refs/heads/main".into(),
1871 remote_oid: "0".repeat(40),
1872 };
1873 in_repo(&work, || {
1874 attest_push(
1875 &test_settings(),
1876 "origin",
1877 &[push_ref],
1878 &["pre-push-pytest".into()],
1879 &[],
1880 );
1881 });
1882 let clone = d.join("ci-checkout");
1883 git(
1884 &d,
1885 &[
1886 "clone",
1887 "-q",
1888 "--template=",
1889 remote.to_str().unwrap(),
1890 clone.to_str().unwrap(),
1891 ],
1892 );
1893 in_repo(&clone, || {
1894 assert_eq!(
1895 covered(&signers, Some("t@t.test"), Some(&platform()), &[]).as_deref(),
1896 Some("pre-push-pytest"),
1897 "a fresh clone verifies the attestation and reads the gates"
1898 );
1899 assert_eq!(
1900 covered(&signers, Some("t@t.test"), None, &[]).as_deref(),
1901 Some("pre-push-pytest"),
1902 "`any` covers a platform-independent suite"
1903 );
1904 assert_eq!(
1907 covered(&signers, Some("t@t.test"), Some("s390x-aix"), &[]),
1908 None,
1909 "a pass on one platform is not evidence about another"
1910 );
1911 assert_eq!(
1912 covered(&signers, Some("someone@else.test"), None, &[]),
1913 None,
1914 "an unlisted principal covers nothing"
1915 );
1916 });
1917 std::fs::write(clone.join("b.ts"), "y").unwrap();
1919 git(&clone, &["config", "user.email", "t@t.test"]);
1920 git(&clone, &["config", "user.name", "t"]);
1921 git(&clone, &["add", "b.ts"]);
1922 git(&clone, &["commit", "-qm", "chore: b"]);
1923 in_repo(&clone, || {
1924 assert_eq!(
1925 covered(&signers, Some("t@t.test"), None, &[]),
1926 None,
1927 "drifted tree"
1928 );
1929 });
1930 let head_tree = git(&work, &["rev-parse", "HEAD^{tree}"]);
1940 for object in [&head, &head_tree] {
1941 git(
1942 &work,
1943 &[
1944 "notes", "--ref", NOTES_REF, "add", "-f", "-m", "garbage", object,
1945 ],
1946 );
1947 }
1948 git(
1949 &work,
1950 &[
1951 "push",
1952 "-q",
1953 "origin",
1954 &format!("+{NOTES_FULL_REF}:{NOTES_FULL_REF}"),
1955 ],
1956 );
1957 git(
1961 &work,
1962 &["push", "-q", "origin", &format!(":{INPUTS_FULL_REF}")],
1963 );
1964 git(&clone, &["reset", "-q", "--hard", &head]);
1965 in_repo(&clone, || {
1966 assert_eq!(
1967 covered(&signers, Some("t@t.test"), None, &[]),
1968 None,
1969 "a foreign note is not a stamp"
1970 );
1971 });
1972 scratch_cleanup(&d);
1973 scratch_cleanup(&work);
1974 }
1975
1976 #[test]
1982 fn default_signers_is_found_from_a_subdirectory() {
1983 let work = repo("signers-subdir");
1984 std::fs::create_dir_all(work.join(".forgejo")).unwrap();
1985 std::fs::write(work.join(".forgejo/allowed_signers"), "t@t.test x\n").unwrap();
1986 let sub = work.join("packages").join("thing");
1987 std::fs::create_dir_all(&sub).unwrap();
1988 in_repo(&sub, || {
1989 let found = default_signers().expect("resolved from the repo root, not the cwd");
1990 assert!(found.ends_with(".forgejo/allowed_signers"));
1991 assert!(found.exists(), "the path it returns must be usable as-is");
1992 });
1993 scratch_cleanup(&work);
1994 }
1995
1996 #[test]
1997 fn zero_oids_of_any_width_are_zero() {
1998 assert!(is_zero(&"0".repeat(40)));
1999 assert!(is_zero(&"0".repeat(64)));
2000 assert!(!is_zero("0a0000"));
2001 assert!(!is_zero(""));
2002 }
2003
2004 #[test]
2005 fn forget_removes_the_local_ref() {
2006 let work = repo("forget");
2007 std::fs::write(work.join("a.ts"), "x").unwrap();
2008 git(&work, &["add", "a.ts"]);
2009 git(&work, &["commit", "-qm", "chore: a"]);
2010 git(
2011 &work,
2012 &["notes", "--ref", NOTES_REF, "add", "-m", "x", "HEAD"],
2013 );
2014 in_repo(&work, forget);
2015 assert!(git(&work, &["notes", "--ref", NOTES_REF, "list"]).is_empty());
2016 scratch_cleanup(&work);
2017 }
2018
2019 pub(crate) fn both_names_signer(dir: &Path) -> (PathBuf, PathBuf) {
2031 let key = dir.join("signer_key");
2032 let ok = std::process::Command::new("ssh-keygen")
2033 .args(["-q", "-t", "ed25519", "-N", "", "-C", "test", "-f"])
2034 .arg(&key)
2035 .status()
2036 .expect("ssh-keygen must exist for these tests")
2037 .success();
2038 assert!(ok, "keygen failed");
2039 let pubkey = std::fs::read_to_string(key.with_extension("pub")).unwrap();
2040 let signers = dir.join("allowed_signers");
2041 std::fs::write(
2042 &signers,
2043 format!(
2044 "cluster-signer@{} namespaces=\"{},{}\" {pubkey}",
2045 crate::cluster::PLATFORM,
2046 git_attest::format::LEGACY.namespace,
2047 git_attest::format::GREEN.namespace
2048 ),
2049 )
2050 .unwrap();
2051 (key, signers)
2052 }
2053
2054 pub(crate) fn block_with(header: &str, namespace: &str, tree: &str, key: &Path) -> String {
2056 let payload = format!(
2057 "{header}\ntree {tree}\ngates suite\nplatform {}\ngreengate 0.0.0\n",
2058 crate::cluster::PLATFORM
2059 );
2060 let sig = git_attest::sign::sign(namespace, &payload, key).expect("sign");
2061 block(&payload, &sig)
2062 }
2063
2064 #[test]
2065 fn a_signer_block_is_checked_under_the_namespace_its_header_names() {
2066 use git_attest::format::{GREEN, LEGACY};
2067 let scratch = dir("signer-names");
2068 let (key, signers) = both_names_signer(&scratch);
2069 let tree = "0123456789012345678901234567890123456789";
2070 for set in [GREEN, LEGACY] {
2071 let body = block_with(set.format, set.namespace, tree, &key);
2072 let checked = signer_block(&body, tree, &signers)
2073 .unwrap_or_else(|e| panic!("{}: {}", set.format, e.reason()));
2074 assert_eq!(checked.names, set);
2075 assert_eq!(checked.gates, ["suite"]);
2076 }
2077 for (header, signed_under) in [(LEGACY, GREEN), (GREEN, LEGACY)] {
2078 let body = block_with(header.format, signed_under.namespace, tree, &key);
2079 assert!(
2080 matches!(
2081 signer_block(&body, tree, &signers),
2082 Err(BlockRefusal::Signer(_))
2083 ),
2084 "a {} block signed under {} must be refused",
2085 header.format,
2086 signed_under.namespace
2087 );
2088 }
2089 scratch_cleanup(&scratch);
2090 }
2091
2092 #[test]
2093 fn forget_in_removes_the_notes_ref_of_both_name_sets() {
2094 let repo_dir = repo("forget-both");
2095 git(&repo_dir, &["commit", "-q", "--allow-empty", "-m", "c"]);
2096 for names in READ_NAMES {
2097 git(
2098 &repo_dir,
2099 &["notes", "--ref", names.notes_ref, "add", "-m", "x", "HEAD"],
2100 );
2101 }
2102 assert!(forget_in(&repo_dir));
2103 for names in READ_NAMES {
2104 let full = format!("refs/notes/{}", names.notes_ref);
2105 let out = std::process::Command::new("git")
2106 .arg("-C")
2107 .arg(&repo_dir)
2108 .args(["rev-parse", "--verify", "-q", &full])
2109 .output()
2110 .unwrap();
2111 assert!(!out.status.success(), "{full} survived forget_in");
2112 }
2113 scratch_cleanup(&repo_dir);
2114 }
2115
2116 #[test]
2117 fn filed_signer_blocks_drops_a_block_of_the_other_name_set() {
2118 use git_attest::format::{GREEN, LEGACY};
2119 let work = repo("filed-names");
2120 std::fs::write(work.join("a.txt"), "x").unwrap();
2121 git(&work, &["add", "a.txt"]);
2122 git(&work, &["commit", "-qm", "chore: a"]);
2123 let (key, signers) = both_names_signer(&work);
2124 std::fs::create_dir_all(work.join(".forgejo")).unwrap();
2125 std::fs::copy(&signers, work.join(".forgejo/allowed_signers")).unwrap();
2126 let tree = git(&work, &["rev-parse", "HEAD^{tree}"]);
2127 let green = block_with(GREEN.format, GREEN.namespace, &tree, &key);
2128 let legacy = block_with(LEGACY.format, LEGACY.namespace, &tree, &key);
2129 in_repo(&work, || {
2130 file_signer_block(&legacy, &[&tree]).expect("file the legacy block");
2131 assert!(
2132 filed_signer_blocks(&tree).is_empty(),
2133 "a legacy block is not publishable while WRITE is green"
2134 );
2135 file_signer_block(&format!("{legacy}\n{green}"), &[&tree]).expect("file both");
2136 let kept = filed_signer_blocks(&tree);
2137 assert_eq!(kept.len(), 1, "{kept:?}");
2138 assert_eq!(kept[0].names, git_attest::format::WRITE);
2139 assert_eq!(kept[0].names, GREEN);
2140 assert!(kept[0].is_publishable());
2141 });
2142 scratch_cleanup(&work);
2143 }
2144
2145 #[test]
2146 fn a_verification_says_which_name_it_went_through() {
2147 let mut verdict = git_attest::verify::Verdict::nothing("test");
2148 assert!(verified_lines(&verdict).is_empty());
2149 verdict.verified_under = vec![
2150 git_attest::format::GREEN.namespace.to_string(),
2151 git_attest::format::LEGACY.namespace.to_string(),
2152 ];
2153 assert_eq!(
2154 verified_lines(&verdict),
2155 [
2156 format!("verified under {}", git_attest::format::GREEN.namespace),
2157 format!("verified under {}", git_attest::format::LEGACY.namespace),
2158 ]
2159 );
2160 }
2161}