1use crate::names::BIN;
38use std::path::{Path, PathBuf};
39
40use greensummit::format::block;
41use greensummit::notes::{publish as publish_notes, Publish, Published};
42use greensummit::produce::attestation;
43
44use crate::pushrefs::PushRef;
45
46pub use greensummit::format::{platform, FORMAT, INPUTS_REF, NAMESPACE, NOTES_REF};
47pub use greensummit::notes::{classify_push as classify_push_stderr, PushFailure};
48
49pub const NOTES_FULL_REF: &str = "refs/notes/greensummit";
52pub const INPUTS_FULL_REF: &str = "refs/notes/greensummit-inputs";
53
54pub(crate) const PRE_SUMMIT_HEADERS: [&str; 2] = ["greengate-attest-v2", "amont-attest-v2"];
58
59const PROVENANCE_LEGACY_FORMAT: &str = "amont-provenance-v1";
64
65pub const PROVENANCE_REF: &str = "greengate-provenance";
71pub const PROVENANCE_FULL_REF: &str = "refs/notes/greengate-provenance";
72pub const PROVENANCE_NAMESPACE: &str = "greengate-provenance";
73pub const PROVENANCE_FORMAT: &str = "greengate-provenance-v1";
74
75pub const PUSH_GUARD: &str = "GREENGATE_ATTEST_PUSH";
78
79fn here() -> &'static Path {
81 Path::new(".")
82}
83
84const TOGGLE: &str = "greengate.attest";
88
89pub(crate) const KEY_CONFIG: &str = "greengate.attestKey";
91const KEY_DEFAULT: &str = ".ssh/greengate-attest";
93const KEY_FALLBACK: &str = ".ssh/amont-attest";
96
97pub fn push_guard_active() -> bool {
99 std::env::var_os(PUSH_GUARD).is_some()
100}
101
102pub fn enabled(settings: &crate::config::Settings) -> bool {
104 crate::config::boolean_or(settings, TOGGLE, false)
105}
106
107fn key_path() -> Option<PathBuf> {
114 if let Some(k) = crate::git::stdout(&["config", "--get", KEY_CONFIG]) {
115 if !k.is_empty() {
116 return Some(PathBuf::from(k));
117 }
118 }
119 let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE"))?;
120 Some(default_key_in(Path::new(&home)))
121}
122
123fn default_key_in(home: &Path) -> PathBuf {
127 let green = home.join(KEY_DEFAULT);
128 let old = home.join(KEY_FALLBACK);
129 if !green.exists() && old.exists() {
130 old
131 } else {
132 green
133 }
134}
135
136pub fn key_move_hint_in(home: &Path) -> Option<String> {
140 (!home.join(KEY_DEFAULT).exists() && home.join(KEY_FALLBACK).exists()).then(|| {
141 format!(
142 "the signing key is still ~/{KEY_FALLBACK}; rename it: mv ~/{KEY_FALLBACK} ~/{KEY_DEFAULT} (and the .pub beside it)"
143 )
144 })
145}
146
147pub fn attest_push(
175 settings: &crate::config::Settings,
176 remote: &str,
177 refs: &[PushRef],
178 gates: &[String],
179 cluster_gates: &[String],
180) {
181 attest_push_per_tip(settings, remote, refs, &|_| gates.to_vec(), cluster_gates);
182}
183
184pub fn attest_push_per_tip(
189 settings: &crate::config::Settings,
190 remote: &str,
191 refs: &[PushRef],
192 gates_for: &dyn Fn(&str) -> Vec<String>,
193 cluster_gates: &[String],
194) {
195 if remote.is_empty() || !enabled(settings) {
196 return;
197 }
198 let Some(key) = key_path() else { return };
199 if !key.exists() {
200 crate::config::complain(
201 TOGGLE,
202 &format!("signing key {} does not exist", key.display()),
203 "no attestation (CI will run the tests)",
204 );
205 return;
206 }
207 let producer = env!("CARGO_PKG_VERSION");
208 let mut laptop_signed: Vec<String> = Vec::new();
210 let mut blocks: Vec<(String, String)> = Vec::new();
211 let mut input_blocks: Vec<(String, String)> = Vec::new();
212 let mut linux_signed: Vec<String> = Vec::new();
213 let (mut n_inputs, mut n_canon) = (0, 0);
214 let in_cluster = std::cell::OnceCell::new();
216 for r in refs {
217 if is_zero(&r.local_oid) {
218 continue; }
220 let gates = gates_for(&r.local_oid);
221 if gates.is_empty() && cluster_gates.is_empty() {
222 continue;
223 }
224 let gates_line = gates.join(" ");
225 let spec = format!("{}^{{tree}}", r.local_oid);
226 let Some(tree) = crate::git::stdout(&["rev-parse", &spec]) else {
227 continue;
228 };
229 let mut proved_here: Vec<String> = cluster_gates
230 .iter()
231 .filter(|g| crate::cluster::proved(g, &tree))
232 .cloned()
233 .collect();
234 if !proved_here.is_empty()
238 && *in_cluster.get_or_init(|| crate::cluster::in_cluster_signer().is_some())
239 {
240 for signed in filed_signer_blocks(&tree) {
241 let (covered, rest): (Vec<String>, Vec<String>) = proved_here
242 .into_iter()
243 .partition(|g| signed.gates.contains(g));
244 proved_here = rest;
245 if covered.is_empty() {
246 continue;
247 }
248 for name in covered {
249 if !linux_signed.contains(&name) {
250 linux_signed.push(name);
251 }
252 }
253 blocks.push((tree.clone(), signed.body.clone()));
254 blocks.push((r.local_oid.clone(), signed.body));
255 }
256 }
257 let platforms = [
258 (platform(), gates_line.clone(), Vec::new()),
259 (
260 crate::cluster::PLATFORM.to_string(),
261 proved_here.join(" "),
262 proved_here,
263 ),
264 ];
265 let mut counted = false;
268 for (on, line, linux_names) in platforms {
269 if line.is_empty() {
270 continue;
271 }
272 let mut reasons = Vec::new();
275 let att = attestation(here(), &tree, &line, &on, producer, &mut reasons);
276 let Ok(sig) = greensummit::sign::sign(NAMESPACE, &att.payload, &key) else {
277 continue;
278 };
279 let body = block(&att.payload, &sig);
280 if !counted {
281 n_inputs += att.inputs.len();
282 n_canon += usize::from(att.canon.is_some());
283 counted = true;
284 }
285 for k in &att.input_keys {
286 input_blocks.push((k.clone(), body.clone()));
287 }
288 blocks.push((tree.clone(), body.clone()));
289 blocks.push((r.local_oid.clone(), body));
290 if linux_names.is_empty() {
291 for name in &gates {
292 if !laptop_signed.contains(name) {
293 laptop_signed.push(name.clone());
294 }
295 }
296 }
297 for name in linux_names {
298 if !linux_signed.contains(&name) {
299 linux_signed.push(name);
300 }
301 }
302 }
303 }
304 if blocks.is_empty() {
305 return;
306 }
307 let main_ok = publish(remote, NOTES_REF, &blocks);
311 let inputs_ok = input_blocks.is_empty() || publish(remote, INPUTS_REF, &input_blocks);
312 if main_ok {
313 let mut signed_on = Vec::new();
316 if !laptop_signed.is_empty() {
317 signed_on.push(format!(
318 "{} on {}",
319 crate::ui::highlight(&laptop_signed.join(" ")),
320 platform()
321 ));
322 }
323 if !linux_signed.is_empty() {
324 signed_on.push(format!(
325 "{} on {}",
326 crate::ui::highlight(&linux_signed.join(" ")),
327 crate::cluster::PLATFORM
328 ));
329 }
330 let what = signed_on.join("; ");
331 crate::say!(
332 "{} attested {} for CI ({}{})",
333 crate::ui::valid_sign(),
334 what,
335 NOTES_REF,
336 if input_blocks.is_empty() {
337 String::new()
338 } else if inputs_ok {
339 match (n_inputs, n_canon) {
340 (0, _) => ", canonical tree".to_string(),
341 (n, 0) => format!(", {n} input fingerprints"),
342 (n, _) => format!(", {n} input fingerprints, canonical tree"),
343 }
344 } else {
345 ", input fingerprints not published".to_string()
346 },
347 );
348 }
349}
350
351const PROVENANCE_OWNER: &str = "greenbelay";
353const OLD_PROVENANCE_OWNER: &str = "amont-agent";
357
358fn provenance_dirs(env: impl Fn(&str) -> Option<std::ffi::OsString>) -> Option<[PathBuf; 2]> {
368 let config = match env("CLAUDE_CONFIG_DIR") {
369 Some(d) => PathBuf::from(d),
370 None => PathBuf::from(env("HOME").or_else(|| env("USERPROFILE"))?).join(".claude"),
371 };
372 Some([PROVENANCE_OWNER, OLD_PROVENANCE_OWNER].map(|o| config.join(o).join("provenance")))
373}
374
375fn read_payload(dirs: &[PathBuf], commit: &str) -> Option<(usize, PathBuf, String)> {
380 for (at, dir) in dirs.iter().enumerate() {
381 let file = dir.join(commit);
382 match std::fs::read_to_string(&file) {
383 Ok(text) => return Some((at, file, text)),
384 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
385 Err(_) => return None,
386 }
387 }
388 None
389}
390
391fn repo_name() -> Option<String> {
396 let common = crate::git::stdout(&["rev-parse", "--git-common-dir"])?;
397 if common.is_empty() {
398 return None;
399 }
400 let common = PathBuf::from(common);
401 let common = if common.is_absolute() {
402 common
403 } else {
404 std::env::current_dir().ok()?.join(common)
405 };
406 let common = std::fs::canonicalize(&common).unwrap_or(common);
407 common
408 .parent()
409 .and_then(std::path::Path::file_name)
410 .map(|n| n.to_string_lossy().into_owned())
411 .filter(|n| !n.is_empty())
412}
413
414pub fn provenance_push(settings: &crate::config::Settings, remote: &str, refs: &[PushRef]) {
419 if remote.is_empty() || !enabled(settings) {
420 return;
421 }
422 let (Some(dirs), Some(name)) = (provenance_dirs(|k| std::env::var_os(k)), repo_name()) else {
423 return;
424 };
425 provenance_push_from_dirs(&dirs.map(|d| d.join(&name)), remote, refs);
426}
427
428#[cfg(test)]
430fn provenance_push_from(dir: &std::path::Path, remote: &str, refs: &[PushRef]) {
431 provenance_push_from_dirs(&[dir.to_path_buf()], remote, refs);
432}
433
434fn provenance_push_from_dirs(dirs: &[PathBuf], remote: &str, refs: &[PushRef]) {
437 let mut found: Vec<PendingRecord> = Vec::new();
438 let mut named_old = false;
439 for r in refs {
440 if is_zero(&r.local_oid) {
441 continue;
442 }
443 let Some((at, file, payload)) = read_payload(dirs, &r.local_oid) else {
444 continue; };
446 if at > 0 && !named_old {
447 named_old = true;
448 crate::say!(
449 " provenance read from {} (amont-agent's directory, until greenbelay migrates it)",
450 dirs[at].display()
451 );
452 }
453 let spec = format!("{}^{{tree}}", r.local_oid);
454 let Some(tree) = crate::git::stdout(&["rev-parse", &spec]) else {
455 continue;
456 };
457 let first = payload.lines().next().unwrap_or_default();
458 let claimed = payload.lines().find_map(|l| l.strip_prefix("tree "));
459 if first == PROVENANCE_LEGACY_FORMAT {
463 crate::say!("{}", legacy_provenance_line(&r.local_oid, &file));
464 continue;
465 }
466 if first != PROVENANCE_FORMAT || claimed != Some(tree.as_str()) {
467 crate::say!(
468 " provenance for {} not signed: its payload is not a {PROVENANCE_FORMAT} record of this tree",
469 &r.local_oid[..r.local_oid.len().min(7)]
470 );
471 continue;
472 }
473 if payload
477 .lines()
478 .any(|l| l.split_ascii_whitespace().next() == Some("canon"))
479 {
480 for line in canon_refusal(&r.local_oid, &file) {
481 crate::say!("{line}");
482 }
483 continue;
484 }
485 let Ok(canon) = greensummit::fingerprint::canon(here(), &tree) else {
488 crate::say!(
489 " provenance for {} not signed: its canonical tree cannot be computed;",
490 &r.local_oid[..r.local_oid.len().min(7)]
491 );
492 crate::say!(" the payload is kept for the next push");
493 continue;
494 };
495 let payload = with_canon(&payload, &canon);
496 found.push(PendingRecord {
497 file,
498 commit: r.local_oid.clone(),
499 tree,
500 payload,
501 });
502 }
503 if found.is_empty() {
504 return;
505 }
506 let Some(key) = key_path().filter(|k| k.exists()) else {
507 crate::say!(" provenance not signed: no signing key");
508 return;
509 };
510 let mut blocks: Vec<(String, String)> = Vec::new();
511 let mut signed: Vec<PathBuf> = Vec::new();
512 for rec in found {
513 let sig = match greensummit::sign::sign(PROVENANCE_NAMESPACE, &rec.payload, &key) {
514 Ok(sig) => sig,
515 Err(e) => {
516 crate::say!(
517 " provenance for {} not signed: {e}; kept for the next push",
518 &rec.commit[..rec.commit.len().min(7)]
519 );
520 continue;
521 }
522 };
523 let body = block(&rec.payload, &sig);
524 blocks.push((rec.tree, body.clone()));
525 blocks.push((rec.commit, body));
526 signed.push(rec.file);
527 }
528 if blocks.is_empty() {
529 return; }
531 if publish(remote, PROVENANCE_REF, &blocks) {
532 for file in &signed {
533 if std::fs::remove_file(file).is_err() {
534 crate::say!(
535 " provenance published, but its payload {} could not be removed",
536 file.display()
537 );
538 }
539 }
540 crate::say!(
541 "{} provenance published ({PROVENANCE_REF})",
542 crate::ui::valid_sign()
543 );
544 } else {
545 crate::say!(" provenance not published: kept for the next push");
546 }
547}
548
549struct PendingRecord {
551 file: PathBuf,
552 commit: String,
553 tree: String,
554 payload: String,
555}
556
557fn legacy_provenance_line(commit: &str, file: &Path) -> String {
560 format!(
561 " provenance for {} not signed: {} was written by an older release of the hook: upgrade greenbelay, then delete {} or re-run its review",
562 &commit[..commit.len().min(7)],
563 file.display(),
564 file.display()
565 )
566}
567
568fn with_canon(payload: &str, canon: &str) -> String {
571 let mut out = String::with_capacity(payload.len() + canon.len() + 7);
572 let mut done = false;
573 for line in payload.split_inclusive('\n') {
574 out.push_str(line);
575 if !done && line.starts_with("tree ") {
576 if !line.ends_with('\n') {
577 out.push('\n');
578 }
579 out.push_str(&format!("canon {canon}\n"));
580 done = true;
581 }
582 }
583 out
584}
585
586fn canon_refusal(commit: &str, file: &std::path::Path) -> Vec<String> {
590 let dir = file.parent().unwrap_or(file).display().to_string();
591 let name = file
592 .file_name()
593 .map(|n| n.to_string_lossy().into_owned())
594 .unwrap_or_default();
595 vec![
596 format!(
597 " provenance for {} not signed: its payload carries a canon line",
598 &commit[..commit.len().min(7)]
599 ),
600 " (a pre-release build of the hook wrote it); delete the file".to_string(),
601 format!(" {name} in"),
602 format!(" {dir}"),
603 " and upgrade greenbelay".to_string(),
604 ]
605}
606
607const PUSH_ATTEMPTS: u32 = 4;
609
610fn publish(remote: &str, notes_ref: &str, blocks: &[(String, String)]) -> bool {
618 let how = Publish {
619 remote,
620 attempts: PUSH_ATTEMPTS,
621 pause: false,
622 identity: None,
623 push_env: &[(PUSH_GUARD, "1")],
624 };
625 let mut log = Vec::new();
626 matches!(
627 publish_notes(here(), &how, notes_ref, blocks, &mut log),
628 Published::Pushed | Published::AlreadyPresent
629 )
630}
631
632pub fn covered(
645 signers: &Path,
646 principal: Option<&str>,
647 require_platform: Option<&str>,
648 anywhere: &[String],
649) -> Option<String> {
650 covered_in(here(), signers, principal, require_platform, anywhere)
651}
652
653pub fn covered_in(
658 dir: &Path,
659 signers: &Path,
660 principal: Option<&str>,
661 require_platform: Option<&str>,
662 anywhere: &[String],
663) -> Option<String> {
664 covered_report(dir, signers, principal, require_platform, anywhere).gates
665}
666
667#[derive(Debug, Clone, PartialEq, Eq, Default)]
672pub struct Covered {
673 pub gates: Option<String>,
674 pub rejected: Vec<String>,
675}
676
677pub fn covered_report(
681 dir: &Path,
682 signers: &Path,
683 principal: Option<&str>,
684 require_platform: Option<&str>,
685 anywhere: &[String],
686) -> Covered {
687 let verdict =
688 greensummit::verify::evaluate(dir, signers, principal, require_platform, anywhere, false);
689 for line in verdict.loud.iter().chain(&verdict.warnings) {
690 eprintln!("{BIN}: {line}");
691 }
692 for line in verified_lines(&verdict) {
693 eprintln!("{BIN}: {line}");
694 }
695 let rejected = signature_rejections(&verdict.trail);
696 for why in &rejected {
697 eprintln!("{BIN}: an attestation was found but did not verify: {why}");
698 }
699 Covered {
700 gates: (!verdict.gates.is_empty()).then(|| verdict.gates.join(" ")),
701 rejected,
702 }
703}
704
705fn verified_lines(verdict: &greensummit::verify::Verdict) -> Vec<String> {
709 verdict
710 .verified_under
711 .iter()
712 .map(|ns| format!("verified under {ns}"))
713 .collect()
714}
715
716fn signature_rejections(trail: &[String]) -> Vec<String> {
721 trail
722 .iter()
723 .filter(|line| line.starts_with("note on ") && line.contains(": "))
724 .cloned()
725 .collect()
726}
727
728#[derive(Debug, Clone, PartialEq, Eq)]
730pub(crate) struct SignerBlock {
731 pub principal: String,
733 pub gates: Vec<String>,
735 pub body: String,
737}
738
739#[derive(Debug, Clone, PartialEq, Eq)]
742pub(crate) enum BlockRefusal {
743 Signer(String),
747 Content(String),
750 StaleSigner(String),
753}
754
755impl BlockRefusal {
756 pub(crate) fn reason(&self) -> &str {
758 match self {
759 BlockRefusal::Signer(why)
760 | BlockRefusal::Content(why)
761 | BlockRefusal::StaleSigner(why) => why,
762 }
763 }
764}
765
766pub(crate) fn signer_block(
772 body: &str,
773 tree: &str,
774 signers: &Path,
775) -> Result<SignerBlock, BlockRefusal> {
776 use greensummit::format::{bound_platform, field, split_blocks};
777 use BlockRefusal::{Content, Signer, StaleSigner};
778 let (mut blocks, _) = split_blocks(body);
779 if blocks.len() != 1 {
780 return Err(Content(format!("{} signed blocks, not one", blocks.len())));
781 }
782 let signed_block = blocks.remove(0);
783 let header = signed_block.payload.split('\n').next();
788 if header != Some(FORMAT) {
789 let header = header.unwrap_or("missing");
790 if PRE_SUMMIT_HEADERS.contains(&header) {
791 return Err(StaleSigner(format!(
792 "a {header} block, written by a greengate older than greensummit 2.0, \
793 not a {FORMAT} one"
794 )));
795 }
796 return Err(Content(format!("not a {FORMAT} payload (header {header})")));
797 }
798 let on = field(&signed_block.payload, "platform");
799 if on != Some(crate::cluster::PLATFORM) {
800 return Err(Content(format!(
801 "its platform is {}, not {}",
802 on.unwrap_or("missing"),
803 crate::cluster::PLATFORM
804 )));
805 }
806 let claimed = field(&signed_block.payload, "tree");
807 if claimed != Some(tree) {
808 return Err(Content(format!(
810 "it is for tree {}, not {tree}",
811 claimed.unwrap_or("missing")
812 )));
813 }
814 let principal = greensummit::sign::verify(
815 NAMESPACE,
816 &signed_block.payload,
817 &signed_block.signature,
818 signers,
819 None,
820 )
821 .map_err(|e| Signer(e.to_string()))?;
822 if bound_platform(&principal) != Some(crate::cluster::PLATFORM) {
823 return Err(Signer(format!(
824 "{principal} is not a principal bound to {}",
825 crate::cluster::PLATFORM
826 )));
827 }
828 Ok(SignerBlock {
829 principal,
830 gates: field(&signed_block.payload, "gates")
831 .unwrap_or("")
832 .split_whitespace()
833 .map(str::to_string)
834 .collect(),
835 body: block(&signed_block.payload, &signed_block.signature),
836 })
837}
838
839fn signer_notes_ref() -> String {
846 format!("{}{NOTES_REF}", greensummit::format::LOCAL_PREFIX)
847}
848
849pub(crate) fn file_signer_block(body: &str, keys: &[&str]) -> Result<(), String> {
855 let notes_ref = signer_notes_ref();
856 for key in keys {
857 let entry = [((*key).to_string(), body.to_string())];
858 if matches!(
859 greensummit::notes::publish_local(here(), None, ¬es_ref, &entry),
860 Published::Error
861 ) {
862 return Err(format!(
863 "git could not write the note on {key} in {notes_ref}"
864 ));
865 }
866 }
867 Ok(())
868}
869
870fn filed_signer_blocks(tree: &str) -> Vec<SignerBlock> {
874 use greensummit::format::{field, split_blocks};
875 let Some(signers) = default_signers() else {
876 return Vec::new();
877 };
878 let notes_ref = signer_notes_ref();
879 let Some(note) = crate::git::stdout(&["notes", "--ref", ¬es_ref, "show", tree]) else {
880 return Vec::new();
881 };
882 split_blocks(¬e)
883 .0
884 .iter()
885 .filter(|b| {
886 field(&b.payload, "platform") == Some(crate::cluster::PLATFORM)
887 && field(&b.payload, "tree") == Some(tree)
888 })
889 .filter_map(|b| signer_block(&block(&b.payload, &b.signature), tree, &signers).ok())
890 .collect()
891}
892
893pub fn default_signers() -> Option<PathBuf> {
896 greensummit::verify::default_signers(here())
897}
898
899fn is_zero(oid: &str) -> bool {
902 !oid.is_empty() && oid.bytes().all(|b| b == b'0')
903}
904
905pub fn forget() -> bool {
909 forget_in(here())
910}
911
912pub fn forget_in(repo: &std::path::Path) -> bool {
914 crate::git::succeeds_in(repo, &["update-ref", "-d", NOTES_FULL_REF])
915}
916
917#[cfg(test)]
918pub(crate) mod tests {
919 use super::*;
920
921 use std::process::Stdio;
922
923 pub(crate) fn scratch_cleanup(path: &Path) {
926 let _ = std::fs::remove_dir_all(path); }
928
929 #[test]
933 fn the_written_names_are_green_and_each_full_ref_names_its_ref() {
934 for (full, short) in [
935 (NOTES_FULL_REF, NOTES_REF),
936 (INPUTS_FULL_REF, INPUTS_REF),
937 (PROVENANCE_FULL_REF, PROVENANCE_REF),
938 ] {
939 assert_eq!(full, format!("refs/notes/{short}"));
940 }
941 assert_eq!(NOTES_FULL_REF, "refs/notes/greensummit");
942 assert_eq!(INPUTS_FULL_REF, "refs/notes/greensummit-inputs");
943 assert_eq!(PROVENANCE_FULL_REF, "refs/notes/greengate-provenance");
944 assert_eq!(greensummit::format::WRITE, greensummit::format::SUMMIT);
945 }
946
947 fn canon(tree: &str) -> Option<String> {
948 greensummit::fingerprint::canon(here(), tree).ok()
949 }
950
951 fn sign(payload: &str, key: &Path) -> Option<String> {
952 greensummit::sign::sign(NAMESPACE, payload, key).ok()
953 }
954
955 fn verify(payload: &str, sig: &str, signers: &Path, principal: &str) -> bool {
956 verify_in(NAMESPACE, payload, sig, signers, principal)
957 }
958
959 fn verify_in(
960 namespace: &str,
961 payload: &str,
962 sig: &str,
963 signers: &Path,
964 principal: &str,
965 ) -> bool {
966 greensummit::sign::verify(namespace, payload, sig, signers, Some(principal)).is_ok()
967 }
968
969 fn test_settings() -> crate::config::Settings {
972 crate::config::Settings::default()
973 }
974
975 use std::io::Write;
976 use std::path::Path;
977
978 pub(crate) fn dir(name: &str) -> PathBuf {
982 let d = std::env::temp_dir().join(format!("attest-{name}-{}", std::process::id()));
983 scratch_cleanup(&d);
984 std::fs::create_dir_all(&d).unwrap();
985 d
986 }
987
988 fn git(dir: &Path, args: &[&str]) -> String {
997 let out = std::process::Command::new("git")
998 .arg("-C")
999 .arg(dir)
1000 .args(args)
1001 .output()
1002 .expect("git");
1003 assert!(
1004 out.status.success(),
1005 "fixture: git {args:?} in {} exited {:?}: {}",
1006 dir.display(),
1007 out.status.code(),
1008 String::from_utf8_lossy(&out.stderr).trim()
1009 );
1010 String::from_utf8_lossy(&out.stdout).trim().to_string()
1011 }
1012
1013 fn repo(name: &str) -> PathBuf {
1014 let d = dir(name);
1015 git(&d, &["init", "-q", "--template=", "."]);
1016 git(&d, &["config", "user.email", "t@t.test"]);
1017 git(&d, &["config", "user.name", "t"]);
1018 d
1019 }
1020
1021 fn keypair(d: &Path) -> (PathBuf, PathBuf) {
1024 let key = d.join("attest_key");
1025 let ok = std::process::Command::new("ssh-keygen")
1026 .args(["-q", "-t", "ed25519", "-N", "", "-C", "test", "-f"])
1027 .arg(&key)
1028 .status()
1029 .expect("ssh-keygen must exist for these tests")
1030 .success();
1031 assert!(ok, "keygen failed");
1032 let pubkey = std::fs::read_to_string(key.with_extension("pub")).unwrap();
1033 let signers = d.join("allowed_signers");
1034 std::fs::write(
1035 &signers,
1036 format!("t@t.test namespaces=\"{NAMESPACE}\" {pubkey}"),
1037 )
1038 .unwrap();
1039 (key, signers)
1040 }
1041
1042 fn in_repo<T>(dir: &Path, f: impl FnOnce() -> T) -> T {
1045 let _guard = crate::TEST_CWD.lock().unwrap_or_else(|p| p.into_inner());
1046 let prev = std::env::current_dir().unwrap();
1047 std::env::set_current_dir(dir).unwrap();
1048 let r = f();
1049 std::env::set_current_dir(prev).unwrap();
1050 r
1051 }
1052
1053 fn remote_and_work(name: &str) -> (PathBuf, PathBuf, PathBuf, PathBuf) {
1055 let d = dir(name);
1056 let (key, signers) = keypair(&d);
1057 let remote = d.join("remote.git");
1058 std::fs::create_dir_all(&remote).unwrap();
1059 git(&remote, &["init", "-q", "--bare", "--template=", "."]);
1060 let work = repo(&format!("{name}-work"));
1061 git(
1062 &work,
1063 &["remote", "add", "origin", remote.to_str().unwrap()],
1064 );
1065 git(&work, &["config", "greengate.attest", "true"]);
1066 git(
1067 &work,
1068 &["config", "greengate.attestKey", key.to_str().unwrap()],
1069 );
1070 std::fs::write(work.join("a.ts"), "x").unwrap();
1071 git(&work, &["add", "a.ts"]);
1072 git(&work, &["commit", "-qm", "chore: a"]);
1073 (d, work, remote, signers)
1074 }
1075
1076 fn push_ref_for(work: &Path) -> PushRef {
1077 PushRef {
1078 local_ref: "refs/heads/main".into(),
1079 local_oid: git(work, &["rev-parse", "HEAD"]),
1080 remote_ref: "refs/heads/main".into(),
1081 remote_oid: "0".repeat(40),
1082 }
1083 }
1084
1085 #[test]
1086 fn each_payload_is_read_from_the_new_dir_first_then_the_old() {
1087 let config = dir("provenance-names");
1088 let new = config.join("greenbelay/provenance/r");
1089 let old = config.join("amont-agent/provenance/r");
1090 let dirs = [new.clone(), old.clone()];
1091 assert_eq!(read_payload(&dirs, "c1"), None, "neither holds it");
1092 std::fs::create_dir_all(&old).unwrap();
1093 std::fs::write(old.join("c1"), "old").unwrap();
1094 assert_eq!(
1095 read_payload(&dirs, "c1"),
1096 Some((1, old.join("c1"), "old".into())),
1097 "old alone"
1098 );
1099 std::fs::create_dir_all(&new).unwrap();
1101 assert_eq!(read_payload(&dirs, "c1").map(|(at, ..)| at), Some(1));
1102 std::fs::write(new.join("c1"), "new").unwrap();
1103 assert_eq!(
1104 read_payload(&dirs, "c1"),
1105 Some((0, new.join("c1"), "new".into())),
1106 "both: the new"
1107 );
1108 std::fs::create_dir_all(new.join("c2")).unwrap();
1110 std::fs::write(old.join("c2"), "old").unwrap();
1111 assert_eq!(read_payload(&dirs, "c2"), None);
1112 }
1113
1114 #[test]
1115 fn the_provenance_dir_is_resolved_like_greenbelays_config_dir() {
1116 use std::ffi::OsString;
1117 let env = |pairs: &'static [(&'static str, &'static str)]| {
1118 move |k: &str| {
1119 pairs
1120 .iter()
1121 .find(|(n, _)| *n == k)
1122 .map(|(_, v)| OsString::from(v))
1123 }
1124 };
1125 assert_eq!(
1126 provenance_dirs(env(&[("CLAUDE_CONFIG_DIR", "/c"), ("HOME", "/h")])),
1127 Some([
1128 PathBuf::from("/c/greenbelay/provenance"),
1129 PathBuf::from("/c/amont-agent/provenance")
1130 ])
1131 );
1132 assert_eq!(
1133 provenance_dirs(env(&[("HOME", "/h"), ("USERPROFILE", "/u")])),
1134 Some([
1135 PathBuf::from("/h/.claude/greenbelay/provenance"),
1136 PathBuf::from("/h/.claude/amont-agent/provenance")
1137 ])
1138 );
1139 assert_eq!(
1140 provenance_dirs(env(&[("USERPROFILE", "/u")])),
1141 Some([
1142 PathBuf::from("/u/.claude/greenbelay/provenance"),
1143 PathBuf::from("/u/.claude/amont-agent/provenance")
1144 ])
1145 );
1146 assert_eq!(provenance_dirs(env(&[])), None);
1147 }
1148
1149 fn provenance_world(name: &str) -> (PathBuf, PathBuf, PathBuf, String, String, PathBuf) {
1153 provenance_world_in(name, None)
1154 }
1155
1156 fn provenance_world_in(
1158 name: &str,
1159 object_format: Option<&str>,
1160 ) -> (PathBuf, PathBuf, PathBuf, String, String, PathBuf) {
1161 let d = dir(name);
1162 let (key, _) = keypair(&d);
1163 let pubkey = std::fs::read_to_string(key.with_extension("pub")).unwrap();
1164 let signers = d.join("allowed_signers_provenance");
1165 std::fs::write(
1166 &signers,
1167 format!("t@t.test namespaces=\"{NAMESPACE},{PROVENANCE_NAMESPACE}\" {pubkey}"),
1168 )
1169 .unwrap();
1170 let remote = d.join("remote.git");
1171 std::fs::create_dir_all(&remote).unwrap();
1172 let fmt = format!("--object-format={}", object_format.unwrap_or("sha1"));
1173 git(&remote, &["init", "-q", "--bare", "--template=", &fmt, "."]);
1174 let work = match object_format {
1175 None => repo(&format!("{name}-work")),
1176 Some(f) => {
1177 let w = dir(&format!("{name}-work"));
1178 let fmt = format!("--object-format={f}");
1179 git(&w, &["init", "-q", "--template=", &fmt, "."]);
1180 git(&w, &["config", "user.email", "t@t.test"]);
1181 git(&w, &["config", "user.name", "t"]);
1182 w
1183 }
1184 };
1185 git(
1186 &work,
1187 &["remote", "add", "origin", remote.to_str().unwrap()],
1188 );
1189 git(&work, &["config", "greengate.attest", "true"]);
1190 git(
1191 &work,
1192 &["config", "greengate.attestKey", key.to_str().unwrap()],
1193 );
1194 std::fs::write(work.join("README.md"), "words").unwrap();
1195 std::fs::create_dir_all(work.join("docs/plans")).unwrap();
1196 std::fs::write(work.join("docs/plans/p.md"), "# P\n").unwrap();
1197 git(&work, &["add", "README.md", "docs/plans/p.md"]);
1198 git(&work, &["commit", "-qm", "docs: words"]);
1199 let head = git(&work, &["rev-parse", "HEAD"]);
1200 let tree = git(&work, &["rev-parse", "HEAD^{tree}"]);
1201 (d, work, remote, head, tree, signers)
1202 }
1203
1204 fn record(head: &str, tree: &str) -> String {
1205 format!(
1206 "{PROVENANCE_FORMAT}\ncommit {head}\ntree {tree}\n\
1207 plan docs/plans/p.md {}\nreview reviewed {}\npreview not-required\n\
1208 producer amont-agent 0.0.0\n",
1209 "a".repeat(64),
1210 "c".repeat(64)
1211 )
1212 }
1213
1214 fn canon_by_hand(work: &Path, tree: &str) -> String {
1218 let listing = git(
1219 work,
1220 &[
1221 "-c",
1222 "core.quotePath=true",
1223 "ls-tree",
1224 "-r",
1225 "--full-tree",
1226 tree,
1227 ],
1228 );
1229 let mut text = String::new();
1230 for line in listing.lines() {
1231 let (head, path) = line.split_once('\t').unwrap();
1232 let f: Vec<&str> = head.split(' ').collect();
1233 let plan = matches!(f[0], "100644" | "100755")
1234 && (path.starts_with("docs/plans/") || path.starts_with("\"docs/plans/"));
1235 if plan {
1236 text.push_str(&format!(
1237 "{} {} {}\t{path}\n",
1238 f[0],
1239 f[1],
1240 "0".repeat(f[2].len())
1241 ));
1242 } else {
1243 text.push_str(&format!("{line}\n"));
1244 }
1245 }
1246 let mut child = std::process::Command::new("git")
1247 .arg("-C")
1248 .arg(work)
1249 .args(["hash-object", "--stdin"])
1250 .stdin(Stdio::piped())
1251 .stdout(Stdio::piped())
1252 .spawn()
1253 .unwrap();
1254 child
1255 .stdin
1256 .take()
1257 .unwrap()
1258 .write_all(text.as_bytes())
1259 .unwrap();
1260 let out = child.wait_with_output().unwrap();
1261 String::from_utf8_lossy(&out.stdout).trim().to_string()
1262 }
1263
1264 fn provenance_payload(remote: &Path, object: &str) -> (String, String) {
1266 let note = git(remote, &["notes", "--ref", PROVENANCE_REF, "show", object]);
1267 let (p, sig) = note
1268 .split_once("\n\n")
1269 .expect("payload, blank line, signature");
1270 (format!("{p}\n"), sig.to_string())
1271 }
1272
1273 fn push_of(head: &str) -> PushRef {
1274 PushRef {
1275 local_ref: "refs/heads/feat/x".into(),
1276 local_oid: head.to_string(),
1277 remote_ref: "refs/heads/feat/x".into(),
1278 remote_oid: "0".repeat(40),
1279 }
1280 }
1281
1282 #[test]
1286 fn a_provenance_payload_is_signed_and_published_by_tree_and_commit() {
1287 let (d, work, remote, head, tree, signers) = provenance_world("prov-e2e");
1288 let payloads = d.join("payloads");
1289 std::fs::create_dir_all(&payloads).unwrap();
1290 let file = payloads.join(&head);
1291 let body = record(&head, &tree);
1292 std::fs::write(&file, &body).unwrap();
1293 let gates = ["pre-push-cargo-test".to_string()];
1294 in_repo(&work, || {
1295 attest_push(&test_settings(), "origin", &[push_of(&head)], &gates, &[])
1296 });
1297 let attested = git(&remote, &["notes", "--ref", NOTES_REF, "show", &head]);
1298 in_repo(&work, || {
1299 provenance_push_from(&payloads, "origin", &[push_of(&head)])
1300 });
1301 let canon = canon_by_hand(&work, &tree);
1304 assert_ne!(
1305 canon, tree,
1306 "the tree carries a plan, so canon(T) is not its oid"
1307 );
1308 let signed = body.replacen(
1309 &format!("tree {tree}\n"),
1310 &format!("tree {tree}\ncanon {canon}\n"),
1311 1,
1312 );
1313 for object in [&head, &tree] {
1314 let (p, sig) = provenance_payload(&remote, object);
1315 assert_eq!(p, signed, "the payload, with canon(T) inserted, is signed");
1316 assert_eq!(p.lines().nth(3), Some(format!("canon {canon}").as_str()));
1317 assert!(verify_in(
1318 PROVENANCE_NAMESPACE,
1319 &p,
1320 &sig,
1321 &signers,
1322 "t@t.test"
1323 ));
1324 assert!(
1325 !verify_in(NAMESPACE, &p, &sig, &signers, "t@t.test"),
1326 "a provenance signature is never an attestation"
1327 );
1328 }
1329 assert!(!file.exists(), "a published payload is deleted");
1330 assert_eq!(
1331 git(&remote, &["notes", "--ref", NOTES_REF, "show", &head]),
1332 attested,
1333 "the attestation note is byte-identical with a provenance payload present"
1334 );
1335 scratch_cleanup(&d);
1336 scratch_cleanup(&work);
1337 }
1338
1339 #[test]
1344 fn a_green_provenance_payload_is_filed_under_the_green_names_alone() {
1345 let (d, work, remote, head, tree, signers) = provenance_world("prov-green-names");
1346 let payloads = d.join("payloads");
1347 std::fs::create_dir_all(&payloads).unwrap();
1348 let body = record(&head, &tree).replacen(PROVENANCE_FORMAT, "greengate-provenance-v1", 1);
1349 assert!(body.starts_with("greengate-provenance-v1\n"));
1350 std::fs::write(payloads.join(&head), &body).unwrap();
1351 in_repo(&work, || {
1352 provenance_push_from(&payloads, "origin", &[push_of(&head)])
1353 });
1354 assert_eq!(
1355 git(
1356 &remote,
1357 &["for-each-ref", "--format=%(refname)", "refs/notes"]
1358 ),
1359 "refs/notes/greengate-provenance"
1360 );
1361 let note = git(
1362 &remote,
1363 &["notes", "--ref", "greengate-provenance", "show", &head],
1364 );
1365 let (p, sig) = note.split_once("\n\n").expect("payload and signature");
1366 let payload = format!("{p}\n");
1367 assert!(payload.starts_with("greengate-provenance-v1\n"));
1368 assert!(verify_in(
1369 "greengate-provenance",
1370 &payload,
1371 sig,
1372 &signers,
1373 "t@t.test"
1374 ));
1375 assert!(!verify_in(
1376 "amont-provenance",
1377 &payload,
1378 sig,
1379 &signers,
1380 "t@t.test"
1381 ));
1382 scratch_cleanup(&d);
1383 scratch_cleanup(&work);
1384 }
1385
1386 #[test]
1392 fn a_waiting_legacy_provenance_payload_is_kept_named_and_not_signed() {
1393 let (d, work, remote, head, tree, _) = provenance_world("prov-legacy-kept");
1394 let payloads = d.join("payloads");
1395 std::fs::create_dir_all(&payloads).unwrap();
1396 let file = payloads.join(&head);
1397 let body = record(&head, &tree).replacen(PROVENANCE_FORMAT, "amont-provenance-v1", 1);
1398 assert!(body.starts_with("amont-provenance-v1\n"));
1399 std::fs::write(&file, &body).unwrap();
1400 in_repo(&work, || {
1401 provenance_push_from(&payloads, "origin", &[push_of(&head)])
1402 });
1403 let said = legacy_provenance_line(&head, &file);
1404 assert!(file.exists(), "a legacy payload is kept, not consumed");
1405 assert_eq!(std::fs::read_to_string(&file).unwrap(), body);
1406 assert_eq!(
1407 git(
1408 &remote,
1409 &["for-each-ref", "--format=%(refname)", "refs/notes"]
1410 ),
1411 "",
1412 "nothing is published for it, under any name"
1413 );
1414 assert_eq!(
1415 git(
1416 &work,
1417 &["for-each-ref", "--format=%(refname)", "refs/notes"]
1418 ),
1419 "",
1420 "nor filed locally"
1421 );
1422 let file_name = file.display().to_string();
1423 assert!(said.contains(&file_name), "names the file: {said}");
1424 assert!(
1425 said.contains("written by an older release of the hook"),
1426 "{said}"
1427 );
1428 assert!(said.contains("upgrade greenbelay"), "{said}");
1429 scratch_cleanup(&d);
1430 scratch_cleanup(&work);
1431 }
1432
1433 #[test]
1437 fn an_attestation_push_writes_only_greensummit_refs() {
1438 let (d, work, remote, head, _tree, signers) = provenance_world("attest-green-refs");
1439 let gates = ["pre-push-cargo-test".to_string()];
1440 in_repo(&work, || {
1441 attest_push(&test_settings(), "origin", &[push_of(&head)], &gates, &[])
1442 });
1443 let refs = git(
1444 &remote,
1445 &["for-each-ref", "--format=%(refname)", "refs/notes"],
1446 );
1447 assert!(
1448 refs.lines().any(|r| r == "refs/notes/greensummit"),
1449 "{refs}"
1450 );
1451 assert!(
1452 refs.lines().all(|r| r.starts_with("refs/notes/greensummit")
1453 || r.starts_with("refs/notes/greengate-provenance")),
1454 "an old name was written: {refs}"
1455 );
1456 let note = git(&remote, &["notes", "--ref", "greensummit", "show", &head]);
1457 let (p, sig) = note.split_once("\n\n").expect("payload and signature");
1458 let payload = format!("{p}\n");
1459 assert!(payload.starts_with("greensummit-v2\n"), "{payload}");
1460 assert!(verify_in(
1461 "greensummit",
1462 &payload,
1463 sig,
1464 &signers,
1465 "t@t.test"
1466 ));
1467 assert!(!verify_in(
1468 "amont-attest",
1469 &payload,
1470 sig,
1471 &signers,
1472 "t@t.test"
1473 ));
1474 scratch_cleanup(&d);
1475 scratch_cleanup(&work);
1476 }
1477
1478 #[test]
1482 fn the_default_key_is_the_green_name_with_the_old_one_as_fallback() {
1483 let home = dir("key-default");
1484 std::fs::create_dir_all(home.join(".ssh")).unwrap();
1485 assert_eq!(default_key_in(&home), home.join(".ssh/greengate-attest"));
1487 assert_eq!(key_move_hint_in(&home), None);
1488 std::fs::write(home.join(".ssh/amont-attest"), "k").unwrap();
1490 assert_eq!(default_key_in(&home), home.join(".ssh/amont-attest"));
1491 let hint = key_move_hint_in(&home).expect("a doctor line");
1492 assert!(
1493 hint.contains("mv ~/.ssh/amont-attest ~/.ssh/greengate-attest"),
1494 "{hint}"
1495 );
1496 assert_eq!(hint.lines().count(), 1);
1497 std::fs::write(home.join(".ssh/greengate-attest"), "k").unwrap();
1499 assert_eq!(default_key_in(&home), home.join(".ssh/greengate-attest"));
1500 assert_eq!(key_move_hint_in(&home), None);
1501 scratch_cleanup(&home);
1502 }
1503
1504 #[test]
1505 fn a_payload_for_another_tree_is_neither_signed_nor_deleted() {
1506 let (d, work, remote, head, _tree, _) = provenance_world("prov-mismatch");
1507 let payloads = d.join("payloads");
1508 std::fs::create_dir_all(&payloads).unwrap();
1509 let file = payloads.join(&head);
1510 std::fs::write(&file, record(&head, &"b".repeat(40))).unwrap();
1511 in_repo(&work, || {
1512 provenance_push_from(&payloads, "origin", &[push_of(&head)])
1513 });
1514 assert!(file.exists(), "a mismatched payload is kept");
1515 let refs = git(&remote, &["for-each-ref", PROVENANCE_FULL_REF]);
1516 assert!(refs.is_empty(), "nothing was published: {refs}");
1517 scratch_cleanup(&d);
1518 scratch_cleanup(&work);
1519 }
1520
1521 #[test]
1524 fn a_payload_with_a_canon_line_is_refused_and_kept() {
1525 let (d, work, remote, head, tree, _) = provenance_world("prov-canon");
1526 let payloads = d.join("payloads");
1527 std::fs::create_dir_all(&payloads).unwrap();
1528 let file = payloads.join(&head);
1529 let old = record(&head, &tree).replacen(
1530 &format!("tree {tree}\n"),
1531 &format!("tree {tree}\ncanon {}\n", "c".repeat(64)),
1532 1,
1533 );
1534 std::fs::write(&file, &old).unwrap();
1535 in_repo(&work, || {
1536 provenance_push_from(&payloads, "origin", &[push_of(&head)])
1537 });
1538 assert_eq!(
1539 std::fs::read_to_string(&file).unwrap(),
1540 old,
1541 "kept as it was"
1542 );
1543 let refs = git(&remote, &["for-each-ref", PROVENANCE_FULL_REF]);
1544 assert!(refs.is_empty(), "nothing was published: {refs}");
1545 scratch_cleanup(&d);
1546 scratch_cleanup(&work);
1547 }
1548
1549 #[test]
1552 fn the_canon_refusal_fits_in_80_columns() {
1553 for commit in [
1554 "9f1c2ab0d6e4c1b2a3f405e6d7c8b9a0f1e2d3c4".to_string(),
1555 "e".repeat(64),
1556 ] {
1557 let file = PathBuf::from("/Users/someone/.claude/greenbelay/provenance/greengate")
1558 .join(&commit);
1559 let lines = canon_refusal(&commit, &file);
1560 assert!(lines[0].starts_with(" provenance for "), "{lines:?}");
1561 assert!(lines[0].contains(&commit[..7]), "{lines:?}");
1562 let all = lines.join("\n");
1563 assert!(all.contains("canon line") && all.contains("pre-release build of the hook"));
1564 assert!(all.contains(&format!(" {commit} in\n")), "{all}");
1565 assert!(all.contains("upgrade greenbelay"), "{all}");
1566 for l in &lines {
1567 assert!(
1568 l.chars().count() <= 80,
1569 "{} columns: {l}",
1570 l.chars().count()
1571 );
1572 }
1573 }
1574 }
1575
1576 #[test]
1578 fn a_failed_canon_keeps_the_payload() {
1579 let (d, work, remote, head, tree, _) = provenance_world("prov-nocanon");
1580 let docs = git(&work, &["rev-parse", &format!("{tree}:docs")]);
1582 let objects = PathBuf::from(git(&work, &["rev-parse", "--git-path", "objects"]));
1583 let objects = if objects.is_absolute() {
1584 objects
1585 } else {
1586 work.join(objects)
1587 };
1588 std::fs::remove_file(objects.join(&docs[..2]).join(&docs[2..])).unwrap();
1589 let payloads = d.join("payloads");
1590 std::fs::create_dir_all(&payloads).unwrap();
1591 let file = payloads.join(&head);
1592 std::fs::write(&file, record(&head, &tree)).unwrap();
1593 in_repo(&work, || {
1594 assert_eq!(canon(&tree), None);
1595 provenance_push_from(&payloads, "origin", &[push_of(&head)])
1596 });
1597 assert!(file.exists(), "a payload without a canon is kept");
1598 let refs = git(&remote, &["for-each-ref", PROVENANCE_FULL_REF]);
1599 assert!(refs.is_empty(), "nothing was published: {refs}");
1600 scratch_cleanup(&d);
1601 scratch_cleanup(&work);
1602 }
1603
1604 #[test]
1607 fn a_sha256_repository_signs_a_64_hex_canon() {
1608 let (d, work, remote, head, tree, _) = provenance_world_in("prov-sha256", Some("sha256"));
1609 assert_eq!(tree.len(), 64);
1610 let payloads = d.join("payloads");
1611 std::fs::create_dir_all(&payloads).unwrap();
1612 std::fs::write(payloads.join(&head), record(&head, &tree)).unwrap();
1613 in_repo(&work, || {
1614 provenance_push_from(&payloads, "origin", &[push_of(&head)])
1615 });
1616 let (p, _) = provenance_payload(&remote, &head);
1617 let canon = canon_by_hand(&work, &tree);
1618 assert_eq!(canon.len(), 64);
1619 assert_eq!(
1620 p.lines().nth(3),
1621 Some(format!("canon {canon}").as_str()),
1622 "{p}"
1623 );
1624 scratch_cleanup(&d);
1625 scratch_cleanup(&work);
1626 }
1627
1628 #[test]
1629 fn a_failed_publish_keeps_the_payload_for_the_next_push() {
1630 let (d, work, _remote, head, tree, _) = provenance_world("prov-fail");
1631 git(
1632 &work,
1633 &[
1634 "remote",
1635 "set-url",
1636 "origin",
1637 d.join("gone.git").to_str().unwrap(),
1638 ],
1639 );
1640 let payloads = d.join("payloads");
1641 std::fs::create_dir_all(&payloads).unwrap();
1642 let file = payloads.join(&head);
1643 std::fs::write(&file, record(&head, &tree)).unwrap();
1644 in_repo(&work, || {
1645 provenance_push_from(&payloads, "origin", &[push_of(&head)])
1646 });
1647 assert!(file.exists(), "an unpublished payload is kept");
1648 scratch_cleanup(&d);
1649 scratch_cleanup(&work);
1650 }
1651
1652 #[test]
1655 fn a_config_key_cannot_point_amont_at_other_payloads() {
1656 let (d, work, remote, head, tree, _) = provenance_world("prov-config");
1657 let elsewhere = d.join("elsewhere");
1658 let name = work.file_name().unwrap().to_string_lossy().into_owned();
1659 std::fs::create_dir_all(elsewhere.join(&name)).unwrap();
1660 std::fs::write(elsewhere.join(&name).join(&head), record(&head, &tree)).unwrap();
1661 for key in ["greengate.provenanceDir", "amont.agent.provenanceDir"] {
1662 git(&work, &["config", key, elsewhere.to_str().unwrap()]);
1663 }
1664 in_repo(&work, || {
1665 provenance_push(&test_settings(), "origin", &[push_of(&head)])
1666 });
1667 let refs = git(&remote, &["for-each-ref", PROVENANCE_FULL_REF]);
1668 assert!(refs.is_empty(), "a configured directory was read: {refs}");
1669 scratch_cleanup(&d);
1670 scratch_cleanup(&work);
1671 }
1672
1673 #[test]
1674 fn no_payload_publishes_nothing() {
1675 let (d, work, remote, head, _, _) = provenance_world("prov-none");
1676 let payloads = d.join("payloads");
1677 std::fs::create_dir_all(&payloads).unwrap();
1678 in_repo(&work, || {
1679 provenance_push_from(&payloads, "origin", &[push_of(&head)])
1680 });
1681 let refs = git(&remote, &["for-each-ref", PROVENANCE_FULL_REF]);
1682 assert!(refs.is_empty(), "{refs}");
1683 scratch_cleanup(&d);
1684 scratch_cleanup(&work);
1685 }
1686
1687 #[test]
1688 fn a_missing_key_signs_nothing() {
1689 assert!(sign("anything", Path::new("/nonexistent/key")).is_none());
1690 }
1691
1692 #[test]
1696 fn an_enabled_push_leaves_a_verifiable_note_on_the_remote() {
1697 let d = dir("e2e");
1698 let (key, signers) = keypair(&d);
1699 let remote = d.join("remote.git");
1700 std::fs::create_dir_all(&remote).unwrap();
1701 git(&remote, &["init", "-q", "--bare", "--template=", "."]);
1702 let work = repo("e2e-work");
1703 git(
1704 &work,
1705 &["remote", "add", "origin", remote.to_str().unwrap()],
1706 );
1707 git(&work, &["config", "greengate.attest", "true"]);
1708 git(
1709 &work,
1710 &["config", "greengate.attestKey", key.to_str().unwrap()],
1711 );
1712 std::fs::write(work.join("a.ts"), "x").unwrap();
1713 git(&work, &["add", "a.ts"]);
1714 git(&work, &["commit", "-qm", "chore: a"]);
1715 let head = git(&work, &["rev-parse", "HEAD"]);
1716 let tree = git(&work, &["rev-parse", "HEAD^{tree}"]);
1717 let push_ref = PushRef {
1718 local_ref: "refs/heads/main".into(),
1719 local_oid: head.clone(),
1720 remote_ref: "refs/heads/main".into(),
1721 remote_oid: "0".repeat(40),
1722 };
1723 in_repo(&work, || {
1724 attest_push(
1725 &test_settings(),
1726 "origin",
1727 &[push_ref],
1728 &["pre-push-run-tests-js".into()],
1729 &[],
1730 );
1731 });
1732 let body = git(&remote, &["notes", "--ref", NOTES_REF, "show", &head]);
1734 assert!(!body.is_empty(), "no note reached the remote");
1735 let (p, sig) = body
1736 .split_once("\n\n")
1737 .expect("payload, blank line, signature");
1738 let p = format!("{p}\n"); assert!(p.starts_with(FORMAT));
1740 assert!(
1741 p.contains(&format!("tree {tree}")),
1742 "attests the pushed tree"
1743 );
1744 assert!(
1745 verify(&p, sig, &signers, "t@t.test"),
1746 "the remote copy verifies"
1747 );
1748 scratch_cleanup(&d);
1749 scratch_cleanup(&work);
1750 }
1751
1752 #[test]
1759 fn a_push_with_a_spec_publishes_the_inputs_ref() {
1760 let (_d, work, remote, _) = remote_and_work("inputs");
1761 std::fs::create_dir_all(work.join(".github")).unwrap();
1762 std::fs::write(
1763 work.join(".github/greensummit-inputs"),
1764 "pre-push-run-tests-js a.ts\n",
1765 )
1766 .unwrap();
1767 git(&work, &["add", ".github/greensummit-inputs"]);
1768 git(&work, &["commit", "-qm", "chore: spec"]);
1769 in_repo(&work, || {
1770 attest_push(
1771 &test_settings(),
1772 "origin",
1773 &[push_ref_for(&work)],
1774 &["pre-push-run-tests-js".into()],
1775 &[],
1776 );
1777 });
1778 let listed = git(&remote, &["notes", "--ref", INPUTS_REF, "list"]);
1779 assert!(
1781 !listed.trim().is_empty(),
1782 "the inputs ref reached the remote"
1783 );
1784 }
1785
1786 #[test]
1787 fn no_opt_in_means_no_note() {
1788 let d = dir("optout");
1789 let (key, _) = keypair(&d);
1790 let remote = d.join("remote.git");
1791 std::fs::create_dir_all(&remote).unwrap();
1792 git(&remote, &["init", "-q", "--bare", "--template=", "."]);
1793 let work = repo("optout-work");
1794 git(
1795 &work,
1796 &["remote", "add", "origin", remote.to_str().unwrap()],
1797 );
1798 git(
1799 &work,
1800 &["config", "greengate.attestKey", key.to_str().unwrap()],
1801 );
1802 std::fs::write(work.join("a.ts"), "x").unwrap();
1803 git(&work, &["add", "a.ts"]);
1804 git(&work, &["commit", "-qm", "chore: a"]);
1805 let head = git(&work, &["rev-parse", "HEAD"]);
1806 let push_ref = PushRef {
1807 local_ref: "refs/heads/main".into(),
1808 local_oid: head.clone(),
1809 remote_ref: "refs/heads/main".into(),
1810 remote_oid: "0".repeat(40),
1811 };
1812 in_repo(&work, || {
1813 attest_push(
1814 &test_settings(),
1815 "origin",
1816 &[push_ref],
1817 &["pre-push-run-tests-js".into()],
1818 &[],
1819 );
1820 });
1821 assert!(
1822 git(&remote, &["notes", "--ref", NOTES_REF, "list"]).is_empty(),
1823 "an un-opted-in repo attested something"
1824 );
1825 scratch_cleanup(&d);
1826 scratch_cleanup(&work);
1827 }
1828
1829 #[test]
1832 fn deletions_and_empty_gates_attest_nothing() {
1833 let d = dir("nothing");
1834 let (key, _) = keypair(&d);
1835 let remote = d.join("remote.git");
1836 std::fs::create_dir_all(&remote).unwrap();
1837 git(&remote, &["init", "-q", "--bare", "--template=", "."]);
1838 let work = repo("nothing-work");
1839 git(
1840 &work,
1841 &["remote", "add", "origin", remote.to_str().unwrap()],
1842 );
1843 git(&work, &["config", "greengate.attest", "true"]);
1844 git(
1845 &work,
1846 &["config", "greengate.attestKey", key.to_str().unwrap()],
1847 );
1848 std::fs::write(work.join("a.ts"), "x").unwrap();
1849 git(&work, &["add", "a.ts"]);
1850 git(&work, &["commit", "-qm", "chore: a"]);
1851 let head = git(&work, &["rev-parse", "HEAD"]);
1852 let deletion = PushRef {
1853 local_ref: "(delete)".into(),
1854 local_oid: "0".repeat(40),
1855 remote_ref: "refs/heads/gone".into(),
1856 remote_oid: head.clone(),
1857 };
1858 let real = PushRef {
1859 local_ref: "refs/heads/main".into(),
1860 local_oid: head,
1861 remote_ref: "refs/heads/main".into(),
1862 remote_oid: "0".repeat(40),
1863 };
1864 in_repo(&work, || {
1865 attest_push(
1866 &test_settings(),
1867 "origin",
1868 &[deletion],
1869 &["pre-push-pytest".into()],
1870 &[],
1871 );
1872 attest_push(&test_settings(), "origin", &[real], &[], &[]);
1873 });
1874 assert!(git(&remote, &["notes", "--ref", NOTES_REF, "list"]).is_empty());
1875 scratch_cleanup(&d);
1876 scratch_cleanup(&work);
1877 }
1878
1879 #[test]
1886 fn a_rejection_is_a_note_whose_signature_did_not_verify() {
1887 let trail: Vec<String> = [
1888 "note on abc123: signature did not verify for principal t@t.test",
1889 "note on abc123 block 2: no principal matched",
1890 "note on def456 carries no signature block",
1891 "attested tree abc is not the checked-out tree def and neither its canonical tree nor an input fingerprint of abc123 matches",
1892 "no attestation found for tree abc",
1893 ]
1894 .iter()
1895 .map(|s| s.to_string())
1896 .collect();
1897 assert_eq!(
1898 signature_rejections(&trail),
1899 vec![
1900 "note on abc123: signature did not verify for principal t@t.test".to_string(),
1901 "note on abc123 block 2: no principal matched".to_string(),
1902 ]
1903 );
1904 }
1905
1906 #[test]
1907 fn covered_answers_in_a_fresh_clone_and_rejects_drift_and_forgery() {
1908 let d = dir("covered");
1909 let (key, signers) = keypair(&d);
1910 let remote = d.join("remote.git");
1911 std::fs::create_dir_all(&remote).unwrap();
1912 git(&remote, &["init", "-q", "--bare", "--template=", "."]);
1913 git(&remote, &["symbolic-ref", "HEAD", "refs/heads/main"]);
1919 let work = repo("covered-work");
1920 git(
1921 &work,
1922 &["remote", "add", "origin", remote.to_str().unwrap()],
1923 );
1924 git(&work, &["config", "greengate.attest", "true"]);
1925 git(
1926 &work,
1927 &["config", "greengate.attestKey", key.to_str().unwrap()],
1928 );
1929 std::fs::write(work.join("a.ts"), "x").unwrap();
1930 git(&work, &["add", "a.ts"]);
1931 git(&work, &["commit", "-qm", "chore: a"]);
1932 git(&work, &["push", "-q", "origin", "HEAD:main"]);
1933 let head = git(&work, &["rev-parse", "HEAD"]);
1934 let push_ref = PushRef {
1935 local_ref: "refs/heads/main".into(),
1936 local_oid: head.clone(),
1937 remote_ref: "refs/heads/main".into(),
1938 remote_oid: "0".repeat(40),
1939 };
1940 in_repo(&work, || {
1941 attest_push(
1942 &test_settings(),
1943 "origin",
1944 &[push_ref],
1945 &["pre-push-pytest".into()],
1946 &[],
1947 );
1948 });
1949 let clone = d.join("ci-checkout");
1950 git(
1951 &d,
1952 &[
1953 "clone",
1954 "-q",
1955 "--template=",
1956 remote.to_str().unwrap(),
1957 clone.to_str().unwrap(),
1958 ],
1959 );
1960 in_repo(&clone, || {
1961 assert_eq!(
1962 covered(&signers, Some("t@t.test"), Some(&platform()), &[]).as_deref(),
1963 Some("pre-push-pytest"),
1964 "a fresh clone verifies the attestation and reads the gates"
1965 );
1966 assert_eq!(
1967 covered(&signers, Some("t@t.test"), None, &[]).as_deref(),
1968 Some("pre-push-pytest"),
1969 "`any` covers a platform-independent suite"
1970 );
1971 assert_eq!(
1974 covered(&signers, Some("t@t.test"), Some("s390x-aix"), &[]),
1975 None,
1976 "a pass on one platform is not evidence about another"
1977 );
1978 assert_eq!(
1979 covered(&signers, Some("someone@else.test"), None, &[]),
1980 None,
1981 "an unlisted principal covers nothing"
1982 );
1983 });
1984 std::fs::write(clone.join("b.ts"), "y").unwrap();
1986 git(&clone, &["config", "user.email", "t@t.test"]);
1987 git(&clone, &["config", "user.name", "t"]);
1988 git(&clone, &["add", "b.ts"]);
1989 git(&clone, &["commit", "-qm", "chore: b"]);
1990 in_repo(&clone, || {
1991 assert_eq!(
1992 covered(&signers, Some("t@t.test"), None, &[]),
1993 None,
1994 "drifted tree"
1995 );
1996 });
1997 let head_tree = git(&work, &["rev-parse", "HEAD^{tree}"]);
2007 for object in [&head, &head_tree] {
2008 git(
2009 &work,
2010 &[
2011 "notes", "--ref", NOTES_REF, "add", "-f", "-m", "garbage", object,
2012 ],
2013 );
2014 }
2015 git(
2016 &work,
2017 &[
2018 "push",
2019 "-q",
2020 "origin",
2021 &format!("+{NOTES_FULL_REF}:{NOTES_FULL_REF}"),
2022 ],
2023 );
2024 git(
2028 &work,
2029 &["push", "-q", "origin", &format!(":{INPUTS_FULL_REF}")],
2030 );
2031 git(&clone, &["reset", "-q", "--hard", &head]);
2032 in_repo(&clone, || {
2033 assert_eq!(
2034 covered(&signers, Some("t@t.test"), None, &[]),
2035 None,
2036 "a foreign note is not a stamp"
2037 );
2038 });
2039 scratch_cleanup(&d);
2040 scratch_cleanup(&work);
2041 }
2042
2043 #[test]
2049 fn default_signers_is_found_from_a_subdirectory() {
2050 let work = repo("signers-subdir");
2051 std::fs::create_dir_all(work.join(".forgejo")).unwrap();
2052 std::fs::write(work.join(".forgejo/allowed_signers"), "t@t.test x\n").unwrap();
2053 let sub = work.join("packages").join("thing");
2054 std::fs::create_dir_all(&sub).unwrap();
2055 in_repo(&sub, || {
2056 let found = default_signers().expect("resolved from the repo root, not the cwd");
2057 assert!(found.ends_with(".forgejo/allowed_signers"));
2058 assert!(found.exists(), "the path it returns must be usable as-is");
2059 });
2060 scratch_cleanup(&work);
2061 }
2062
2063 #[test]
2064 fn zero_oids_of_any_width_are_zero() {
2065 assert!(is_zero(&"0".repeat(40)));
2066 assert!(is_zero(&"0".repeat(64)));
2067 assert!(!is_zero("0a0000"));
2068 assert!(!is_zero(""));
2069 }
2070
2071 #[test]
2072 fn forget_removes_the_local_ref() {
2073 let work = repo("forget");
2074 std::fs::write(work.join("a.ts"), "x").unwrap();
2075 git(&work, &["add", "a.ts"]);
2076 git(&work, &["commit", "-qm", "chore: a"]);
2077 git(
2078 &work,
2079 &["notes", "--ref", NOTES_REF, "add", "-m", "x", "HEAD"],
2080 );
2081 in_repo(&work, forget);
2082 assert!(git(&work, &["notes", "--ref", NOTES_REF, "list"]).is_empty());
2083 scratch_cleanup(&work);
2084 }
2085
2086 pub(crate) const OLD_FORMAT: &str = PRE_SUMMIT_HEADERS[0];
2097 pub(crate) const OLD_NAMESPACE: &str = "greengate-attest";
2098
2099 pub(crate) fn both_names_signer(dir: &Path) -> (PathBuf, PathBuf) {
2103 let key = dir.join("signer_key");
2104 let ok = std::process::Command::new("ssh-keygen")
2105 .args(["-q", "-t", "ed25519", "-N", "", "-C", "test", "-f"])
2106 .arg(&key)
2107 .status()
2108 .expect("ssh-keygen must exist for these tests")
2109 .success();
2110 assert!(ok, "keygen failed");
2111 let pubkey = std::fs::read_to_string(key.with_extension("pub")).unwrap();
2112 let signers = dir.join("allowed_signers");
2113 std::fs::write(
2114 &signers,
2115 format!(
2116 "cluster-signer@{} namespaces=\"{},{}\" {pubkey}",
2117 crate::cluster::PLATFORM,
2118 OLD_NAMESPACE,
2119 greensummit::format::SUMMIT.namespace
2120 ),
2121 )
2122 .unwrap();
2123 (key, signers)
2124 }
2125
2126 pub(crate) fn block_with(header: &str, namespace: &str, tree: &str, key: &Path) -> String {
2128 let payload = format!(
2129 "{header}\ntree {tree}\ngates suite\nplatform {}\ngreengate 0.0.0\n",
2130 crate::cluster::PLATFORM
2131 );
2132 let sig = greensummit::sign::sign(namespace, &payload, key).expect("sign");
2133 block(&payload, &sig)
2134 }
2135
2136 #[test]
2137 fn a_signer_block_is_read_only_under_greensummit_names() {
2138 use greensummit::format::SUMMIT;
2139 let scratch = dir("signer-names");
2140 let (key, signers) = both_names_signer(&scratch);
2141 let tree = "0123456789012345678901234567890123456789";
2142 let body = block_with(SUMMIT.format, SUMMIT.namespace, tree, &key);
2143 let checked = signer_block(&body, tree, &signers)
2144 .unwrap_or_else(|e| panic!("{}: {}", SUMMIT.format, e.reason()));
2145 assert_eq!(checked.gates, ["suite"]);
2146 for header in PRE_SUMMIT_HEADERS {
2149 let old = block_with(header, OLD_NAMESPACE, tree, &key);
2150 match signer_block(&old, tree, &signers) {
2151 Err(BlockRefusal::StaleSigner(why)) => {
2152 assert!(why.contains(header), "{why}");
2153 assert!(why.contains(SUMMIT.format), "{why}");
2154 }
2155 other => panic!("a {header} block must be refused, got {other:?}"),
2156 }
2157 }
2158 let crossed = block_with(SUMMIT.format, OLD_NAMESPACE, tree, &key);
2161 assert!(matches!(
2162 signer_block(&crossed, tree, &signers),
2163 Err(BlockRefusal::Signer(_))
2164 ));
2165 scratch_cleanup(&scratch);
2166 }
2167
2168 #[test]
2169 fn forget_in_removes_the_notes_ref() {
2170 let repo_dir = repo("forget-in");
2171 git(&repo_dir, &["commit", "-q", "--allow-empty", "-m", "c"]);
2172 git(
2173 &repo_dir,
2174 &["notes", "--ref", NOTES_REF, "add", "-m", "x", "HEAD"],
2175 );
2176 assert!(forget_in(&repo_dir));
2177 let out = std::process::Command::new("git")
2178 .arg("-C")
2179 .arg(&repo_dir)
2180 .args(["rev-parse", "--verify", "-q", NOTES_FULL_REF])
2181 .output()
2182 .unwrap();
2183 assert!(!out.status.success(), "{NOTES_FULL_REF} survived forget_in");
2184 scratch_cleanup(&repo_dir);
2185 }
2186
2187 #[test]
2188 fn filed_signer_blocks_drops_a_block_under_the_old_names() {
2189 use greensummit::format::SUMMIT;
2190 let work = repo("filed-names");
2191 std::fs::write(work.join("a.txt"), "x").unwrap();
2192 git(&work, &["add", "a.txt"]);
2193 git(&work, &["commit", "-qm", "chore: a"]);
2194 let (key, signers) = both_names_signer(&work);
2195 std::fs::create_dir_all(work.join(".forgejo")).unwrap();
2196 std::fs::copy(&signers, work.join(".forgejo/allowed_signers")).unwrap();
2197 let tree = git(&work, &["rev-parse", "HEAD^{tree}"]);
2198 let summit = block_with(SUMMIT.format, SUMMIT.namespace, &tree, &key);
2199 let old = block_with(OLD_FORMAT, OLD_NAMESPACE, &tree, &key);
2200 in_repo(&work, || {
2201 file_signer_block(&old, &[&tree]).expect("file the old block");
2202 assert!(
2203 filed_signer_blocks(&tree).is_empty(),
2204 "a block under the old names is not read"
2205 );
2206 file_signer_block(&format!("{old}\n{summit}"), &[&tree]).expect("file both");
2207 let kept = filed_signer_blocks(&tree);
2208 assert_eq!(kept.len(), 1, "{kept:?}");
2209 assert!(kept[0].body.starts_with(SUMMIT.format), "{}", kept[0].body);
2210 });
2211 scratch_cleanup(&work);
2212 }
2213
2214 #[test]
2215 fn a_verification_says_which_name_it_went_through() {
2216 let mut verdict = greensummit::verify::Verdict::nothing("test");
2217 assert!(verified_lines(&verdict).is_empty());
2218 verdict.verified_under = vec![NAMESPACE.to_string()];
2219 assert_eq!(verified_lines(&verdict), ["verified under greensummit"]);
2220 }
2221}