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 = "greenpiste";
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 greenpiste 5.0 moves 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 greenpiste: upgrade greenpiste, 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 greenpiste wrote it); delete the file".to_string(),
604 format!(" {name} in"),
605 format!(" {dir}"),
606 " and upgrade greenpiste".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("greenpiste/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_greenpistes_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/greenpiste/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/greenpiste/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/greenpiste/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!(said.contains("written by an older greenpiste"), "{said}");
1435 assert!(said.contains("upgrade greenpiste"), "{said}");
1436 scratch_cleanup(&d);
1437 scratch_cleanup(&work);
1438 }
1439
1440 #[test]
1444 fn an_attestation_push_writes_only_green_refs() {
1445 let (d, work, remote, head, _tree, signers) = provenance_world("attest-green-refs");
1446 let gates = ["pre-push-cargo-test".to_string()];
1447 in_repo(&work, || {
1448 attest_push(&test_settings(), "origin", &[push_of(&head)], &gates, &[])
1449 });
1450 let refs = git(
1451 &remote,
1452 &["for-each-ref", "--format=%(refname)", "refs/notes"],
1453 );
1454 assert!(
1455 refs.lines().any(|r| r == "refs/notes/greengate-attest"),
1456 "{refs}"
1457 );
1458 assert!(
1459 refs.lines().all(|r| r.starts_with("refs/notes/greengate-")),
1460 "an old name was written: {refs}"
1461 );
1462 let note = git(
1463 &remote,
1464 &["notes", "--ref", "greengate-attest", "show", &head],
1465 );
1466 let (p, sig) = note.split_once("\n\n").expect("payload and signature");
1467 let payload = format!("{p}\n");
1468 assert!(payload.starts_with("greengate-attest-v2\n"), "{payload}");
1469 assert!(verify_in(
1470 "greengate-attest",
1471 &payload,
1472 sig,
1473 &signers,
1474 "t@t.test"
1475 ));
1476 assert!(!verify_in(
1477 "amont-attest",
1478 &payload,
1479 sig,
1480 &signers,
1481 "t@t.test"
1482 ));
1483 scratch_cleanup(&d);
1484 scratch_cleanup(&work);
1485 }
1486
1487 #[test]
1491 fn the_default_key_is_the_green_name_with_the_old_one_as_fallback() {
1492 let home = dir("key-default");
1493 std::fs::create_dir_all(home.join(".ssh")).unwrap();
1494 assert_eq!(default_key_in(&home), home.join(".ssh/greengate-attest"));
1496 assert_eq!(key_move_hint_in(&home), None);
1497 std::fs::write(home.join(".ssh/amont-attest"), "k").unwrap();
1499 assert_eq!(default_key_in(&home), home.join(".ssh/amont-attest"));
1500 let hint = key_move_hint_in(&home).expect("a doctor line");
1501 assert!(
1502 hint.contains("mv ~/.ssh/amont-attest ~/.ssh/greengate-attest"),
1503 "{hint}"
1504 );
1505 assert_eq!(hint.lines().count(), 1);
1506 std::fs::write(home.join(".ssh/greengate-attest"), "k").unwrap();
1508 assert_eq!(default_key_in(&home), home.join(".ssh/greengate-attest"));
1509 assert_eq!(key_move_hint_in(&home), None);
1510 scratch_cleanup(&home);
1511 }
1512
1513 #[test]
1514 fn a_payload_for_another_tree_is_neither_signed_nor_deleted() {
1515 let (d, work, remote, head, _tree, _) = provenance_world("prov-mismatch");
1516 let payloads = d.join("payloads");
1517 std::fs::create_dir_all(&payloads).unwrap();
1518 let file = payloads.join(&head);
1519 std::fs::write(&file, record(&head, &"b".repeat(40))).unwrap();
1520 in_repo(&work, || {
1521 provenance_push_from(&payloads, "origin", &[push_of(&head)])
1522 });
1523 assert!(file.exists(), "a mismatched payload is kept");
1524 let refs = git(&remote, &["for-each-ref", PROVENANCE_FULL_REF]);
1525 assert!(refs.is_empty(), "nothing was published: {refs}");
1526 scratch_cleanup(&d);
1527 scratch_cleanup(&work);
1528 }
1529
1530 #[test]
1533 fn a_payload_with_a_canon_line_is_refused_and_kept() {
1534 let (d, work, remote, head, tree, _) = provenance_world("prov-canon");
1535 let payloads = d.join("payloads");
1536 std::fs::create_dir_all(&payloads).unwrap();
1537 let file = payloads.join(&head);
1538 let old = record(&head, &tree).replacen(
1539 &format!("tree {tree}\n"),
1540 &format!("tree {tree}\ncanon {}\n", "c".repeat(64)),
1541 1,
1542 );
1543 std::fs::write(&file, &old).unwrap();
1544 in_repo(&work, || {
1545 provenance_push_from(&payloads, "origin", &[push_of(&head)])
1546 });
1547 assert_eq!(
1548 std::fs::read_to_string(&file).unwrap(),
1549 old,
1550 "kept as it was"
1551 );
1552 let refs = git(&remote, &["for-each-ref", PROVENANCE_FULL_REF]);
1553 assert!(refs.is_empty(), "nothing was published: {refs}");
1554 scratch_cleanup(&d);
1555 scratch_cleanup(&work);
1556 }
1557
1558 #[test]
1561 fn the_canon_refusal_fits_in_80_columns() {
1562 for commit in [
1563 "9f1c2ab0d6e4c1b2a3f405e6d7c8b9a0f1e2d3c4".to_string(),
1564 "e".repeat(64),
1565 ] {
1566 let file = PathBuf::from("/Users/someone/.claude/greenpiste/provenance/greengate")
1567 .join(&commit);
1568 let lines = canon_refusal(&commit, &file);
1569 assert!(lines[0].starts_with(" provenance for "), "{lines:?}");
1570 assert!(lines[0].contains(&commit[..7]), "{lines:?}");
1571 let all = lines.join("\n");
1572 assert!(all.contains("canon line") && all.contains("pre-release greenpiste"));
1573 assert!(all.contains(&format!(" {commit} in\n")), "{all}");
1574 assert!(all.contains("upgrade greenpiste"), "{all}");
1575 for l in &lines {
1576 assert!(
1577 l.chars().count() <= 80,
1578 "{} columns: {l}",
1579 l.chars().count()
1580 );
1581 }
1582 }
1583 }
1584
1585 #[test]
1587 fn a_failed_canon_keeps_the_payload() {
1588 let (d, work, remote, head, tree, _) = provenance_world("prov-nocanon");
1589 let docs = git(&work, &["rev-parse", &format!("{tree}:docs")]);
1591 let objects = PathBuf::from(git(&work, &["rev-parse", "--git-path", "objects"]));
1592 let objects = if objects.is_absolute() {
1593 objects
1594 } else {
1595 work.join(objects)
1596 };
1597 std::fs::remove_file(objects.join(&docs[..2]).join(&docs[2..])).unwrap();
1598 let payloads = d.join("payloads");
1599 std::fs::create_dir_all(&payloads).unwrap();
1600 let file = payloads.join(&head);
1601 std::fs::write(&file, record(&head, &tree)).unwrap();
1602 in_repo(&work, || {
1603 assert_eq!(canon(&tree), None);
1604 provenance_push_from(&payloads, "origin", &[push_of(&head)])
1605 });
1606 assert!(file.exists(), "a payload without a canon is kept");
1607 let refs = git(&remote, &["for-each-ref", PROVENANCE_FULL_REF]);
1608 assert!(refs.is_empty(), "nothing was published: {refs}");
1609 scratch_cleanup(&d);
1610 scratch_cleanup(&work);
1611 }
1612
1613 #[test]
1616 fn a_sha256_repository_signs_a_64_hex_canon() {
1617 let (d, work, remote, head, tree, _) = provenance_world_in("prov-sha256", Some("sha256"));
1618 assert_eq!(tree.len(), 64);
1619 let payloads = d.join("payloads");
1620 std::fs::create_dir_all(&payloads).unwrap();
1621 std::fs::write(payloads.join(&head), record(&head, &tree)).unwrap();
1622 in_repo(&work, || {
1623 provenance_push_from(&payloads, "origin", &[push_of(&head)])
1624 });
1625 let (p, _) = provenance_payload(&remote, &head);
1626 let canon = canon_by_hand(&work, &tree);
1627 assert_eq!(canon.len(), 64);
1628 assert_eq!(
1629 p.lines().nth(3),
1630 Some(format!("canon {canon}").as_str()),
1631 "{p}"
1632 );
1633 scratch_cleanup(&d);
1634 scratch_cleanup(&work);
1635 }
1636
1637 #[test]
1638 fn a_failed_publish_keeps_the_payload_for_the_next_push() {
1639 let (d, work, _remote, head, tree, _) = provenance_world("prov-fail");
1640 git(
1641 &work,
1642 &[
1643 "remote",
1644 "set-url",
1645 "origin",
1646 d.join("gone.git").to_str().unwrap(),
1647 ],
1648 );
1649 let payloads = d.join("payloads");
1650 std::fs::create_dir_all(&payloads).unwrap();
1651 let file = payloads.join(&head);
1652 std::fs::write(&file, record(&head, &tree)).unwrap();
1653 in_repo(&work, || {
1654 provenance_push_from(&payloads, "origin", &[push_of(&head)])
1655 });
1656 assert!(file.exists(), "an unpublished payload is kept");
1657 scratch_cleanup(&d);
1658 scratch_cleanup(&work);
1659 }
1660
1661 #[test]
1664 fn a_config_key_cannot_point_amont_at_other_payloads() {
1665 let (d, work, remote, head, tree, _) = provenance_world("prov-config");
1666 let elsewhere = d.join("elsewhere");
1667 let name = work.file_name().unwrap().to_string_lossy().into_owned();
1668 std::fs::create_dir_all(elsewhere.join(&name)).unwrap();
1669 std::fs::write(elsewhere.join(&name).join(&head), record(&head, &tree)).unwrap();
1670 for key in ["greengate.provenanceDir", "amont.agent.provenanceDir"] {
1671 git(&work, &["config", key, elsewhere.to_str().unwrap()]);
1672 }
1673 in_repo(&work, || {
1674 provenance_push(&test_settings(), "origin", &[push_of(&head)])
1675 });
1676 let refs = git(&remote, &["for-each-ref", PROVENANCE_FULL_REF]);
1677 assert!(refs.is_empty(), "a configured directory was read: {refs}");
1678 scratch_cleanup(&d);
1679 scratch_cleanup(&work);
1680 }
1681
1682 #[test]
1683 fn no_payload_publishes_nothing() {
1684 let (d, work, remote, head, _, _) = provenance_world("prov-none");
1685 let payloads = d.join("payloads");
1686 std::fs::create_dir_all(&payloads).unwrap();
1687 in_repo(&work, || {
1688 provenance_push_from(&payloads, "origin", &[push_of(&head)])
1689 });
1690 let refs = git(&remote, &["for-each-ref", PROVENANCE_FULL_REF]);
1691 assert!(refs.is_empty(), "{refs}");
1692 scratch_cleanup(&d);
1693 scratch_cleanup(&work);
1694 }
1695
1696 #[test]
1697 fn a_missing_key_signs_nothing() {
1698 assert!(sign("anything", Path::new("/nonexistent/key")).is_none());
1699 }
1700
1701 #[test]
1705 fn an_enabled_push_leaves_a_verifiable_note_on_the_remote() {
1706 let d = dir("e2e");
1707 let (key, signers) = keypair(&d);
1708 let remote = d.join("remote.git");
1709 std::fs::create_dir_all(&remote).unwrap();
1710 git(&remote, &["init", "-q", "--bare", "--template=", "."]);
1711 let work = repo("e2e-work");
1712 git(
1713 &work,
1714 &["remote", "add", "origin", remote.to_str().unwrap()],
1715 );
1716 git(&work, &["config", "greengate.attest", "true"]);
1717 git(
1718 &work,
1719 &["config", "greengate.attestKey", key.to_str().unwrap()],
1720 );
1721 std::fs::write(work.join("a.ts"), "x").unwrap();
1722 git(&work, &["add", "a.ts"]);
1723 git(&work, &["commit", "-qm", "chore: a"]);
1724 let head = git(&work, &["rev-parse", "HEAD"]);
1725 let tree = git(&work, &["rev-parse", "HEAD^{tree}"]);
1726 let push_ref = PushRef {
1727 local_ref: "refs/heads/main".into(),
1728 local_oid: head.clone(),
1729 remote_ref: "refs/heads/main".into(),
1730 remote_oid: "0".repeat(40),
1731 };
1732 in_repo(&work, || {
1733 attest_push(
1734 &test_settings(),
1735 "origin",
1736 &[push_ref],
1737 &["pre-push-run-tests-js".into()],
1738 &[],
1739 );
1740 });
1741 let body = git(&remote, &["notes", "--ref", NOTES_REF, "show", &head]);
1743 assert!(!body.is_empty(), "no note reached the remote");
1744 let (p, sig) = body
1745 .split_once("\n\n")
1746 .expect("payload, blank line, signature");
1747 let p = format!("{p}\n"); assert!(p.starts_with(FORMAT));
1749 assert!(
1750 p.contains(&format!("tree {tree}")),
1751 "attests the pushed tree"
1752 );
1753 assert!(
1754 verify(&p, sig, &signers, "t@t.test"),
1755 "the remote copy verifies"
1756 );
1757 scratch_cleanup(&d);
1758 scratch_cleanup(&work);
1759 }
1760
1761 #[test]
1768 fn a_push_with_a_spec_publishes_the_inputs_ref() {
1769 let (_d, work, remote, _) = remote_and_work("inputs");
1770 std::fs::create_dir_all(work.join(".github")).unwrap();
1771 std::fs::write(
1772 work.join(".github/attest-inputs"),
1773 "pre-push-run-tests-js a.ts\n",
1774 )
1775 .unwrap();
1776 git(&work, &["add", ".github/attest-inputs"]);
1777 git(&work, &["commit", "-qm", "chore: spec"]);
1778 in_repo(&work, || {
1779 attest_push(
1780 &test_settings(),
1781 "origin",
1782 &[push_ref_for(&work)],
1783 &["pre-push-run-tests-js".into()],
1784 &[],
1785 );
1786 });
1787 let listed = git(&remote, &["notes", "--ref", INPUTS_REF, "list"]);
1788 assert!(
1790 !listed.trim().is_empty(),
1791 "the inputs ref reached the remote"
1792 );
1793 }
1794
1795 #[test]
1796 fn no_opt_in_means_no_note() {
1797 let d = dir("optout");
1798 let (key, _) = keypair(&d);
1799 let remote = d.join("remote.git");
1800 std::fs::create_dir_all(&remote).unwrap();
1801 git(&remote, &["init", "-q", "--bare", "--template=", "."]);
1802 let work = repo("optout-work");
1803 git(
1804 &work,
1805 &["remote", "add", "origin", remote.to_str().unwrap()],
1806 );
1807 git(
1808 &work,
1809 &["config", "greengate.attestKey", key.to_str().unwrap()],
1810 );
1811 std::fs::write(work.join("a.ts"), "x").unwrap();
1812 git(&work, &["add", "a.ts"]);
1813 git(&work, &["commit", "-qm", "chore: a"]);
1814 let head = git(&work, &["rev-parse", "HEAD"]);
1815 let push_ref = PushRef {
1816 local_ref: "refs/heads/main".into(),
1817 local_oid: head.clone(),
1818 remote_ref: "refs/heads/main".into(),
1819 remote_oid: "0".repeat(40),
1820 };
1821 in_repo(&work, || {
1822 attest_push(
1823 &test_settings(),
1824 "origin",
1825 &[push_ref],
1826 &["pre-push-run-tests-js".into()],
1827 &[],
1828 );
1829 });
1830 assert!(
1831 git(&remote, &["notes", "--ref", NOTES_REF, "list"]).is_empty(),
1832 "an un-opted-in repo attested something"
1833 );
1834 scratch_cleanup(&d);
1835 scratch_cleanup(&work);
1836 }
1837
1838 #[test]
1841 fn deletions_and_empty_gates_attest_nothing() {
1842 let d = dir("nothing");
1843 let (key, _) = keypair(&d);
1844 let remote = d.join("remote.git");
1845 std::fs::create_dir_all(&remote).unwrap();
1846 git(&remote, &["init", "-q", "--bare", "--template=", "."]);
1847 let work = repo("nothing-work");
1848 git(
1849 &work,
1850 &["remote", "add", "origin", remote.to_str().unwrap()],
1851 );
1852 git(&work, &["config", "greengate.attest", "true"]);
1853 git(
1854 &work,
1855 &["config", "greengate.attestKey", key.to_str().unwrap()],
1856 );
1857 std::fs::write(work.join("a.ts"), "x").unwrap();
1858 git(&work, &["add", "a.ts"]);
1859 git(&work, &["commit", "-qm", "chore: a"]);
1860 let head = git(&work, &["rev-parse", "HEAD"]);
1861 let deletion = PushRef {
1862 local_ref: "(delete)".into(),
1863 local_oid: "0".repeat(40),
1864 remote_ref: "refs/heads/gone".into(),
1865 remote_oid: head.clone(),
1866 };
1867 let real = PushRef {
1868 local_ref: "refs/heads/main".into(),
1869 local_oid: head,
1870 remote_ref: "refs/heads/main".into(),
1871 remote_oid: "0".repeat(40),
1872 };
1873 in_repo(&work, || {
1874 attest_push(
1875 &test_settings(),
1876 "origin",
1877 &[deletion],
1878 &["pre-push-pytest".into()],
1879 &[],
1880 );
1881 attest_push(&test_settings(), "origin", &[real], &[], &[]);
1882 });
1883 assert!(git(&remote, &["notes", "--ref", NOTES_REF, "list"]).is_empty());
1884 scratch_cleanup(&d);
1885 scratch_cleanup(&work);
1886 }
1887
1888 #[test]
1895 fn a_rejection_is_a_note_whose_signature_did_not_verify() {
1896 let trail: Vec<String> = [
1897 "note on abc123: signature did not verify for principal t@t.test",
1898 "note on abc123 block 2: no principal matched",
1899 "note on def456 carries no signature block",
1900 "attested tree abc is not the checked-out tree def and neither its canonical tree nor an input fingerprint of abc123 matches",
1901 "no attestation found for tree abc",
1902 ]
1903 .iter()
1904 .map(|s| s.to_string())
1905 .collect();
1906 assert_eq!(
1907 signature_rejections(&trail),
1908 vec![
1909 "note on abc123: signature did not verify for principal t@t.test".to_string(),
1910 "note on abc123 block 2: no principal matched".to_string(),
1911 ]
1912 );
1913 }
1914
1915 #[test]
1916 fn covered_answers_in_a_fresh_clone_and_rejects_drift_and_forgery() {
1917 let d = dir("covered");
1918 let (key, signers) = keypair(&d);
1919 let remote = d.join("remote.git");
1920 std::fs::create_dir_all(&remote).unwrap();
1921 git(&remote, &["init", "-q", "--bare", "--template=", "."]);
1922 git(&remote, &["symbolic-ref", "HEAD", "refs/heads/main"]);
1928 let work = repo("covered-work");
1929 git(
1930 &work,
1931 &["remote", "add", "origin", remote.to_str().unwrap()],
1932 );
1933 git(&work, &["config", "greengate.attest", "true"]);
1934 git(
1935 &work,
1936 &["config", "greengate.attestKey", key.to_str().unwrap()],
1937 );
1938 std::fs::write(work.join("a.ts"), "x").unwrap();
1939 git(&work, &["add", "a.ts"]);
1940 git(&work, &["commit", "-qm", "chore: a"]);
1941 git(&work, &["push", "-q", "origin", "HEAD:main"]);
1942 let head = git(&work, &["rev-parse", "HEAD"]);
1943 let push_ref = PushRef {
1944 local_ref: "refs/heads/main".into(),
1945 local_oid: head.clone(),
1946 remote_ref: "refs/heads/main".into(),
1947 remote_oid: "0".repeat(40),
1948 };
1949 in_repo(&work, || {
1950 attest_push(
1951 &test_settings(),
1952 "origin",
1953 &[push_ref],
1954 &["pre-push-pytest".into()],
1955 &[],
1956 );
1957 });
1958 let clone = d.join("ci-checkout");
1959 git(
1960 &d,
1961 &[
1962 "clone",
1963 "-q",
1964 "--template=",
1965 remote.to_str().unwrap(),
1966 clone.to_str().unwrap(),
1967 ],
1968 );
1969 in_repo(&clone, || {
1970 assert_eq!(
1971 covered(&signers, Some("t@t.test"), Some(&platform()), &[]).as_deref(),
1972 Some("pre-push-pytest"),
1973 "a fresh clone verifies the attestation and reads the gates"
1974 );
1975 assert_eq!(
1976 covered(&signers, Some("t@t.test"), None, &[]).as_deref(),
1977 Some("pre-push-pytest"),
1978 "`any` covers a platform-independent suite"
1979 );
1980 assert_eq!(
1983 covered(&signers, Some("t@t.test"), Some("s390x-aix"), &[]),
1984 None,
1985 "a pass on one platform is not evidence about another"
1986 );
1987 assert_eq!(
1988 covered(&signers, Some("someone@else.test"), None, &[]),
1989 None,
1990 "an unlisted principal covers nothing"
1991 );
1992 });
1993 std::fs::write(clone.join("b.ts"), "y").unwrap();
1995 git(&clone, &["config", "user.email", "t@t.test"]);
1996 git(&clone, &["config", "user.name", "t"]);
1997 git(&clone, &["add", "b.ts"]);
1998 git(&clone, &["commit", "-qm", "chore: b"]);
1999 in_repo(&clone, || {
2000 assert_eq!(
2001 covered(&signers, Some("t@t.test"), None, &[]),
2002 None,
2003 "drifted tree"
2004 );
2005 });
2006 let head_tree = git(&work, &["rev-parse", "HEAD^{tree}"]);
2016 for object in [&head, &head_tree] {
2017 git(
2018 &work,
2019 &[
2020 "notes", "--ref", NOTES_REF, "add", "-f", "-m", "garbage", object,
2021 ],
2022 );
2023 }
2024 git(
2025 &work,
2026 &[
2027 "push",
2028 "-q",
2029 "origin",
2030 &format!("+{NOTES_FULL_REF}:{NOTES_FULL_REF}"),
2031 ],
2032 );
2033 git(
2037 &work,
2038 &["push", "-q", "origin", &format!(":{INPUTS_FULL_REF}")],
2039 );
2040 git(&clone, &["reset", "-q", "--hard", &head]);
2041 in_repo(&clone, || {
2042 assert_eq!(
2043 covered(&signers, Some("t@t.test"), None, &[]),
2044 None,
2045 "a foreign note is not a stamp"
2046 );
2047 });
2048 scratch_cleanup(&d);
2049 scratch_cleanup(&work);
2050 }
2051
2052 #[test]
2058 fn default_signers_is_found_from_a_subdirectory() {
2059 let work = repo("signers-subdir");
2060 std::fs::create_dir_all(work.join(".forgejo")).unwrap();
2061 std::fs::write(work.join(".forgejo/allowed_signers"), "t@t.test x\n").unwrap();
2062 let sub = work.join("packages").join("thing");
2063 std::fs::create_dir_all(&sub).unwrap();
2064 in_repo(&sub, || {
2065 let found = default_signers().expect("resolved from the repo root, not the cwd");
2066 assert!(found.ends_with(".forgejo/allowed_signers"));
2067 assert!(found.exists(), "the path it returns must be usable as-is");
2068 });
2069 scratch_cleanup(&work);
2070 }
2071
2072 #[test]
2073 fn zero_oids_of_any_width_are_zero() {
2074 assert!(is_zero(&"0".repeat(40)));
2075 assert!(is_zero(&"0".repeat(64)));
2076 assert!(!is_zero("0a0000"));
2077 assert!(!is_zero(""));
2078 }
2079
2080 #[test]
2081 fn forget_removes_the_local_ref() {
2082 let work = repo("forget");
2083 std::fs::write(work.join("a.ts"), "x").unwrap();
2084 git(&work, &["add", "a.ts"]);
2085 git(&work, &["commit", "-qm", "chore: a"]);
2086 git(
2087 &work,
2088 &["notes", "--ref", NOTES_REF, "add", "-m", "x", "HEAD"],
2089 );
2090 in_repo(&work, forget);
2091 assert!(git(&work, &["notes", "--ref", NOTES_REF, "list"]).is_empty());
2092 scratch_cleanup(&work);
2093 }
2094
2095 pub(crate) fn both_names_signer(dir: &Path) -> (PathBuf, PathBuf) {
2107 let key = dir.join("signer_key");
2108 let ok = std::process::Command::new("ssh-keygen")
2109 .args(["-q", "-t", "ed25519", "-N", "", "-C", "test", "-f"])
2110 .arg(&key)
2111 .status()
2112 .expect("ssh-keygen must exist for these tests")
2113 .success();
2114 assert!(ok, "keygen failed");
2115 let pubkey = std::fs::read_to_string(key.with_extension("pub")).unwrap();
2116 let signers = dir.join("allowed_signers");
2117 std::fs::write(
2118 &signers,
2119 format!(
2120 "cluster-signer@{} namespaces=\"{},{}\" {pubkey}",
2121 crate::cluster::PLATFORM,
2122 git_attest::format::LEGACY.namespace,
2123 git_attest::format::GREEN.namespace
2124 ),
2125 )
2126 .unwrap();
2127 (key, signers)
2128 }
2129
2130 pub(crate) fn block_with(header: &str, namespace: &str, tree: &str, key: &Path) -> String {
2132 let payload = format!(
2133 "{header}\ntree {tree}\ngates suite\nplatform {}\ngreengate 0.0.0\n",
2134 crate::cluster::PLATFORM
2135 );
2136 let sig = git_attest::sign::sign(namespace, &payload, key).expect("sign");
2137 block(&payload, &sig)
2138 }
2139
2140 #[test]
2141 fn a_signer_block_is_checked_under_the_namespace_its_header_names() {
2142 use git_attest::format::{GREEN, LEGACY};
2143 let scratch = dir("signer-names");
2144 let (key, signers) = both_names_signer(&scratch);
2145 let tree = "0123456789012345678901234567890123456789";
2146 for set in [GREEN, LEGACY] {
2147 let body = block_with(set.format, set.namespace, tree, &key);
2148 let checked = signer_block(&body, tree, &signers)
2149 .unwrap_or_else(|e| panic!("{}: {}", set.format, e.reason()));
2150 assert_eq!(checked.names, set);
2151 assert_eq!(checked.gates, ["suite"]);
2152 }
2153 for (header, signed_under) in [(LEGACY, GREEN), (GREEN, LEGACY)] {
2154 let body = block_with(header.format, signed_under.namespace, tree, &key);
2155 assert!(
2156 matches!(
2157 signer_block(&body, tree, &signers),
2158 Err(BlockRefusal::Signer(_))
2159 ),
2160 "a {} block signed under {} must be refused",
2161 header.format,
2162 signed_under.namespace
2163 );
2164 }
2165 scratch_cleanup(&scratch);
2166 }
2167
2168 #[test]
2169 fn forget_in_removes_the_notes_ref_of_both_name_sets() {
2170 let repo_dir = repo("forget-both");
2171 git(&repo_dir, &["commit", "-q", "--allow-empty", "-m", "c"]);
2172 for names in READ_NAMES {
2173 git(
2174 &repo_dir,
2175 &["notes", "--ref", names.notes_ref, "add", "-m", "x", "HEAD"],
2176 );
2177 }
2178 assert!(forget_in(&repo_dir));
2179 for names in READ_NAMES {
2180 let full = format!("refs/notes/{}", names.notes_ref);
2181 let out = std::process::Command::new("git")
2182 .arg("-C")
2183 .arg(&repo_dir)
2184 .args(["rev-parse", "--verify", "-q", &full])
2185 .output()
2186 .unwrap();
2187 assert!(!out.status.success(), "{full} survived forget_in");
2188 }
2189 scratch_cleanup(&repo_dir);
2190 }
2191
2192 #[test]
2193 fn filed_signer_blocks_drops_a_block_of_the_other_name_set() {
2194 use git_attest::format::{GREEN, LEGACY};
2195 let work = repo("filed-names");
2196 std::fs::write(work.join("a.txt"), "x").unwrap();
2197 git(&work, &["add", "a.txt"]);
2198 git(&work, &["commit", "-qm", "chore: a"]);
2199 let (key, signers) = both_names_signer(&work);
2200 std::fs::create_dir_all(work.join(".forgejo")).unwrap();
2201 std::fs::copy(&signers, work.join(".forgejo/allowed_signers")).unwrap();
2202 let tree = git(&work, &["rev-parse", "HEAD^{tree}"]);
2203 let green = block_with(GREEN.format, GREEN.namespace, &tree, &key);
2204 let legacy = block_with(LEGACY.format, LEGACY.namespace, &tree, &key);
2205 in_repo(&work, || {
2206 file_signer_block(&legacy, &[&tree]).expect("file the legacy block");
2207 assert!(
2208 filed_signer_blocks(&tree).is_empty(),
2209 "a legacy block is not publishable while WRITE is green"
2210 );
2211 file_signer_block(&format!("{legacy}\n{green}"), &[&tree]).expect("file both");
2212 let kept = filed_signer_blocks(&tree);
2213 assert_eq!(kept.len(), 1, "{kept:?}");
2214 assert_eq!(kept[0].names, git_attest::format::WRITE);
2215 assert_eq!(kept[0].names, GREEN);
2216 assert!(kept[0].is_publishable());
2217 });
2218 scratch_cleanup(&work);
2219 }
2220
2221 #[test]
2222 fn a_verification_says_which_name_it_went_through() {
2223 let mut verdict = git_attest::verify::Verdict::nothing("test");
2224 assert!(verified_lines(&verdict).is_empty());
2225 verdict.verified_under = vec![
2226 git_attest::format::GREEN.namespace.to_string(),
2227 git_attest::format::LEGACY.namespace.to_string(),
2228 ];
2229 assert_eq!(
2230 verified_lines(&verdict),
2231 [
2232 format!("verified under {}", git_attest::format::GREEN.namespace),
2233 format!("verified under {}", git_attest::format::LEGACY.namespace),
2234 ]
2235 );
2236 }
2237}