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
354const PROVENANCE_OWNER: &str = "greenbelay";
356const OLD_PROVENANCE_OWNER: &str = "amont-agent";
360
361fn provenance_dirs(env: impl Fn(&str) -> Option<std::ffi::OsString>) -> Option<[PathBuf; 2]> {
371 let config = match env("CLAUDE_CONFIG_DIR") {
372 Some(d) => PathBuf::from(d),
373 None => PathBuf::from(env("HOME").or_else(|| env("USERPROFILE"))?).join(".claude"),
374 };
375 Some([PROVENANCE_OWNER, OLD_PROVENANCE_OWNER].map(|o| config.join(o).join("provenance")))
376}
377
378fn read_payload(dirs: &[PathBuf], commit: &str) -> Option<(usize, PathBuf, String)> {
383 for (at, dir) in dirs.iter().enumerate() {
384 let file = dir.join(commit);
385 match std::fs::read_to_string(&file) {
386 Ok(text) => return Some((at, file, text)),
387 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
388 Err(_) => return None,
389 }
390 }
391 None
392}
393
394fn repo_name() -> Option<String> {
399 let common = crate::git::stdout(&["rev-parse", "--git-common-dir"])?;
400 if common.is_empty() {
401 return None;
402 }
403 let common = PathBuf::from(common);
404 let common = if common.is_absolute() {
405 common
406 } else {
407 std::env::current_dir().ok()?.join(common)
408 };
409 let common = std::fs::canonicalize(&common).unwrap_or(common);
410 common
411 .parent()
412 .and_then(std::path::Path::file_name)
413 .map(|n| n.to_string_lossy().into_owned())
414 .filter(|n| !n.is_empty())
415}
416
417pub fn provenance_push(settings: &crate::config::Settings, remote: &str, refs: &[PushRef]) {
422 if remote.is_empty() || !enabled(settings) {
423 return;
424 }
425 let (Some(dirs), Some(name)) = (provenance_dirs(|k| std::env::var_os(k)), repo_name()) else {
426 return;
427 };
428 provenance_push_from_dirs(&dirs.map(|d| d.join(&name)), remote, refs);
429}
430
431#[cfg(test)]
433fn provenance_push_from(dir: &std::path::Path, remote: &str, refs: &[PushRef]) {
434 provenance_push_from_dirs(&[dir.to_path_buf()], remote, refs);
435}
436
437fn provenance_push_from_dirs(dirs: &[PathBuf], remote: &str, refs: &[PushRef]) {
440 let mut found: Vec<PendingRecord> = Vec::new();
441 let mut named_old = false;
442 for r in refs {
443 if is_zero(&r.local_oid) {
444 continue;
445 }
446 let Some((at, file, payload)) = read_payload(dirs, &r.local_oid) else {
447 continue; };
449 if at > 0 && !named_old {
450 named_old = true;
451 crate::say!(
452 " provenance read from {} (amont-agent's directory, until greenbelay migrates it)",
453 dirs[at].display()
454 );
455 }
456 let spec = format!("{}^{{tree}}", r.local_oid);
457 let Some(tree) = crate::git::stdout(&["rev-parse", &spec]) else {
458 continue;
459 };
460 let first = payload.lines().next().unwrap_or_default();
461 let claimed = payload.lines().find_map(|l| l.strip_prefix("tree "));
462 if first == PROVENANCE_LEGACY_FORMAT {
466 crate::say!("{}", legacy_provenance_line(&r.local_oid, &file));
467 continue;
468 }
469 if first != PROVENANCE_FORMAT || claimed != Some(tree.as_str()) {
470 crate::say!(
471 " provenance for {} not signed: its payload is not a {PROVENANCE_FORMAT} record of this tree",
472 &r.local_oid[..r.local_oid.len().min(7)]
473 );
474 continue;
475 }
476 if payload
480 .lines()
481 .any(|l| l.split_ascii_whitespace().next() == Some("canon"))
482 {
483 for line in canon_refusal(&r.local_oid, &file) {
484 crate::say!("{line}");
485 }
486 continue;
487 }
488 let Ok(canon) = git_attest::fingerprint::canon(here(), &tree) else {
491 crate::say!(
492 " provenance for {} not signed: its canonical tree cannot be computed;",
493 &r.local_oid[..r.local_oid.len().min(7)]
494 );
495 crate::say!(" the payload is kept for the next push");
496 continue;
497 };
498 let payload = with_canon(&payload, &canon);
499 found.push(PendingRecord {
500 file,
501 commit: r.local_oid.clone(),
502 tree,
503 payload,
504 });
505 }
506 if found.is_empty() {
507 return;
508 }
509 let Some(key) = key_path().filter(|k| k.exists()) else {
510 crate::say!(" provenance not signed: no signing key");
511 return;
512 };
513 let mut blocks: Vec<(String, String)> = Vec::new();
514 let mut signed: Vec<PathBuf> = Vec::new();
515 for rec in found {
516 let sig = match git_attest::sign::sign(PROVENANCE_NAMESPACE, &rec.payload, &key) {
517 Ok(sig) => sig,
518 Err(e) => {
519 crate::say!(
520 " provenance for {} not signed: {e}; kept for the next push",
521 &rec.commit[..rec.commit.len().min(7)]
522 );
523 continue;
524 }
525 };
526 let body = block(&rec.payload, &sig);
527 blocks.push((rec.tree, body.clone()));
528 blocks.push((rec.commit, body));
529 signed.push(rec.file);
530 }
531 if blocks.is_empty() {
532 return; }
534 if publish(remote, PROVENANCE_REF, &blocks) {
535 for file in &signed {
536 if std::fs::remove_file(file).is_err() {
537 crate::say!(
538 " provenance published, but its payload {} could not be removed",
539 file.display()
540 );
541 }
542 }
543 crate::say!(
544 "{} provenance published ({PROVENANCE_REF})",
545 crate::ui::valid_sign()
546 );
547 } else {
548 crate::say!(" provenance not published: kept for the next push");
549 }
550}
551
552struct PendingRecord {
554 file: PathBuf,
555 commit: String,
556 tree: String,
557 payload: String,
558}
559
560fn legacy_provenance_line(commit: &str, file: &Path) -> String {
563 format!(
564 " provenance for {} not signed: {} was written by an older release of the hook: upgrade greenbelay, then delete {} or re-run its review",
565 &commit[..commit.len().min(7)],
566 file.display(),
567 file.display()
568 )
569}
570
571fn with_canon(payload: &str, canon: &str) -> String {
574 let mut out = String::with_capacity(payload.len() + canon.len() + 7);
575 let mut done = false;
576 for line in payload.split_inclusive('\n') {
577 out.push_str(line);
578 if !done && line.starts_with("tree ") {
579 if !line.ends_with('\n') {
580 out.push('\n');
581 }
582 out.push_str(&format!("canon {canon}\n"));
583 done = true;
584 }
585 }
586 out
587}
588
589fn canon_refusal(commit: &str, file: &std::path::Path) -> Vec<String> {
593 let dir = file.parent().unwrap_or(file).display().to_string();
594 let name = file
595 .file_name()
596 .map(|n| n.to_string_lossy().into_owned())
597 .unwrap_or_default();
598 vec![
599 format!(
600 " provenance for {} not signed: its payload carries a canon line",
601 &commit[..commit.len().min(7)]
602 ),
603 " (a pre-release build of the hook wrote it); delete the file".to_string(),
604 format!(" {name} in"),
605 format!(" {dir}"),
606 " and upgrade greenbelay".to_string(),
607 ]
608}
609
610const PUSH_ATTEMPTS: u32 = 4;
612
613fn publish(remote: &str, notes_ref: &str, blocks: &[(String, String)]) -> bool {
621 let how = Publish {
622 remote,
623 attempts: PUSH_ATTEMPTS,
624 pause: false,
625 identity: None,
626 push_env: &[(PUSH_GUARD, "1")],
627 };
628 let mut log = Vec::new();
629 matches!(
630 publish_notes(here(), &how, notes_ref, blocks, &mut log),
631 Published::Pushed | Published::AlreadyPresent
632 )
633}
634
635pub fn covered(
648 signers: &Path,
649 principal: Option<&str>,
650 require_platform: Option<&str>,
651 anywhere: &[String],
652) -> Option<String> {
653 covered_in(here(), signers, principal, require_platform, anywhere)
654}
655
656pub fn covered_in(
661 dir: &Path,
662 signers: &Path,
663 principal: Option<&str>,
664 require_platform: Option<&str>,
665 anywhere: &[String],
666) -> Option<String> {
667 covered_report(dir, signers, principal, require_platform, anywhere).gates
668}
669
670#[derive(Debug, Clone, PartialEq, Eq, Default)]
675pub struct Covered {
676 pub gates: Option<String>,
677 pub rejected: Vec<String>,
678}
679
680pub fn covered_report(
684 dir: &Path,
685 signers: &Path,
686 principal: Option<&str>,
687 require_platform: Option<&str>,
688 anywhere: &[String],
689) -> Covered {
690 let verdict =
691 git_attest::verify::evaluate(dir, signers, principal, require_platform, anywhere, false);
692 for line in verdict.loud.iter().chain(&verdict.warnings) {
693 eprintln!("{BIN}: {line}");
694 }
695 for line in verified_lines(&verdict) {
696 eprintln!("{BIN}: {line}");
697 }
698 let rejected = signature_rejections(&verdict.trail);
699 for why in &rejected {
700 eprintln!("{BIN}: an attestation was found but did not verify: {why}");
701 }
702 Covered {
703 gates: (!verdict.gates.is_empty()).then(|| verdict.gates.join(" ")),
704 rejected,
705 }
706}
707
708fn verified_lines(verdict: &git_attest::verify::Verdict) -> Vec<String> {
712 verdict
713 .verified_under
714 .iter()
715 .map(|ns| format!("verified under {ns}"))
716 .collect()
717}
718
719fn signature_rejections(trail: &[String]) -> Vec<String> {
724 trail
725 .iter()
726 .filter(|line| line.starts_with("note on ") && line.contains(": "))
727 .cloned()
728 .collect()
729}
730
731#[derive(Debug, Clone, PartialEq, Eq)]
733pub(crate) struct SignerBlock {
734 pub principal: String,
736 pub gates: Vec<String>,
738 pub body: String,
740 pub names: git_attest::format::Names,
742}
743
744impl SignerBlock {
745 pub(crate) fn is_publishable(&self) -> bool {
749 self.names == git_attest::format::WRITE
750 }
751}
752
753#[derive(Debug, Clone, PartialEq, Eq)]
756pub(crate) enum BlockRefusal {
757 Signer(String),
761 Content(String),
764}
765
766impl BlockRefusal {
767 pub(crate) fn reason(&self) -> &str {
769 match self {
770 BlockRefusal::Signer(why) | BlockRefusal::Content(why) => why,
771 }
772 }
773}
774
775pub(crate) fn signer_block(
781 body: &str,
782 tree: &str,
783 signers: &Path,
784) -> Result<SignerBlock, BlockRefusal> {
785 use git_attest::format::{bound_platform, field, split_blocks};
786 use BlockRefusal::{Content, Signer};
787 let (mut blocks, _) = split_blocks(body);
788 if blocks.len() != 1 {
789 return Err(Content(format!("{} signed blocks, not one", blocks.len())));
790 }
791 let signed_block = blocks.remove(0);
792 let header = signed_block.payload.split('\n').next();
795 let Some(names) = READ_NAMES.into_iter().find(|n| Some(n.format) == header) else {
796 return Err(Content(format!(
797 "not an {} or {} payload",
798 git_attest::format::GREEN.format,
799 git_attest::format::LEGACY.format
800 )));
801 };
802 let on = field(&signed_block.payload, "platform");
803 if on != Some(crate::cluster::PLATFORM) {
804 return Err(Content(format!(
805 "its platform is {}, not {}",
806 on.unwrap_or("missing"),
807 crate::cluster::PLATFORM
808 )));
809 }
810 let claimed = field(&signed_block.payload, "tree");
811 if claimed != Some(tree) {
812 return Err(Content(format!(
814 "it is for tree {}, not {tree}",
815 claimed.unwrap_or("missing")
816 )));
817 }
818 let principal = git_attest::sign::verify(
819 names.namespace,
820 &signed_block.payload,
821 &signed_block.signature,
822 signers,
823 None,
824 )
825 .map_err(|e| Signer(e.to_string()))?;
826 if bound_platform(&principal) != Some(crate::cluster::PLATFORM) {
827 return Err(Signer(format!(
828 "{principal} is not a principal bound to {}",
829 crate::cluster::PLATFORM
830 )));
831 }
832 Ok(SignerBlock {
833 principal,
834 gates: field(&signed_block.payload, "gates")
835 .unwrap_or("")
836 .split_whitespace()
837 .map(str::to_string)
838 .collect(),
839 body: block(&signed_block.payload, &signed_block.signature),
840 names,
841 })
842}
843
844fn signer_notes_ref() -> String {
851 format!("{}{NOTES_REF}", git_attest::format::LOCAL_PREFIX)
852}
853
854pub(crate) fn file_signer_block(body: &str, keys: &[&str]) -> Result<(), String> {
860 let notes_ref = signer_notes_ref();
861 for key in keys {
862 let entry = [((*key).to_string(), body.to_string())];
863 if matches!(
864 git_attest::notes::publish_local(here(), None, ¬es_ref, &entry),
865 Published::Error
866 ) {
867 return Err(format!(
868 "git could not write the note on {key} in {notes_ref}"
869 ));
870 }
871 }
872 Ok(())
873}
874
875fn filed_signer_blocks(tree: &str) -> Vec<SignerBlock> {
879 use git_attest::format::{field, split_blocks};
880 let Some(signers) = default_signers() else {
881 return Vec::new();
882 };
883 let notes_ref = signer_notes_ref();
884 let Some(note) = crate::git::stdout(&["notes", "--ref", ¬es_ref, "show", tree]) else {
885 return Vec::new();
886 };
887 split_blocks(¬e)
888 .0
889 .iter()
890 .filter(|b| {
891 field(&b.payload, "platform") == Some(crate::cluster::PLATFORM)
892 && field(&b.payload, "tree") == Some(tree)
893 })
894 .filter_map(|b| signer_block(&block(&b.payload, &b.signature), tree, &signers).ok())
895 .filter(SignerBlock::is_publishable)
897 .collect()
898}
899
900pub fn default_signers() -> Option<PathBuf> {
903 git_attest::verify::default_signers(here())
904}
905
906fn is_zero(oid: &str) -> bool {
909 !oid.is_empty() && oid.bytes().all(|b| b == b'0')
910}
911
912pub fn forget() -> bool {
916 forget_in(here())
917}
918
919pub fn forget_in(repo: &std::path::Path) -> bool {
921 let mut deleted = false;
922 for names in READ_NAMES {
923 let full = format!("refs/notes/{}", names.notes_ref);
924 deleted |= crate::git::succeeds_in(repo, &["update-ref", "-d", &full]);
925 }
926 deleted
927}
928
929#[cfg(test)]
930pub(crate) mod tests {
931 use super::*;
932
933 use std::process::Stdio;
934
935 pub(crate) fn scratch_cleanup(path: &Path) {
938 let _ = std::fs::remove_dir_all(path); }
940
941 #[test]
945 fn the_written_names_are_green_and_each_full_ref_names_its_ref() {
946 for (full, short) in [
947 (NOTES_FULL_REF, NOTES_REF),
948 (INPUTS_FULL_REF, INPUTS_REF),
949 (PROVENANCE_FULL_REF, PROVENANCE_REF),
950 ] {
951 assert_eq!(full, format!("refs/notes/{short}"));
952 assert!(full.starts_with("refs/notes/greengate-"), "{full}");
953 }
954 assert_eq!(git_attest::format::WRITE, git_attest::format::GREEN);
955 }
956
957 fn canon(tree: &str) -> Option<String> {
958 git_attest::fingerprint::canon(here(), tree).ok()
959 }
960
961 fn sign(payload: &str, key: &Path) -> Option<String> {
962 git_attest::sign::sign(NAMESPACE, payload, key).ok()
963 }
964
965 fn verify(payload: &str, sig: &str, signers: &Path, principal: &str) -> bool {
966 verify_in(NAMESPACE, payload, sig, signers, principal)
967 }
968
969 fn verify_in(
970 namespace: &str,
971 payload: &str,
972 sig: &str,
973 signers: &Path,
974 principal: &str,
975 ) -> bool {
976 git_attest::sign::verify(namespace, payload, sig, signers, Some(principal)).is_ok()
977 }
978
979 fn test_settings() -> crate::config::Settings {
982 crate::config::Settings::default()
983 }
984
985 use std::io::Write;
986 use std::path::Path;
987
988 pub(crate) fn dir(name: &str) -> PathBuf {
992 let d = std::env::temp_dir().join(format!("attest-{name}-{}", std::process::id()));
993 scratch_cleanup(&d);
994 std::fs::create_dir_all(&d).unwrap();
995 d
996 }
997
998 fn git(dir: &Path, args: &[&str]) -> String {
1007 let out = std::process::Command::new("git")
1008 .arg("-C")
1009 .arg(dir)
1010 .args(args)
1011 .output()
1012 .expect("git");
1013 assert!(
1014 out.status.success(),
1015 "fixture: git {args:?} in {} exited {:?}: {}",
1016 dir.display(),
1017 out.status.code(),
1018 String::from_utf8_lossy(&out.stderr).trim()
1019 );
1020 String::from_utf8_lossy(&out.stdout).trim().to_string()
1021 }
1022
1023 fn repo(name: &str) -> PathBuf {
1024 let d = dir(name);
1025 git(&d, &["init", "-q", "--template=", "."]);
1026 git(&d, &["config", "user.email", "t@t.test"]);
1027 git(&d, &["config", "user.name", "t"]);
1028 d
1029 }
1030
1031 fn keypair(d: &Path) -> (PathBuf, PathBuf) {
1034 let key = d.join("attest_key");
1035 let ok = std::process::Command::new("ssh-keygen")
1036 .args(["-q", "-t", "ed25519", "-N", "", "-C", "test", "-f"])
1037 .arg(&key)
1038 .status()
1039 .expect("ssh-keygen must exist for these tests")
1040 .success();
1041 assert!(ok, "keygen failed");
1042 let pubkey = std::fs::read_to_string(key.with_extension("pub")).unwrap();
1043 let signers = d.join("allowed_signers");
1044 std::fs::write(
1045 &signers,
1046 format!("t@t.test namespaces=\"{NAMESPACE}\" {pubkey}"),
1047 )
1048 .unwrap();
1049 (key, signers)
1050 }
1051
1052 fn in_repo<T>(dir: &Path, f: impl FnOnce() -> T) -> T {
1055 let _guard = crate::TEST_CWD.lock().unwrap_or_else(|p| p.into_inner());
1056 let prev = std::env::current_dir().unwrap();
1057 std::env::set_current_dir(dir).unwrap();
1058 let r = f();
1059 std::env::set_current_dir(prev).unwrap();
1060 r
1061 }
1062
1063 fn remote_and_work(name: &str) -> (PathBuf, PathBuf, PathBuf, PathBuf) {
1065 let d = dir(name);
1066 let (key, signers) = keypair(&d);
1067 let remote = d.join("remote.git");
1068 std::fs::create_dir_all(&remote).unwrap();
1069 git(&remote, &["init", "-q", "--bare", "--template=", "."]);
1070 let work = repo(&format!("{name}-work"));
1071 git(
1072 &work,
1073 &["remote", "add", "origin", remote.to_str().unwrap()],
1074 );
1075 git(&work, &["config", "greengate.attest", "true"]);
1076 git(
1077 &work,
1078 &["config", "greengate.attestKey", key.to_str().unwrap()],
1079 );
1080 std::fs::write(work.join("a.ts"), "x").unwrap();
1081 git(&work, &["add", "a.ts"]);
1082 git(&work, &["commit", "-qm", "chore: a"]);
1083 (d, work, remote, signers)
1084 }
1085
1086 fn push_ref_for(work: &Path) -> PushRef {
1087 PushRef {
1088 local_ref: "refs/heads/main".into(),
1089 local_oid: git(work, &["rev-parse", "HEAD"]),
1090 remote_ref: "refs/heads/main".into(),
1091 remote_oid: "0".repeat(40),
1092 }
1093 }
1094
1095 #[test]
1096 fn each_payload_is_read_from_the_new_dir_first_then_the_old() {
1097 let config = dir("provenance-names");
1098 let new = config.join("greenbelay/provenance/r");
1099 let old = config.join("amont-agent/provenance/r");
1100 let dirs = [new.clone(), old.clone()];
1101 assert_eq!(read_payload(&dirs, "c1"), None, "neither holds it");
1102 std::fs::create_dir_all(&old).unwrap();
1103 std::fs::write(old.join("c1"), "old").unwrap();
1104 assert_eq!(
1105 read_payload(&dirs, "c1"),
1106 Some((1, old.join("c1"), "old".into())),
1107 "old alone"
1108 );
1109 std::fs::create_dir_all(&new).unwrap();
1111 assert_eq!(read_payload(&dirs, "c1").map(|(at, ..)| at), Some(1));
1112 std::fs::write(new.join("c1"), "new").unwrap();
1113 assert_eq!(
1114 read_payload(&dirs, "c1"),
1115 Some((0, new.join("c1"), "new".into())),
1116 "both: the new"
1117 );
1118 std::fs::create_dir_all(new.join("c2")).unwrap();
1120 std::fs::write(old.join("c2"), "old").unwrap();
1121 assert_eq!(read_payload(&dirs, "c2"), None);
1122 }
1123
1124 #[test]
1125 fn the_provenance_dir_is_resolved_like_greenbelays_config_dir() {
1126 use std::ffi::OsString;
1127 let env = |pairs: &'static [(&'static str, &'static str)]| {
1128 move |k: &str| {
1129 pairs
1130 .iter()
1131 .find(|(n, _)| *n == k)
1132 .map(|(_, v)| OsString::from(v))
1133 }
1134 };
1135 assert_eq!(
1136 provenance_dirs(env(&[("CLAUDE_CONFIG_DIR", "/c"), ("HOME", "/h")])),
1137 Some([
1138 PathBuf::from("/c/greenbelay/provenance"),
1139 PathBuf::from("/c/amont-agent/provenance")
1140 ])
1141 );
1142 assert_eq!(
1143 provenance_dirs(env(&[("HOME", "/h"), ("USERPROFILE", "/u")])),
1144 Some([
1145 PathBuf::from("/h/.claude/greenbelay/provenance"),
1146 PathBuf::from("/h/.claude/amont-agent/provenance")
1147 ])
1148 );
1149 assert_eq!(
1150 provenance_dirs(env(&[("USERPROFILE", "/u")])),
1151 Some([
1152 PathBuf::from("/u/.claude/greenbelay/provenance"),
1153 PathBuf::from("/u/.claude/amont-agent/provenance")
1154 ])
1155 );
1156 assert_eq!(provenance_dirs(env(&[])), None);
1157 }
1158
1159 fn provenance_world(name: &str) -> (PathBuf, PathBuf, PathBuf, String, String, PathBuf) {
1163 provenance_world_in(name, None)
1164 }
1165
1166 fn provenance_world_in(
1168 name: &str,
1169 object_format: Option<&str>,
1170 ) -> (PathBuf, PathBuf, PathBuf, String, String, PathBuf) {
1171 let d = dir(name);
1172 let (key, _) = keypair(&d);
1173 let pubkey = std::fs::read_to_string(key.with_extension("pub")).unwrap();
1174 let signers = d.join("allowed_signers_provenance");
1175 std::fs::write(
1176 &signers,
1177 format!("t@t.test namespaces=\"{NAMESPACE},{PROVENANCE_NAMESPACE}\" {pubkey}"),
1178 )
1179 .unwrap();
1180 let remote = d.join("remote.git");
1181 std::fs::create_dir_all(&remote).unwrap();
1182 let fmt = format!("--object-format={}", object_format.unwrap_or("sha1"));
1183 git(&remote, &["init", "-q", "--bare", "--template=", &fmt, "."]);
1184 let work = match object_format {
1185 None => repo(&format!("{name}-work")),
1186 Some(f) => {
1187 let w = dir(&format!("{name}-work"));
1188 let fmt = format!("--object-format={f}");
1189 git(&w, &["init", "-q", "--template=", &fmt, "."]);
1190 git(&w, &["config", "user.email", "t@t.test"]);
1191 git(&w, &["config", "user.name", "t"]);
1192 w
1193 }
1194 };
1195 git(
1196 &work,
1197 &["remote", "add", "origin", remote.to_str().unwrap()],
1198 );
1199 git(&work, &["config", "greengate.attest", "true"]);
1200 git(
1201 &work,
1202 &["config", "greengate.attestKey", key.to_str().unwrap()],
1203 );
1204 std::fs::write(work.join("README.md"), "words").unwrap();
1205 std::fs::create_dir_all(work.join("docs/plans")).unwrap();
1206 std::fs::write(work.join("docs/plans/p.md"), "# P\n").unwrap();
1207 git(&work, &["add", "README.md", "docs/plans/p.md"]);
1208 git(&work, &["commit", "-qm", "docs: words"]);
1209 let head = git(&work, &["rev-parse", "HEAD"]);
1210 let tree = git(&work, &["rev-parse", "HEAD^{tree}"]);
1211 (d, work, remote, head, tree, signers)
1212 }
1213
1214 fn record(head: &str, tree: &str) -> String {
1215 format!(
1216 "{PROVENANCE_FORMAT}\ncommit {head}\ntree {tree}\n\
1217 plan docs/plans/p.md {}\nreview reviewed {}\npreview not-required\n\
1218 producer amont-agent 0.0.0\n",
1219 "a".repeat(64),
1220 "c".repeat(64)
1221 )
1222 }
1223
1224 fn canon_by_hand(work: &Path, tree: &str) -> String {
1228 let listing = git(
1229 work,
1230 &[
1231 "-c",
1232 "core.quotePath=true",
1233 "ls-tree",
1234 "-r",
1235 "--full-tree",
1236 tree,
1237 ],
1238 );
1239 let mut text = String::new();
1240 for line in listing.lines() {
1241 let (head, path) = line.split_once('\t').unwrap();
1242 let f: Vec<&str> = head.split(' ').collect();
1243 let plan = matches!(f[0], "100644" | "100755")
1244 && (path.starts_with("docs/plans/") || path.starts_with("\"docs/plans/"));
1245 if plan {
1246 text.push_str(&format!(
1247 "{} {} {}\t{path}\n",
1248 f[0],
1249 f[1],
1250 "0".repeat(f[2].len())
1251 ));
1252 } else {
1253 text.push_str(&format!("{line}\n"));
1254 }
1255 }
1256 let mut child = std::process::Command::new("git")
1257 .arg("-C")
1258 .arg(work)
1259 .args(["hash-object", "--stdin"])
1260 .stdin(Stdio::piped())
1261 .stdout(Stdio::piped())
1262 .spawn()
1263 .unwrap();
1264 child
1265 .stdin
1266 .take()
1267 .unwrap()
1268 .write_all(text.as_bytes())
1269 .unwrap();
1270 let out = child.wait_with_output().unwrap();
1271 String::from_utf8_lossy(&out.stdout).trim().to_string()
1272 }
1273
1274 fn provenance_payload(remote: &Path, object: &str) -> (String, String) {
1276 let note = git(remote, &["notes", "--ref", PROVENANCE_REF, "show", object]);
1277 let (p, sig) = note
1278 .split_once("\n\n")
1279 .expect("payload, blank line, signature");
1280 (format!("{p}\n"), sig.to_string())
1281 }
1282
1283 fn push_of(head: &str) -> PushRef {
1284 PushRef {
1285 local_ref: "refs/heads/feat/x".into(),
1286 local_oid: head.to_string(),
1287 remote_ref: "refs/heads/feat/x".into(),
1288 remote_oid: "0".repeat(40),
1289 }
1290 }
1291
1292 #[test]
1296 fn a_provenance_payload_is_signed_and_published_by_tree_and_commit() {
1297 let (d, work, remote, head, tree, signers) = provenance_world("prov-e2e");
1298 let payloads = d.join("payloads");
1299 std::fs::create_dir_all(&payloads).unwrap();
1300 let file = payloads.join(&head);
1301 let body = record(&head, &tree);
1302 std::fs::write(&file, &body).unwrap();
1303 let gates = ["pre-push-cargo-test".to_string()];
1304 in_repo(&work, || {
1305 attest_push(&test_settings(), "origin", &[push_of(&head)], &gates, &[])
1306 });
1307 let attested = git(&remote, &["notes", "--ref", NOTES_REF, "show", &head]);
1308 in_repo(&work, || {
1309 provenance_push_from(&payloads, "origin", &[push_of(&head)])
1310 });
1311 let canon = canon_by_hand(&work, &tree);
1314 assert_ne!(
1315 canon, tree,
1316 "the tree carries a plan, so canon(T) is not its oid"
1317 );
1318 let signed = body.replacen(
1319 &format!("tree {tree}\n"),
1320 &format!("tree {tree}\ncanon {canon}\n"),
1321 1,
1322 );
1323 for object in [&head, &tree] {
1324 let (p, sig) = provenance_payload(&remote, object);
1325 assert_eq!(p, signed, "the payload, with canon(T) inserted, is signed");
1326 assert_eq!(p.lines().nth(3), Some(format!("canon {canon}").as_str()));
1327 assert!(verify_in(
1328 PROVENANCE_NAMESPACE,
1329 &p,
1330 &sig,
1331 &signers,
1332 "t@t.test"
1333 ));
1334 assert!(
1335 !verify_in(NAMESPACE, &p, &sig, &signers, "t@t.test"),
1336 "a provenance signature is never an attestation"
1337 );
1338 }
1339 assert!(!file.exists(), "a published payload is deleted");
1340 assert_eq!(
1341 git(&remote, &["notes", "--ref", NOTES_REF, "show", &head]),
1342 attested,
1343 "the attestation note is byte-identical with a provenance payload present"
1344 );
1345 scratch_cleanup(&d);
1346 scratch_cleanup(&work);
1347 }
1348
1349 #[test]
1354 fn a_green_provenance_payload_is_filed_under_the_green_names_alone() {
1355 let (d, work, remote, head, tree, signers) = provenance_world("prov-green-names");
1356 let payloads = d.join("payloads");
1357 std::fs::create_dir_all(&payloads).unwrap();
1358 let body = record(&head, &tree).replacen(PROVENANCE_FORMAT, "greengate-provenance-v1", 1);
1359 assert!(body.starts_with("greengate-provenance-v1\n"));
1360 std::fs::write(payloads.join(&head), &body).unwrap();
1361 in_repo(&work, || {
1362 provenance_push_from(&payloads, "origin", &[push_of(&head)])
1363 });
1364 assert_eq!(
1365 git(
1366 &remote,
1367 &["for-each-ref", "--format=%(refname)", "refs/notes"]
1368 ),
1369 "refs/notes/greengate-provenance"
1370 );
1371 let note = git(
1372 &remote,
1373 &["notes", "--ref", "greengate-provenance", "show", &head],
1374 );
1375 let (p, sig) = note.split_once("\n\n").expect("payload and signature");
1376 let payload = format!("{p}\n");
1377 assert!(payload.starts_with("greengate-provenance-v1\n"));
1378 assert!(verify_in(
1379 "greengate-provenance",
1380 &payload,
1381 sig,
1382 &signers,
1383 "t@t.test"
1384 ));
1385 assert!(!verify_in(
1386 "amont-provenance",
1387 &payload,
1388 sig,
1389 &signers,
1390 "t@t.test"
1391 ));
1392 scratch_cleanup(&d);
1393 scratch_cleanup(&work);
1394 }
1395
1396 #[test]
1402 fn a_waiting_legacy_provenance_payload_is_kept_named_and_not_signed() {
1403 let (d, work, remote, head, tree, _) = provenance_world("prov-legacy-kept");
1404 let payloads = d.join("payloads");
1405 std::fs::create_dir_all(&payloads).unwrap();
1406 let file = payloads.join(&head);
1407 let body = record(&head, &tree).replacen(PROVENANCE_FORMAT, "amont-provenance-v1", 1);
1408 assert!(body.starts_with("amont-provenance-v1\n"));
1409 std::fs::write(&file, &body).unwrap();
1410 in_repo(&work, || {
1411 provenance_push_from(&payloads, "origin", &[push_of(&head)])
1412 });
1413 let said = legacy_provenance_line(&head, &file);
1414 assert!(file.exists(), "a legacy payload is kept, not consumed");
1415 assert_eq!(std::fs::read_to_string(&file).unwrap(), body);
1416 assert_eq!(
1417 git(
1418 &remote,
1419 &["for-each-ref", "--format=%(refname)", "refs/notes"]
1420 ),
1421 "",
1422 "nothing is published for it, under any name"
1423 );
1424 assert_eq!(
1425 git(
1426 &work,
1427 &["for-each-ref", "--format=%(refname)", "refs/notes"]
1428 ),
1429 "",
1430 "nor filed locally"
1431 );
1432 let file_name = file.display().to_string();
1433 assert!(said.contains(&file_name), "names the file: {said}");
1434 assert!(
1435 said.contains("written by an older release of the hook"),
1436 "{said}"
1437 );
1438 assert!(said.contains("upgrade greenbelay"), "{said}");
1439 scratch_cleanup(&d);
1440 scratch_cleanup(&work);
1441 }
1442
1443 #[test]
1447 fn an_attestation_push_writes_only_green_refs() {
1448 let (d, work, remote, head, _tree, signers) = provenance_world("attest-green-refs");
1449 let gates = ["pre-push-cargo-test".to_string()];
1450 in_repo(&work, || {
1451 attest_push(&test_settings(), "origin", &[push_of(&head)], &gates, &[])
1452 });
1453 let refs = git(
1454 &remote,
1455 &["for-each-ref", "--format=%(refname)", "refs/notes"],
1456 );
1457 assert!(
1458 refs.lines().any(|r| r == "refs/notes/greengate-attest"),
1459 "{refs}"
1460 );
1461 assert!(
1462 refs.lines().all(|r| r.starts_with("refs/notes/greengate-")),
1463 "an old name was written: {refs}"
1464 );
1465 let note = git(
1466 &remote,
1467 &["notes", "--ref", "greengate-attest", "show", &head],
1468 );
1469 let (p, sig) = note.split_once("\n\n").expect("payload and signature");
1470 let payload = format!("{p}\n");
1471 assert!(payload.starts_with("greengate-attest-v2\n"), "{payload}");
1472 assert!(verify_in(
1473 "greengate-attest",
1474 &payload,
1475 sig,
1476 &signers,
1477 "t@t.test"
1478 ));
1479 assert!(!verify_in(
1480 "amont-attest",
1481 &payload,
1482 sig,
1483 &signers,
1484 "t@t.test"
1485 ));
1486 scratch_cleanup(&d);
1487 scratch_cleanup(&work);
1488 }
1489
1490 #[test]
1494 fn the_default_key_is_the_green_name_with_the_old_one_as_fallback() {
1495 let home = dir("key-default");
1496 std::fs::create_dir_all(home.join(".ssh")).unwrap();
1497 assert_eq!(default_key_in(&home), home.join(".ssh/greengate-attest"));
1499 assert_eq!(key_move_hint_in(&home), None);
1500 std::fs::write(home.join(".ssh/amont-attest"), "k").unwrap();
1502 assert_eq!(default_key_in(&home), home.join(".ssh/amont-attest"));
1503 let hint = key_move_hint_in(&home).expect("a doctor line");
1504 assert!(
1505 hint.contains("mv ~/.ssh/amont-attest ~/.ssh/greengate-attest"),
1506 "{hint}"
1507 );
1508 assert_eq!(hint.lines().count(), 1);
1509 std::fs::write(home.join(".ssh/greengate-attest"), "k").unwrap();
1511 assert_eq!(default_key_in(&home), home.join(".ssh/greengate-attest"));
1512 assert_eq!(key_move_hint_in(&home), None);
1513 scratch_cleanup(&home);
1514 }
1515
1516 #[test]
1517 fn a_payload_for_another_tree_is_neither_signed_nor_deleted() {
1518 let (d, work, remote, head, _tree, _) = provenance_world("prov-mismatch");
1519 let payloads = d.join("payloads");
1520 std::fs::create_dir_all(&payloads).unwrap();
1521 let file = payloads.join(&head);
1522 std::fs::write(&file, record(&head, &"b".repeat(40))).unwrap();
1523 in_repo(&work, || {
1524 provenance_push_from(&payloads, "origin", &[push_of(&head)])
1525 });
1526 assert!(file.exists(), "a mismatched payload is kept");
1527 let refs = git(&remote, &["for-each-ref", PROVENANCE_FULL_REF]);
1528 assert!(refs.is_empty(), "nothing was published: {refs}");
1529 scratch_cleanup(&d);
1530 scratch_cleanup(&work);
1531 }
1532
1533 #[test]
1536 fn a_payload_with_a_canon_line_is_refused_and_kept() {
1537 let (d, work, remote, head, tree, _) = provenance_world("prov-canon");
1538 let payloads = d.join("payloads");
1539 std::fs::create_dir_all(&payloads).unwrap();
1540 let file = payloads.join(&head);
1541 let old = record(&head, &tree).replacen(
1542 &format!("tree {tree}\n"),
1543 &format!("tree {tree}\ncanon {}\n", "c".repeat(64)),
1544 1,
1545 );
1546 std::fs::write(&file, &old).unwrap();
1547 in_repo(&work, || {
1548 provenance_push_from(&payloads, "origin", &[push_of(&head)])
1549 });
1550 assert_eq!(
1551 std::fs::read_to_string(&file).unwrap(),
1552 old,
1553 "kept as it was"
1554 );
1555 let refs = git(&remote, &["for-each-ref", PROVENANCE_FULL_REF]);
1556 assert!(refs.is_empty(), "nothing was published: {refs}");
1557 scratch_cleanup(&d);
1558 scratch_cleanup(&work);
1559 }
1560
1561 #[test]
1564 fn the_canon_refusal_fits_in_80_columns() {
1565 for commit in [
1566 "9f1c2ab0d6e4c1b2a3f405e6d7c8b9a0f1e2d3c4".to_string(),
1567 "e".repeat(64),
1568 ] {
1569 let file = PathBuf::from("/Users/someone/.claude/greenbelay/provenance/greengate")
1570 .join(&commit);
1571 let lines = canon_refusal(&commit, &file);
1572 assert!(lines[0].starts_with(" provenance for "), "{lines:?}");
1573 assert!(lines[0].contains(&commit[..7]), "{lines:?}");
1574 let all = lines.join("\n");
1575 assert!(all.contains("canon line") && all.contains("pre-release build of the hook"));
1576 assert!(all.contains(&format!(" {commit} in\n")), "{all}");
1577 assert!(all.contains("upgrade greenbelay"), "{all}");
1578 for l in &lines {
1579 assert!(
1580 l.chars().count() <= 80,
1581 "{} columns: {l}",
1582 l.chars().count()
1583 );
1584 }
1585 }
1586 }
1587
1588 #[test]
1590 fn a_failed_canon_keeps_the_payload() {
1591 let (d, work, remote, head, tree, _) = provenance_world("prov-nocanon");
1592 let docs = git(&work, &["rev-parse", &format!("{tree}:docs")]);
1594 let objects = PathBuf::from(git(&work, &["rev-parse", "--git-path", "objects"]));
1595 let objects = if objects.is_absolute() {
1596 objects
1597 } else {
1598 work.join(objects)
1599 };
1600 std::fs::remove_file(objects.join(&docs[..2]).join(&docs[2..])).unwrap();
1601 let payloads = d.join("payloads");
1602 std::fs::create_dir_all(&payloads).unwrap();
1603 let file = payloads.join(&head);
1604 std::fs::write(&file, record(&head, &tree)).unwrap();
1605 in_repo(&work, || {
1606 assert_eq!(canon(&tree), None);
1607 provenance_push_from(&payloads, "origin", &[push_of(&head)])
1608 });
1609 assert!(file.exists(), "a payload without a canon is kept");
1610 let refs = git(&remote, &["for-each-ref", PROVENANCE_FULL_REF]);
1611 assert!(refs.is_empty(), "nothing was published: {refs}");
1612 scratch_cleanup(&d);
1613 scratch_cleanup(&work);
1614 }
1615
1616 #[test]
1619 fn a_sha256_repository_signs_a_64_hex_canon() {
1620 let (d, work, remote, head, tree, _) = provenance_world_in("prov-sha256", Some("sha256"));
1621 assert_eq!(tree.len(), 64);
1622 let payloads = d.join("payloads");
1623 std::fs::create_dir_all(&payloads).unwrap();
1624 std::fs::write(payloads.join(&head), record(&head, &tree)).unwrap();
1625 in_repo(&work, || {
1626 provenance_push_from(&payloads, "origin", &[push_of(&head)])
1627 });
1628 let (p, _) = provenance_payload(&remote, &head);
1629 let canon = canon_by_hand(&work, &tree);
1630 assert_eq!(canon.len(), 64);
1631 assert_eq!(
1632 p.lines().nth(3),
1633 Some(format!("canon {canon}").as_str()),
1634 "{p}"
1635 );
1636 scratch_cleanup(&d);
1637 scratch_cleanup(&work);
1638 }
1639
1640 #[test]
1641 fn a_failed_publish_keeps_the_payload_for_the_next_push() {
1642 let (d, work, _remote, head, tree, _) = provenance_world("prov-fail");
1643 git(
1644 &work,
1645 &[
1646 "remote",
1647 "set-url",
1648 "origin",
1649 d.join("gone.git").to_str().unwrap(),
1650 ],
1651 );
1652 let payloads = d.join("payloads");
1653 std::fs::create_dir_all(&payloads).unwrap();
1654 let file = payloads.join(&head);
1655 std::fs::write(&file, record(&head, &tree)).unwrap();
1656 in_repo(&work, || {
1657 provenance_push_from(&payloads, "origin", &[push_of(&head)])
1658 });
1659 assert!(file.exists(), "an unpublished payload is kept");
1660 scratch_cleanup(&d);
1661 scratch_cleanup(&work);
1662 }
1663
1664 #[test]
1667 fn a_config_key_cannot_point_amont_at_other_payloads() {
1668 let (d, work, remote, head, tree, _) = provenance_world("prov-config");
1669 let elsewhere = d.join("elsewhere");
1670 let name = work.file_name().unwrap().to_string_lossy().into_owned();
1671 std::fs::create_dir_all(elsewhere.join(&name)).unwrap();
1672 std::fs::write(elsewhere.join(&name).join(&head), record(&head, &tree)).unwrap();
1673 for key in ["greengate.provenanceDir", "amont.agent.provenanceDir"] {
1674 git(&work, &["config", key, elsewhere.to_str().unwrap()]);
1675 }
1676 in_repo(&work, || {
1677 provenance_push(&test_settings(), "origin", &[push_of(&head)])
1678 });
1679 let refs = git(&remote, &["for-each-ref", PROVENANCE_FULL_REF]);
1680 assert!(refs.is_empty(), "a configured directory was read: {refs}");
1681 scratch_cleanup(&d);
1682 scratch_cleanup(&work);
1683 }
1684
1685 #[test]
1686 fn no_payload_publishes_nothing() {
1687 let (d, work, remote, head, _, _) = provenance_world("prov-none");
1688 let payloads = d.join("payloads");
1689 std::fs::create_dir_all(&payloads).unwrap();
1690 in_repo(&work, || {
1691 provenance_push_from(&payloads, "origin", &[push_of(&head)])
1692 });
1693 let refs = git(&remote, &["for-each-ref", PROVENANCE_FULL_REF]);
1694 assert!(refs.is_empty(), "{refs}");
1695 scratch_cleanup(&d);
1696 scratch_cleanup(&work);
1697 }
1698
1699 #[test]
1700 fn a_missing_key_signs_nothing() {
1701 assert!(sign("anything", Path::new("/nonexistent/key")).is_none());
1702 }
1703
1704 #[test]
1708 fn an_enabled_push_leaves_a_verifiable_note_on_the_remote() {
1709 let d = dir("e2e");
1710 let (key, signers) = keypair(&d);
1711 let remote = d.join("remote.git");
1712 std::fs::create_dir_all(&remote).unwrap();
1713 git(&remote, &["init", "-q", "--bare", "--template=", "."]);
1714 let work = repo("e2e-work");
1715 git(
1716 &work,
1717 &["remote", "add", "origin", remote.to_str().unwrap()],
1718 );
1719 git(&work, &["config", "greengate.attest", "true"]);
1720 git(
1721 &work,
1722 &["config", "greengate.attestKey", key.to_str().unwrap()],
1723 );
1724 std::fs::write(work.join("a.ts"), "x").unwrap();
1725 git(&work, &["add", "a.ts"]);
1726 git(&work, &["commit", "-qm", "chore: a"]);
1727 let head = git(&work, &["rev-parse", "HEAD"]);
1728 let tree = git(&work, &["rev-parse", "HEAD^{tree}"]);
1729 let push_ref = PushRef {
1730 local_ref: "refs/heads/main".into(),
1731 local_oid: head.clone(),
1732 remote_ref: "refs/heads/main".into(),
1733 remote_oid: "0".repeat(40),
1734 };
1735 in_repo(&work, || {
1736 attest_push(
1737 &test_settings(),
1738 "origin",
1739 &[push_ref],
1740 &["pre-push-run-tests-js".into()],
1741 &[],
1742 );
1743 });
1744 let body = git(&remote, &["notes", "--ref", NOTES_REF, "show", &head]);
1746 assert!(!body.is_empty(), "no note reached the remote");
1747 let (p, sig) = body
1748 .split_once("\n\n")
1749 .expect("payload, blank line, signature");
1750 let p = format!("{p}\n"); assert!(p.starts_with(FORMAT));
1752 assert!(
1753 p.contains(&format!("tree {tree}")),
1754 "attests the pushed tree"
1755 );
1756 assert!(
1757 verify(&p, sig, &signers, "t@t.test"),
1758 "the remote copy verifies"
1759 );
1760 scratch_cleanup(&d);
1761 scratch_cleanup(&work);
1762 }
1763
1764 #[test]
1771 fn a_push_with_a_spec_publishes_the_inputs_ref() {
1772 let (_d, work, remote, _) = remote_and_work("inputs");
1773 std::fs::create_dir_all(work.join(".github")).unwrap();
1774 std::fs::write(
1775 work.join(".github/attest-inputs"),
1776 "pre-push-run-tests-js a.ts\n",
1777 )
1778 .unwrap();
1779 git(&work, &["add", ".github/attest-inputs"]);
1780 git(&work, &["commit", "-qm", "chore: spec"]);
1781 in_repo(&work, || {
1782 attest_push(
1783 &test_settings(),
1784 "origin",
1785 &[push_ref_for(&work)],
1786 &["pre-push-run-tests-js".into()],
1787 &[],
1788 );
1789 });
1790 let listed = git(&remote, &["notes", "--ref", INPUTS_REF, "list"]);
1791 assert!(
1793 !listed.trim().is_empty(),
1794 "the inputs ref reached the remote"
1795 );
1796 }
1797
1798 #[test]
1799 fn no_opt_in_means_no_note() {
1800 let d = dir("optout");
1801 let (key, _) = keypair(&d);
1802 let remote = d.join("remote.git");
1803 std::fs::create_dir_all(&remote).unwrap();
1804 git(&remote, &["init", "-q", "--bare", "--template=", "."]);
1805 let work = repo("optout-work");
1806 git(
1807 &work,
1808 &["remote", "add", "origin", remote.to_str().unwrap()],
1809 );
1810 git(
1811 &work,
1812 &["config", "greengate.attestKey", key.to_str().unwrap()],
1813 );
1814 std::fs::write(work.join("a.ts"), "x").unwrap();
1815 git(&work, &["add", "a.ts"]);
1816 git(&work, &["commit", "-qm", "chore: a"]);
1817 let head = git(&work, &["rev-parse", "HEAD"]);
1818 let push_ref = PushRef {
1819 local_ref: "refs/heads/main".into(),
1820 local_oid: head.clone(),
1821 remote_ref: "refs/heads/main".into(),
1822 remote_oid: "0".repeat(40),
1823 };
1824 in_repo(&work, || {
1825 attest_push(
1826 &test_settings(),
1827 "origin",
1828 &[push_ref],
1829 &["pre-push-run-tests-js".into()],
1830 &[],
1831 );
1832 });
1833 assert!(
1834 git(&remote, &["notes", "--ref", NOTES_REF, "list"]).is_empty(),
1835 "an un-opted-in repo attested something"
1836 );
1837 scratch_cleanup(&d);
1838 scratch_cleanup(&work);
1839 }
1840
1841 #[test]
1844 fn deletions_and_empty_gates_attest_nothing() {
1845 let d = dir("nothing");
1846 let (key, _) = keypair(&d);
1847 let remote = d.join("remote.git");
1848 std::fs::create_dir_all(&remote).unwrap();
1849 git(&remote, &["init", "-q", "--bare", "--template=", "."]);
1850 let work = repo("nothing-work");
1851 git(
1852 &work,
1853 &["remote", "add", "origin", remote.to_str().unwrap()],
1854 );
1855 git(&work, &["config", "greengate.attest", "true"]);
1856 git(
1857 &work,
1858 &["config", "greengate.attestKey", key.to_str().unwrap()],
1859 );
1860 std::fs::write(work.join("a.ts"), "x").unwrap();
1861 git(&work, &["add", "a.ts"]);
1862 git(&work, &["commit", "-qm", "chore: a"]);
1863 let head = git(&work, &["rev-parse", "HEAD"]);
1864 let deletion = PushRef {
1865 local_ref: "(delete)".into(),
1866 local_oid: "0".repeat(40),
1867 remote_ref: "refs/heads/gone".into(),
1868 remote_oid: head.clone(),
1869 };
1870 let real = PushRef {
1871 local_ref: "refs/heads/main".into(),
1872 local_oid: head,
1873 remote_ref: "refs/heads/main".into(),
1874 remote_oid: "0".repeat(40),
1875 };
1876 in_repo(&work, || {
1877 attest_push(
1878 &test_settings(),
1879 "origin",
1880 &[deletion],
1881 &["pre-push-pytest".into()],
1882 &[],
1883 );
1884 attest_push(&test_settings(), "origin", &[real], &[], &[]);
1885 });
1886 assert!(git(&remote, &["notes", "--ref", NOTES_REF, "list"]).is_empty());
1887 scratch_cleanup(&d);
1888 scratch_cleanup(&work);
1889 }
1890
1891 #[test]
1898 fn a_rejection_is_a_note_whose_signature_did_not_verify() {
1899 let trail: Vec<String> = [
1900 "note on abc123: signature did not verify for principal t@t.test",
1901 "note on abc123 block 2: no principal matched",
1902 "note on def456 carries no signature block",
1903 "attested tree abc is not the checked-out tree def and neither its canonical tree nor an input fingerprint of abc123 matches",
1904 "no attestation found for tree abc",
1905 ]
1906 .iter()
1907 .map(|s| s.to_string())
1908 .collect();
1909 assert_eq!(
1910 signature_rejections(&trail),
1911 vec![
1912 "note on abc123: signature did not verify for principal t@t.test".to_string(),
1913 "note on abc123 block 2: no principal matched".to_string(),
1914 ]
1915 );
1916 }
1917
1918 #[test]
1919 fn covered_answers_in_a_fresh_clone_and_rejects_drift_and_forgery() {
1920 let d = dir("covered");
1921 let (key, signers) = keypair(&d);
1922 let remote = d.join("remote.git");
1923 std::fs::create_dir_all(&remote).unwrap();
1924 git(&remote, &["init", "-q", "--bare", "--template=", "."]);
1925 git(&remote, &["symbolic-ref", "HEAD", "refs/heads/main"]);
1931 let work = repo("covered-work");
1932 git(
1933 &work,
1934 &["remote", "add", "origin", remote.to_str().unwrap()],
1935 );
1936 git(&work, &["config", "greengate.attest", "true"]);
1937 git(
1938 &work,
1939 &["config", "greengate.attestKey", key.to_str().unwrap()],
1940 );
1941 std::fs::write(work.join("a.ts"), "x").unwrap();
1942 git(&work, &["add", "a.ts"]);
1943 git(&work, &["commit", "-qm", "chore: a"]);
1944 git(&work, &["push", "-q", "origin", "HEAD:main"]);
1945 let head = git(&work, &["rev-parse", "HEAD"]);
1946 let push_ref = PushRef {
1947 local_ref: "refs/heads/main".into(),
1948 local_oid: head.clone(),
1949 remote_ref: "refs/heads/main".into(),
1950 remote_oid: "0".repeat(40),
1951 };
1952 in_repo(&work, || {
1953 attest_push(
1954 &test_settings(),
1955 "origin",
1956 &[push_ref],
1957 &["pre-push-pytest".into()],
1958 &[],
1959 );
1960 });
1961 let clone = d.join("ci-checkout");
1962 git(
1963 &d,
1964 &[
1965 "clone",
1966 "-q",
1967 "--template=",
1968 remote.to_str().unwrap(),
1969 clone.to_str().unwrap(),
1970 ],
1971 );
1972 in_repo(&clone, || {
1973 assert_eq!(
1974 covered(&signers, Some("t@t.test"), Some(&platform()), &[]).as_deref(),
1975 Some("pre-push-pytest"),
1976 "a fresh clone verifies the attestation and reads the gates"
1977 );
1978 assert_eq!(
1979 covered(&signers, Some("t@t.test"), None, &[]).as_deref(),
1980 Some("pre-push-pytest"),
1981 "`any` covers a platform-independent suite"
1982 );
1983 assert_eq!(
1986 covered(&signers, Some("t@t.test"), Some("s390x-aix"), &[]),
1987 None,
1988 "a pass on one platform is not evidence about another"
1989 );
1990 assert_eq!(
1991 covered(&signers, Some("someone@else.test"), None, &[]),
1992 None,
1993 "an unlisted principal covers nothing"
1994 );
1995 });
1996 std::fs::write(clone.join("b.ts"), "y").unwrap();
1998 git(&clone, &["config", "user.email", "t@t.test"]);
1999 git(&clone, &["config", "user.name", "t"]);
2000 git(&clone, &["add", "b.ts"]);
2001 git(&clone, &["commit", "-qm", "chore: b"]);
2002 in_repo(&clone, || {
2003 assert_eq!(
2004 covered(&signers, Some("t@t.test"), None, &[]),
2005 None,
2006 "drifted tree"
2007 );
2008 });
2009 let head_tree = git(&work, &["rev-parse", "HEAD^{tree}"]);
2019 for object in [&head, &head_tree] {
2020 git(
2021 &work,
2022 &[
2023 "notes", "--ref", NOTES_REF, "add", "-f", "-m", "garbage", object,
2024 ],
2025 );
2026 }
2027 git(
2028 &work,
2029 &[
2030 "push",
2031 "-q",
2032 "origin",
2033 &format!("+{NOTES_FULL_REF}:{NOTES_FULL_REF}"),
2034 ],
2035 );
2036 git(
2040 &work,
2041 &["push", "-q", "origin", &format!(":{INPUTS_FULL_REF}")],
2042 );
2043 git(&clone, &["reset", "-q", "--hard", &head]);
2044 in_repo(&clone, || {
2045 assert_eq!(
2046 covered(&signers, Some("t@t.test"), None, &[]),
2047 None,
2048 "a foreign note is not a stamp"
2049 );
2050 });
2051 scratch_cleanup(&d);
2052 scratch_cleanup(&work);
2053 }
2054
2055 #[test]
2061 fn default_signers_is_found_from_a_subdirectory() {
2062 let work = repo("signers-subdir");
2063 std::fs::create_dir_all(work.join(".forgejo")).unwrap();
2064 std::fs::write(work.join(".forgejo/allowed_signers"), "t@t.test x\n").unwrap();
2065 let sub = work.join("packages").join("thing");
2066 std::fs::create_dir_all(&sub).unwrap();
2067 in_repo(&sub, || {
2068 let found = default_signers().expect("resolved from the repo root, not the cwd");
2069 assert!(found.ends_with(".forgejo/allowed_signers"));
2070 assert!(found.exists(), "the path it returns must be usable as-is");
2071 });
2072 scratch_cleanup(&work);
2073 }
2074
2075 #[test]
2076 fn zero_oids_of_any_width_are_zero() {
2077 assert!(is_zero(&"0".repeat(40)));
2078 assert!(is_zero(&"0".repeat(64)));
2079 assert!(!is_zero("0a0000"));
2080 assert!(!is_zero(""));
2081 }
2082
2083 #[test]
2084 fn forget_removes_the_local_ref() {
2085 let work = repo("forget");
2086 std::fs::write(work.join("a.ts"), "x").unwrap();
2087 git(&work, &["add", "a.ts"]);
2088 git(&work, &["commit", "-qm", "chore: a"]);
2089 git(
2090 &work,
2091 &["notes", "--ref", NOTES_REF, "add", "-m", "x", "HEAD"],
2092 );
2093 in_repo(&work, forget);
2094 assert!(git(&work, &["notes", "--ref", NOTES_REF, "list"]).is_empty());
2095 scratch_cleanup(&work);
2096 }
2097
2098 pub(crate) fn both_names_signer(dir: &Path) -> (PathBuf, PathBuf) {
2110 let key = dir.join("signer_key");
2111 let ok = std::process::Command::new("ssh-keygen")
2112 .args(["-q", "-t", "ed25519", "-N", "", "-C", "test", "-f"])
2113 .arg(&key)
2114 .status()
2115 .expect("ssh-keygen must exist for these tests")
2116 .success();
2117 assert!(ok, "keygen failed");
2118 let pubkey = std::fs::read_to_string(key.with_extension("pub")).unwrap();
2119 let signers = dir.join("allowed_signers");
2120 std::fs::write(
2121 &signers,
2122 format!(
2123 "cluster-signer@{} namespaces=\"{},{}\" {pubkey}",
2124 crate::cluster::PLATFORM,
2125 git_attest::format::LEGACY.namespace,
2126 git_attest::format::GREEN.namespace
2127 ),
2128 )
2129 .unwrap();
2130 (key, signers)
2131 }
2132
2133 pub(crate) fn block_with(header: &str, namespace: &str, tree: &str, key: &Path) -> String {
2135 let payload = format!(
2136 "{header}\ntree {tree}\ngates suite\nplatform {}\ngreengate 0.0.0\n",
2137 crate::cluster::PLATFORM
2138 );
2139 let sig = git_attest::sign::sign(namespace, &payload, key).expect("sign");
2140 block(&payload, &sig)
2141 }
2142
2143 #[test]
2144 fn a_signer_block_is_checked_under_the_namespace_its_header_names() {
2145 use git_attest::format::{GREEN, LEGACY};
2146 let scratch = dir("signer-names");
2147 let (key, signers) = both_names_signer(&scratch);
2148 let tree = "0123456789012345678901234567890123456789";
2149 for set in [GREEN, LEGACY] {
2150 let body = block_with(set.format, set.namespace, tree, &key);
2151 let checked = signer_block(&body, tree, &signers)
2152 .unwrap_or_else(|e| panic!("{}: {}", set.format, e.reason()));
2153 assert_eq!(checked.names, set);
2154 assert_eq!(checked.gates, ["suite"]);
2155 }
2156 for (header, signed_under) in [(LEGACY, GREEN), (GREEN, LEGACY)] {
2157 let body = block_with(header.format, signed_under.namespace, tree, &key);
2158 assert!(
2159 matches!(
2160 signer_block(&body, tree, &signers),
2161 Err(BlockRefusal::Signer(_))
2162 ),
2163 "a {} block signed under {} must be refused",
2164 header.format,
2165 signed_under.namespace
2166 );
2167 }
2168 scratch_cleanup(&scratch);
2169 }
2170
2171 #[test]
2172 fn forget_in_removes_the_notes_ref_of_both_name_sets() {
2173 let repo_dir = repo("forget-both");
2174 git(&repo_dir, &["commit", "-q", "--allow-empty", "-m", "c"]);
2175 for names in READ_NAMES {
2176 git(
2177 &repo_dir,
2178 &["notes", "--ref", names.notes_ref, "add", "-m", "x", "HEAD"],
2179 );
2180 }
2181 assert!(forget_in(&repo_dir));
2182 for names in READ_NAMES {
2183 let full = format!("refs/notes/{}", names.notes_ref);
2184 let out = std::process::Command::new("git")
2185 .arg("-C")
2186 .arg(&repo_dir)
2187 .args(["rev-parse", "--verify", "-q", &full])
2188 .output()
2189 .unwrap();
2190 assert!(!out.status.success(), "{full} survived forget_in");
2191 }
2192 scratch_cleanup(&repo_dir);
2193 }
2194
2195 #[test]
2196 fn filed_signer_blocks_drops_a_block_of_the_other_name_set() {
2197 use git_attest::format::{GREEN, LEGACY};
2198 let work = repo("filed-names");
2199 std::fs::write(work.join("a.txt"), "x").unwrap();
2200 git(&work, &["add", "a.txt"]);
2201 git(&work, &["commit", "-qm", "chore: a"]);
2202 let (key, signers) = both_names_signer(&work);
2203 std::fs::create_dir_all(work.join(".forgejo")).unwrap();
2204 std::fs::copy(&signers, work.join(".forgejo/allowed_signers")).unwrap();
2205 let tree = git(&work, &["rev-parse", "HEAD^{tree}"]);
2206 let green = block_with(GREEN.format, GREEN.namespace, &tree, &key);
2207 let legacy = block_with(LEGACY.format, LEGACY.namespace, &tree, &key);
2208 in_repo(&work, || {
2209 file_signer_block(&legacy, &[&tree]).expect("file the legacy block");
2210 assert!(
2211 filed_signer_blocks(&tree).is_empty(),
2212 "a legacy block is not publishable while WRITE is green"
2213 );
2214 file_signer_block(&format!("{legacy}\n{green}"), &[&tree]).expect("file both");
2215 let kept = filed_signer_blocks(&tree);
2216 assert_eq!(kept.len(), 1, "{kept:?}");
2217 assert_eq!(kept[0].names, git_attest::format::WRITE);
2218 assert_eq!(kept[0].names, GREEN);
2219 assert!(kept[0].is_publishable());
2220 });
2221 scratch_cleanup(&work);
2222 }
2223
2224 #[test]
2225 fn a_verification_says_which_name_it_went_through() {
2226 let mut verdict = git_attest::verify::Verdict::nothing("test");
2227 assert!(verified_lines(&verdict).is_empty());
2228 verdict.verified_under = vec![
2229 git_attest::format::GREEN.namespace.to_string(),
2230 git_attest::format::LEGACY.namespace.to_string(),
2231 ];
2232 assert_eq!(
2233 verified_lines(&verdict),
2234 [
2235 format!("verified under {}", git_attest::format::GREEN.namespace),
2236 format!("verified under {}", git_attest::format::LEGACY.namespace),
2237 ]
2238 );
2239 }
2240}