use crate::names::BIN;
use std::path::{Path, PathBuf};
use git_attest::format::block;
use git_attest::notes::{publish as publish_notes, Publish, Published};
use git_attest::produce::attestation;
use crate::pushrefs::PushRef;
pub use git_attest::format::{platform, FORMAT, INPUTS_REF, NAMESPACE, NOTES_REF};
pub use git_attest::notes::{classify_push as classify_push_stderr, PushFailure};
const READ_NAMES: [git_attest::format::Names; 2] =
[git_attest::format::GREEN, git_attest::format::LEGACY];
pub const NOTES_FULL_REF: &str = "refs/notes/greengate-attest";
pub const INPUTS_FULL_REF: &str = "refs/notes/greengate-attest-inputs";
const PROVENANCE_LEGACY_FORMAT: &str = "amont-provenance-v1";
pub const PROVENANCE_REF: &str = "greengate-provenance";
pub const PROVENANCE_FULL_REF: &str = "refs/notes/greengate-provenance";
pub const PROVENANCE_NAMESPACE: &str = "greengate-provenance";
pub const PROVENANCE_FORMAT: &str = "greengate-provenance-v1";
pub const PUSH_GUARD: &str = "GREENGATE_ATTEST_PUSH";
fn here() -> &'static Path {
Path::new(".")
}
const TOGGLE: &str = "greengate.attest";
pub(crate) const KEY_CONFIG: &str = "greengate.attestKey";
const KEY_DEFAULT: &str = ".ssh/greengate-attest";
const KEY_FALLBACK: &str = ".ssh/amont-attest";
pub fn push_guard_active() -> bool {
std::env::var_os(PUSH_GUARD).is_some()
}
pub fn enabled(settings: &crate::config::Settings) -> bool {
crate::config::boolean_or(settings, TOGGLE, false)
}
fn key_path() -> Option<PathBuf> {
if let Some(k) = crate::git::stdout(&["config", "--get", KEY_CONFIG]) {
if !k.is_empty() {
return Some(PathBuf::from(k));
}
}
let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE"))?;
Some(default_key_in(Path::new(&home)))
}
fn default_key_in(home: &Path) -> PathBuf {
let green = home.join(KEY_DEFAULT);
let old = home.join(KEY_FALLBACK);
if !green.exists() && old.exists() {
old
} else {
green
}
}
pub fn key_move_hint_in(home: &Path) -> Option<String> {
(!home.join(KEY_DEFAULT).exists() && home.join(KEY_FALLBACK).exists()).then(|| {
format!(
"the signing key is still ~/{KEY_FALLBACK}; rename it: mv ~/{KEY_FALLBACK} ~/{KEY_DEFAULT} (and the .pub beside it)"
)
})
}
pub fn attest_push(
settings: &crate::config::Settings,
remote: &str,
refs: &[PushRef],
gates: &[String],
cluster_gates: &[String],
) {
attest_push_per_tip(settings, remote, refs, &|_| gates.to_vec(), cluster_gates);
}
pub fn attest_push_per_tip(
settings: &crate::config::Settings,
remote: &str,
refs: &[PushRef],
gates_for: &dyn Fn(&str) -> Vec<String>,
cluster_gates: &[String],
) {
if remote.is_empty() || !enabled(settings) {
return;
}
let Some(key) = key_path() else { return };
if !key.exists() {
crate::config::complain(
TOGGLE,
&format!("signing key {} does not exist", key.display()),
"no attestation (CI will run the tests)",
);
return;
}
let producer = env!("CARGO_PKG_VERSION");
let mut laptop_signed: Vec<String> = Vec::new();
let mut blocks: Vec<(String, String)> = Vec::new();
let mut input_blocks: Vec<(String, String)> = Vec::new();
let mut linux_signed: Vec<String> = Vec::new();
let (mut n_inputs, mut n_canon) = (0, 0);
let in_cluster = std::cell::OnceCell::new();
for r in refs {
if is_zero(&r.local_oid) {
continue; }
let gates = gates_for(&r.local_oid);
if gates.is_empty() && cluster_gates.is_empty() {
continue;
}
let gates_line = gates.join(" ");
let spec = format!("{}^{{tree}}", r.local_oid);
let Some(tree) = crate::git::stdout(&["rev-parse", &spec]) else {
continue;
};
let mut proved_here: Vec<String> = cluster_gates
.iter()
.filter(|g| crate::cluster::proved(g, &tree))
.cloned()
.collect();
if !proved_here.is_empty()
&& *in_cluster.get_or_init(|| crate::cluster::in_cluster_signer().is_some())
{
for signed in filed_signer_blocks(&tree) {
let (covered, rest): (Vec<String>, Vec<String>) = proved_here
.into_iter()
.partition(|g| signed.gates.contains(g));
proved_here = rest;
if covered.is_empty() {
continue;
}
for name in covered {
if !linux_signed.contains(&name) {
linux_signed.push(name);
}
}
blocks.push((tree.clone(), signed.body.clone()));
blocks.push((r.local_oid.clone(), signed.body));
}
}
let platforms = [
(platform(), gates_line.clone(), Vec::new()),
(
crate::cluster::PLATFORM.to_string(),
proved_here.join(" "),
proved_here,
),
];
let mut counted = false;
for (on, line, linux_names) in platforms {
if line.is_empty() {
continue;
}
let mut reasons = Vec::new();
let att = attestation(here(), &tree, &line, &on, producer, &mut reasons);
let Ok(sig) = git_attest::sign::sign(NAMESPACE, &att.payload, &key) else {
continue;
};
let body = block(&att.payload, &sig);
if !counted {
n_inputs += att.inputs.len();
n_canon += usize::from(att.canon.is_some());
counted = true;
}
for k in &att.input_keys {
input_blocks.push((k.clone(), body.clone()));
}
blocks.push((tree.clone(), body.clone()));
blocks.push((r.local_oid.clone(), body));
if linux_names.is_empty() {
for name in &gates {
if !laptop_signed.contains(name) {
laptop_signed.push(name.clone());
}
}
}
for name in linux_names {
if !linux_signed.contains(&name) {
linux_signed.push(name);
}
}
}
}
if blocks.is_empty() {
return;
}
let main_ok = publish(remote, NOTES_REF, &blocks);
let inputs_ok = input_blocks.is_empty() || publish(remote, INPUTS_REF, &input_blocks);
if main_ok {
let mut signed_on = Vec::new();
if !laptop_signed.is_empty() {
signed_on.push(format!(
"{} on {}",
crate::ui::highlight(&laptop_signed.join(" ")),
platform()
));
}
if !linux_signed.is_empty() {
signed_on.push(format!(
"{} on {}",
crate::ui::highlight(&linux_signed.join(" ")),
crate::cluster::PLATFORM
));
}
let what = signed_on.join("; ");
crate::say!(
"{} attested {} for CI ({}{})",
crate::ui::valid_sign(),
what,
NOTES_REF,
if input_blocks.is_empty() {
String::new()
} else if inputs_ok {
match (n_inputs, n_canon) {
(0, _) => ", canonical tree".to_string(),
(n, 0) => format!(", {n} input fingerprints"),
(n, _) => format!(", {n} input fingerprints, canonical tree"),
}
} else {
", input fingerprints not published".to_string()
},
);
}
}
const PROVENANCE_OWNER: &str = "greenbelay";
const OLD_PROVENANCE_OWNER: &str = "amont-agent";
fn provenance_dirs(env: impl Fn(&str) -> Option<std::ffi::OsString>) -> Option<[PathBuf; 2]> {
let config = match env("CLAUDE_CONFIG_DIR") {
Some(d) => PathBuf::from(d),
None => PathBuf::from(env("HOME").or_else(|| env("USERPROFILE"))?).join(".claude"),
};
Some([PROVENANCE_OWNER, OLD_PROVENANCE_OWNER].map(|o| config.join(o).join("provenance")))
}
fn read_payload(dirs: &[PathBuf], commit: &str) -> Option<(usize, PathBuf, String)> {
for (at, dir) in dirs.iter().enumerate() {
let file = dir.join(commit);
match std::fs::read_to_string(&file) {
Ok(text) => return Some((at, file, text)),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(_) => return None,
}
}
None
}
fn repo_name() -> Option<String> {
let common = crate::git::stdout(&["rev-parse", "--git-common-dir"])?;
if common.is_empty() {
return None;
}
let common = PathBuf::from(common);
let common = if common.is_absolute() {
common
} else {
std::env::current_dir().ok()?.join(common)
};
let common = std::fs::canonicalize(&common).unwrap_or(common);
common
.parent()
.and_then(std::path::Path::file_name)
.map(|n| n.to_string_lossy().into_owned())
.filter(|n| !n.is_empty())
}
pub fn provenance_push(settings: &crate::config::Settings, remote: &str, refs: &[PushRef]) {
if remote.is_empty() || !enabled(settings) {
return;
}
let (Some(dirs), Some(name)) = (provenance_dirs(|k| std::env::var_os(k)), repo_name()) else {
return;
};
provenance_push_from_dirs(&dirs.map(|d| d.join(&name)), remote, refs);
}
#[cfg(test)]
fn provenance_push_from(dir: &std::path::Path, remote: &str, refs: &[PushRef]) {
provenance_push_from_dirs(&[dir.to_path_buf()], remote, refs);
}
fn provenance_push_from_dirs(dirs: &[PathBuf], remote: &str, refs: &[PushRef]) {
let mut found: Vec<PendingRecord> = Vec::new();
let mut named_old = false;
for r in refs {
if is_zero(&r.local_oid) {
continue;
}
let Some((at, file, payload)) = read_payload(dirs, &r.local_oid) else {
continue; };
if at > 0 && !named_old {
named_old = true;
crate::say!(
" provenance read from {} (amont-agent's directory, until greenbelay migrates it)",
dirs[at].display()
);
}
let spec = format!("{}^{{tree}}", r.local_oid);
let Some(tree) = crate::git::stdout(&["rev-parse", &spec]) else {
continue;
};
let first = payload.lines().next().unwrap_or_default();
let claimed = payload.lines().find_map(|l| l.strip_prefix("tree "));
if first == PROVENANCE_LEGACY_FORMAT {
crate::say!("{}", legacy_provenance_line(&r.local_oid, &file));
continue;
}
if first != PROVENANCE_FORMAT || claimed != Some(tree.as_str()) {
crate::say!(
" provenance for {} not signed: its payload is not a {PROVENANCE_FORMAT} record of this tree",
&r.local_oid[..r.local_oid.len().min(7)]
);
continue;
}
if payload
.lines()
.any(|l| l.split_ascii_whitespace().next() == Some("canon"))
{
for line in canon_refusal(&r.local_oid, &file) {
crate::say!("{line}");
}
continue;
}
let Ok(canon) = git_attest::fingerprint::canon(here(), &tree) else {
crate::say!(
" provenance for {} not signed: its canonical tree cannot be computed;",
&r.local_oid[..r.local_oid.len().min(7)]
);
crate::say!(" the payload is kept for the next push");
continue;
};
let payload = with_canon(&payload, &canon);
found.push(PendingRecord {
file,
commit: r.local_oid.clone(),
tree,
payload,
});
}
if found.is_empty() {
return;
}
let Some(key) = key_path().filter(|k| k.exists()) else {
crate::say!(" provenance not signed: no signing key");
return;
};
let mut blocks: Vec<(String, String)> = Vec::new();
let mut signed: Vec<PathBuf> = Vec::new();
for rec in found {
let sig = match git_attest::sign::sign(PROVENANCE_NAMESPACE, &rec.payload, &key) {
Ok(sig) => sig,
Err(e) => {
crate::say!(
" provenance for {} not signed: {e}; kept for the next push",
&rec.commit[..rec.commit.len().min(7)]
);
continue;
}
};
let body = block(&rec.payload, &sig);
blocks.push((rec.tree, body.clone()));
blocks.push((rec.commit, body));
signed.push(rec.file);
}
if blocks.is_empty() {
return; }
if publish(remote, PROVENANCE_REF, &blocks) {
for file in &signed {
if std::fs::remove_file(file).is_err() {
crate::say!(
" provenance published, but its payload {} could not be removed",
file.display()
);
}
}
crate::say!(
"{} provenance published ({PROVENANCE_REF})",
crate::ui::valid_sign()
);
} else {
crate::say!(" provenance not published: kept for the next push");
}
}
struct PendingRecord {
file: PathBuf,
commit: String,
tree: String,
payload: String,
}
fn legacy_provenance_line(commit: &str, file: &Path) -> String {
format!(
" provenance for {} not signed: {} was written by an older release of the hook: upgrade greenbelay, then delete {} or re-run its review",
&commit[..commit.len().min(7)],
file.display(),
file.display()
)
}
fn with_canon(payload: &str, canon: &str) -> String {
let mut out = String::with_capacity(payload.len() + canon.len() + 7);
let mut done = false;
for line in payload.split_inclusive('\n') {
out.push_str(line);
if !done && line.starts_with("tree ") {
if !line.ends_with('\n') {
out.push('\n');
}
out.push_str(&format!("canon {canon}\n"));
done = true;
}
}
out
}
fn canon_refusal(commit: &str, file: &std::path::Path) -> Vec<String> {
let dir = file.parent().unwrap_or(file).display().to_string();
let name = file
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
vec![
format!(
" provenance for {} not signed: its payload carries a canon line",
&commit[..commit.len().min(7)]
),
" (a pre-release build of the hook wrote it); delete the file".to_string(),
format!(" {name} in"),
format!(" {dir}"),
" and upgrade greenbelay".to_string(),
]
}
const PUSH_ATTEMPTS: u32 = 4;
fn publish(remote: &str, notes_ref: &str, blocks: &[(String, String)]) -> bool {
let how = Publish {
remote,
attempts: PUSH_ATTEMPTS,
pause: false,
identity: None,
push_env: &[(PUSH_GUARD, "1")],
};
let mut log = Vec::new();
matches!(
publish_notes(here(), &how, notes_ref, blocks, &mut log),
Published::Pushed | Published::AlreadyPresent
)
}
pub fn covered(
signers: &Path,
principal: Option<&str>,
require_platform: Option<&str>,
anywhere: &[String],
) -> Option<String> {
covered_in(here(), signers, principal, require_platform, anywhere)
}
pub fn covered_in(
dir: &Path,
signers: &Path,
principal: Option<&str>,
require_platform: Option<&str>,
anywhere: &[String],
) -> Option<String> {
covered_report(dir, signers, principal, require_platform, anywhere).gates
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Covered {
pub gates: Option<String>,
pub rejected: Vec<String>,
}
pub fn covered_report(
dir: &Path,
signers: &Path,
principal: Option<&str>,
require_platform: Option<&str>,
anywhere: &[String],
) -> Covered {
let verdict =
git_attest::verify::evaluate(dir, signers, principal, require_platform, anywhere, false);
for line in verdict.loud.iter().chain(&verdict.warnings) {
eprintln!("{BIN}: {line}");
}
for line in verified_lines(&verdict) {
eprintln!("{BIN}: {line}");
}
let rejected = signature_rejections(&verdict.trail);
for why in &rejected {
eprintln!("{BIN}: an attestation was found but did not verify: {why}");
}
Covered {
gates: (!verdict.gates.is_empty()).then(|| verdict.gates.join(" ")),
rejected,
}
}
fn verified_lines(verdict: &git_attest::verify::Verdict) -> Vec<String> {
verdict
.verified_under
.iter()
.map(|ns| format!("verified under {ns}"))
.collect()
}
fn signature_rejections(trail: &[String]) -> Vec<String> {
trail
.iter()
.filter(|line| line.starts_with("note on ") && line.contains(": "))
.cloned()
.collect()
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct SignerBlock {
pub principal: String,
pub gates: Vec<String>,
pub body: String,
pub names: git_attest::format::Names,
}
impl SignerBlock {
pub(crate) fn is_publishable(&self) -> bool {
self.names == git_attest::format::WRITE
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum BlockRefusal {
Signer(String),
Content(String),
}
impl BlockRefusal {
pub(crate) fn reason(&self) -> &str {
match self {
BlockRefusal::Signer(why) | BlockRefusal::Content(why) => why,
}
}
}
pub(crate) fn signer_block(
body: &str,
tree: &str,
signers: &Path,
) -> Result<SignerBlock, BlockRefusal> {
use git_attest::format::{bound_platform, field, split_blocks};
use BlockRefusal::{Content, Signer};
let (mut blocks, _) = split_blocks(body);
if blocks.len() != 1 {
return Err(Content(format!("{} signed blocks, not one", blocks.len())));
}
let signed_block = blocks.remove(0);
let header = signed_block.payload.split('\n').next();
let Some(names) = READ_NAMES.into_iter().find(|n| Some(n.format) == header) else {
return Err(Content(format!(
"not an {} or {} payload",
git_attest::format::GREEN.format,
git_attest::format::LEGACY.format
)));
};
let on = field(&signed_block.payload, "platform");
if on != Some(crate::cluster::PLATFORM) {
return Err(Content(format!(
"its platform is {}, not {}",
on.unwrap_or("missing"),
crate::cluster::PLATFORM
)));
}
let claimed = field(&signed_block.payload, "tree");
if claimed != Some(tree) {
return Err(Content(format!(
"it is for tree {}, not {tree}",
claimed.unwrap_or("missing")
)));
}
let principal = git_attest::sign::verify(
names.namespace,
&signed_block.payload,
&signed_block.signature,
signers,
None,
)
.map_err(|e| Signer(e.to_string()))?;
if bound_platform(&principal) != Some(crate::cluster::PLATFORM) {
return Err(Signer(format!(
"{principal} is not a principal bound to {}",
crate::cluster::PLATFORM
)));
}
Ok(SignerBlock {
principal,
gates: field(&signed_block.payload, "gates")
.unwrap_or("")
.split_whitespace()
.map(str::to_string)
.collect(),
body: block(&signed_block.payload, &signed_block.signature),
names,
})
}
fn signer_notes_ref() -> String {
format!("{}{NOTES_REF}", git_attest::format::LOCAL_PREFIX)
}
pub(crate) fn file_signer_block(body: &str, keys: &[&str]) -> Result<(), String> {
let notes_ref = signer_notes_ref();
for key in keys {
let entry = [((*key).to_string(), body.to_string())];
if matches!(
git_attest::notes::publish_local(here(), None, ¬es_ref, &entry),
Published::Error
) {
return Err(format!(
"git could not write the note on {key} in {notes_ref}"
));
}
}
Ok(())
}
fn filed_signer_blocks(tree: &str) -> Vec<SignerBlock> {
use git_attest::format::{field, split_blocks};
let Some(signers) = default_signers() else {
return Vec::new();
};
let notes_ref = signer_notes_ref();
let Some(note) = crate::git::stdout(&["notes", "--ref", ¬es_ref, "show", tree]) else {
return Vec::new();
};
split_blocks(¬e)
.0
.iter()
.filter(|b| {
field(&b.payload, "platform") == Some(crate::cluster::PLATFORM)
&& field(&b.payload, "tree") == Some(tree)
})
.filter_map(|b| signer_block(&block(&b.payload, &b.signature), tree, &signers).ok())
.filter(SignerBlock::is_publishable)
.collect()
}
pub fn default_signers() -> Option<PathBuf> {
git_attest::verify::default_signers(here())
}
fn is_zero(oid: &str) -> bool {
!oid.is_empty() && oid.bytes().all(|b| b == b'0')
}
pub fn forget() -> bool {
forget_in(here())
}
pub fn forget_in(repo: &std::path::Path) -> bool {
let mut deleted = false;
for names in READ_NAMES {
let full = format!("refs/notes/{}", names.notes_ref);
deleted |= crate::git::succeeds_in(repo, &["update-ref", "-d", &full]);
}
deleted
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
use std::process::Stdio;
pub(crate) fn scratch_cleanup(path: &Path) {
let _ = std::fs::remove_dir_all(path); }
#[test]
fn the_written_names_are_green_and_each_full_ref_names_its_ref() {
for (full, short) in [
(NOTES_FULL_REF, NOTES_REF),
(INPUTS_FULL_REF, INPUTS_REF),
(PROVENANCE_FULL_REF, PROVENANCE_REF),
] {
assert_eq!(full, format!("refs/notes/{short}"));
assert!(full.starts_with("refs/notes/greengate-"), "{full}");
}
assert_eq!(git_attest::format::WRITE, git_attest::format::GREEN);
}
fn canon(tree: &str) -> Option<String> {
git_attest::fingerprint::canon(here(), tree).ok()
}
fn sign(payload: &str, key: &Path) -> Option<String> {
git_attest::sign::sign(NAMESPACE, payload, key).ok()
}
fn verify(payload: &str, sig: &str, signers: &Path, principal: &str) -> bool {
verify_in(NAMESPACE, payload, sig, signers, principal)
}
fn verify_in(
namespace: &str,
payload: &str,
sig: &str,
signers: &Path,
principal: &str,
) -> bool {
git_attest::sign::verify(namespace, payload, sig, signers, Some(principal)).is_ok()
}
fn test_settings() -> crate::config::Settings {
crate::config::Settings::default()
}
use std::io::Write;
use std::path::Path;
pub(crate) fn dir(name: &str) -> PathBuf {
let d = std::env::temp_dir().join(format!("attest-{name}-{}", std::process::id()));
scratch_cleanup(&d);
std::fs::create_dir_all(&d).unwrap();
d
}
fn git(dir: &Path, args: &[&str]) -> String {
let out = std::process::Command::new("git")
.arg("-C")
.arg(dir)
.args(args)
.output()
.expect("git");
assert!(
out.status.success(),
"fixture: git {args:?} in {} exited {:?}: {}",
dir.display(),
out.status.code(),
String::from_utf8_lossy(&out.stderr).trim()
);
String::from_utf8_lossy(&out.stdout).trim().to_string()
}
fn repo(name: &str) -> PathBuf {
let d = dir(name);
git(&d, &["init", "-q", "--template=", "."]);
git(&d, &["config", "user.email", "t@t.test"]);
git(&d, &["config", "user.name", "t"]);
d
}
fn keypair(d: &Path) -> (PathBuf, PathBuf) {
let key = d.join("attest_key");
let ok = std::process::Command::new("ssh-keygen")
.args(["-q", "-t", "ed25519", "-N", "", "-C", "test", "-f"])
.arg(&key)
.status()
.expect("ssh-keygen must exist for these tests")
.success();
assert!(ok, "keygen failed");
let pubkey = std::fs::read_to_string(key.with_extension("pub")).unwrap();
let signers = d.join("allowed_signers");
std::fs::write(
&signers,
format!("t@t.test namespaces=\"{NAMESPACE}\" {pubkey}"),
)
.unwrap();
(key, signers)
}
fn in_repo<T>(dir: &Path, f: impl FnOnce() -> T) -> T {
let _guard = crate::TEST_CWD.lock().unwrap_or_else(|p| p.into_inner());
let prev = std::env::current_dir().unwrap();
std::env::set_current_dir(dir).unwrap();
let r = f();
std::env::set_current_dir(prev).unwrap();
r
}
fn remote_and_work(name: &str) -> (PathBuf, PathBuf, PathBuf, PathBuf) {
let d = dir(name);
let (key, signers) = keypair(&d);
let remote = d.join("remote.git");
std::fs::create_dir_all(&remote).unwrap();
git(&remote, &["init", "-q", "--bare", "--template=", "."]);
let work = repo(&format!("{name}-work"));
git(
&work,
&["remote", "add", "origin", remote.to_str().unwrap()],
);
git(&work, &["config", "greengate.attest", "true"]);
git(
&work,
&["config", "greengate.attestKey", key.to_str().unwrap()],
);
std::fs::write(work.join("a.ts"), "x").unwrap();
git(&work, &["add", "a.ts"]);
git(&work, &["commit", "-qm", "chore: a"]);
(d, work, remote, signers)
}
fn push_ref_for(work: &Path) -> PushRef {
PushRef {
local_ref: "refs/heads/main".into(),
local_oid: git(work, &["rev-parse", "HEAD"]),
remote_ref: "refs/heads/main".into(),
remote_oid: "0".repeat(40),
}
}
#[test]
fn each_payload_is_read_from_the_new_dir_first_then_the_old() {
let config = dir("provenance-names");
let new = config.join("greenbelay/provenance/r");
let old = config.join("amont-agent/provenance/r");
let dirs = [new.clone(), old.clone()];
assert_eq!(read_payload(&dirs, "c1"), None, "neither holds it");
std::fs::create_dir_all(&old).unwrap();
std::fs::write(old.join("c1"), "old").unwrap();
assert_eq!(
read_payload(&dirs, "c1"),
Some((1, old.join("c1"), "old".into())),
"old alone"
);
std::fs::create_dir_all(&new).unwrap();
assert_eq!(read_payload(&dirs, "c1").map(|(at, ..)| at), Some(1));
std::fs::write(new.join("c1"), "new").unwrap();
assert_eq!(
read_payload(&dirs, "c1"),
Some((0, new.join("c1"), "new".into())),
"both: the new"
);
std::fs::create_dir_all(new.join("c2")).unwrap();
std::fs::write(old.join("c2"), "old").unwrap();
assert_eq!(read_payload(&dirs, "c2"), None);
}
#[test]
fn the_provenance_dir_is_resolved_like_greenbelays_config_dir() {
use std::ffi::OsString;
let env = |pairs: &'static [(&'static str, &'static str)]| {
move |k: &str| {
pairs
.iter()
.find(|(n, _)| *n == k)
.map(|(_, v)| OsString::from(v))
}
};
assert_eq!(
provenance_dirs(env(&[("CLAUDE_CONFIG_DIR", "/c"), ("HOME", "/h")])),
Some([
PathBuf::from("/c/greenbelay/provenance"),
PathBuf::from("/c/amont-agent/provenance")
])
);
assert_eq!(
provenance_dirs(env(&[("HOME", "/h"), ("USERPROFILE", "/u")])),
Some([
PathBuf::from("/h/.claude/greenbelay/provenance"),
PathBuf::from("/h/.claude/amont-agent/provenance")
])
);
assert_eq!(
provenance_dirs(env(&[("USERPROFILE", "/u")])),
Some([
PathBuf::from("/u/.claude/greenbelay/provenance"),
PathBuf::from("/u/.claude/amont-agent/provenance")
])
);
assert_eq!(provenance_dirs(env(&[])), None);
}
fn provenance_world(name: &str) -> (PathBuf, PathBuf, PathBuf, String, String, PathBuf) {
provenance_world_in(name, None)
}
fn provenance_world_in(
name: &str,
object_format: Option<&str>,
) -> (PathBuf, PathBuf, PathBuf, String, String, PathBuf) {
let d = dir(name);
let (key, _) = keypair(&d);
let pubkey = std::fs::read_to_string(key.with_extension("pub")).unwrap();
let signers = d.join("allowed_signers_provenance");
std::fs::write(
&signers,
format!("t@t.test namespaces=\"{NAMESPACE},{PROVENANCE_NAMESPACE}\" {pubkey}"),
)
.unwrap();
let remote = d.join("remote.git");
std::fs::create_dir_all(&remote).unwrap();
let fmt = format!("--object-format={}", object_format.unwrap_or("sha1"));
git(&remote, &["init", "-q", "--bare", "--template=", &fmt, "."]);
let work = match object_format {
None => repo(&format!("{name}-work")),
Some(f) => {
let w = dir(&format!("{name}-work"));
let fmt = format!("--object-format={f}");
git(&w, &["init", "-q", "--template=", &fmt, "."]);
git(&w, &["config", "user.email", "t@t.test"]);
git(&w, &["config", "user.name", "t"]);
w
}
};
git(
&work,
&["remote", "add", "origin", remote.to_str().unwrap()],
);
git(&work, &["config", "greengate.attest", "true"]);
git(
&work,
&["config", "greengate.attestKey", key.to_str().unwrap()],
);
std::fs::write(work.join("README.md"), "words").unwrap();
std::fs::create_dir_all(work.join("docs/plans")).unwrap();
std::fs::write(work.join("docs/plans/p.md"), "# P\n").unwrap();
git(&work, &["add", "README.md", "docs/plans/p.md"]);
git(&work, &["commit", "-qm", "docs: words"]);
let head = git(&work, &["rev-parse", "HEAD"]);
let tree = git(&work, &["rev-parse", "HEAD^{tree}"]);
(d, work, remote, head, tree, signers)
}
fn record(head: &str, tree: &str) -> String {
format!(
"{PROVENANCE_FORMAT}\ncommit {head}\ntree {tree}\n\
plan docs/plans/p.md {}\nreview reviewed {}\npreview not-required\n\
producer amont-agent 0.0.0\n",
"a".repeat(64),
"c".repeat(64)
)
}
fn canon_by_hand(work: &Path, tree: &str) -> String {
let listing = git(
work,
&[
"-c",
"core.quotePath=true",
"ls-tree",
"-r",
"--full-tree",
tree,
],
);
let mut text = String::new();
for line in listing.lines() {
let (head, path) = line.split_once('\t').unwrap();
let f: Vec<&str> = head.split(' ').collect();
let plan = matches!(f[0], "100644" | "100755")
&& (path.starts_with("docs/plans/") || path.starts_with("\"docs/plans/"));
if plan {
text.push_str(&format!(
"{} {} {}\t{path}\n",
f[0],
f[1],
"0".repeat(f[2].len())
));
} else {
text.push_str(&format!("{line}\n"));
}
}
let mut child = std::process::Command::new("git")
.arg("-C")
.arg(work)
.args(["hash-object", "--stdin"])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()
.unwrap();
child
.stdin
.take()
.unwrap()
.write_all(text.as_bytes())
.unwrap();
let out = child.wait_with_output().unwrap();
String::from_utf8_lossy(&out.stdout).trim().to_string()
}
fn provenance_payload(remote: &Path, object: &str) -> (String, String) {
let note = git(remote, &["notes", "--ref", PROVENANCE_REF, "show", object]);
let (p, sig) = note
.split_once("\n\n")
.expect("payload, blank line, signature");
(format!("{p}\n"), sig.to_string())
}
fn push_of(head: &str) -> PushRef {
PushRef {
local_ref: "refs/heads/feat/x".into(),
local_oid: head.to_string(),
remote_ref: "refs/heads/feat/x".into(),
remote_oid: "0".repeat(40),
}
}
#[test]
fn a_provenance_payload_is_signed_and_published_by_tree_and_commit() {
let (d, work, remote, head, tree, signers) = provenance_world("prov-e2e");
let payloads = d.join("payloads");
std::fs::create_dir_all(&payloads).unwrap();
let file = payloads.join(&head);
let body = record(&head, &tree);
std::fs::write(&file, &body).unwrap();
let gates = ["pre-push-cargo-test".to_string()];
in_repo(&work, || {
attest_push(&test_settings(), "origin", &[push_of(&head)], &gates, &[])
});
let attested = git(&remote, &["notes", "--ref", NOTES_REF, "show", &head]);
in_repo(&work, || {
provenance_push_from(&payloads, "origin", &[push_of(&head)])
});
let canon = canon_by_hand(&work, &tree);
assert_ne!(
canon, tree,
"the tree carries a plan, so canon(T) is not its oid"
);
let signed = body.replacen(
&format!("tree {tree}\n"),
&format!("tree {tree}\ncanon {canon}\n"),
1,
);
for object in [&head, &tree] {
let (p, sig) = provenance_payload(&remote, object);
assert_eq!(p, signed, "the payload, with canon(T) inserted, is signed");
assert_eq!(p.lines().nth(3), Some(format!("canon {canon}").as_str()));
assert!(verify_in(
PROVENANCE_NAMESPACE,
&p,
&sig,
&signers,
"t@t.test"
));
assert!(
!verify_in(NAMESPACE, &p, &sig, &signers, "t@t.test"),
"a provenance signature is never an attestation"
);
}
assert!(!file.exists(), "a published payload is deleted");
assert_eq!(
git(&remote, &["notes", "--ref", NOTES_REF, "show", &head]),
attested,
"the attestation note is byte-identical with a provenance payload present"
);
scratch_cleanup(&d);
scratch_cleanup(&work);
}
#[test]
fn a_green_provenance_payload_is_filed_under_the_green_names_alone() {
let (d, work, remote, head, tree, signers) = provenance_world("prov-green-names");
let payloads = d.join("payloads");
std::fs::create_dir_all(&payloads).unwrap();
let body = record(&head, &tree).replacen(PROVENANCE_FORMAT, "greengate-provenance-v1", 1);
assert!(body.starts_with("greengate-provenance-v1\n"));
std::fs::write(payloads.join(&head), &body).unwrap();
in_repo(&work, || {
provenance_push_from(&payloads, "origin", &[push_of(&head)])
});
assert_eq!(
git(
&remote,
&["for-each-ref", "--format=%(refname)", "refs/notes"]
),
"refs/notes/greengate-provenance"
);
let note = git(
&remote,
&["notes", "--ref", "greengate-provenance", "show", &head],
);
let (p, sig) = note.split_once("\n\n").expect("payload and signature");
let payload = format!("{p}\n");
assert!(payload.starts_with("greengate-provenance-v1\n"));
assert!(verify_in(
"greengate-provenance",
&payload,
sig,
&signers,
"t@t.test"
));
assert!(!verify_in(
"amont-provenance",
&payload,
sig,
&signers,
"t@t.test"
));
scratch_cleanup(&d);
scratch_cleanup(&work);
}
#[test]
fn a_waiting_legacy_provenance_payload_is_kept_named_and_not_signed() {
let (d, work, remote, head, tree, _) = provenance_world("prov-legacy-kept");
let payloads = d.join("payloads");
std::fs::create_dir_all(&payloads).unwrap();
let file = payloads.join(&head);
let body = record(&head, &tree).replacen(PROVENANCE_FORMAT, "amont-provenance-v1", 1);
assert!(body.starts_with("amont-provenance-v1\n"));
std::fs::write(&file, &body).unwrap();
in_repo(&work, || {
provenance_push_from(&payloads, "origin", &[push_of(&head)])
});
let said = legacy_provenance_line(&head, &file);
assert!(file.exists(), "a legacy payload is kept, not consumed");
assert_eq!(std::fs::read_to_string(&file).unwrap(), body);
assert_eq!(
git(
&remote,
&["for-each-ref", "--format=%(refname)", "refs/notes"]
),
"",
"nothing is published for it, under any name"
);
assert_eq!(
git(
&work,
&["for-each-ref", "--format=%(refname)", "refs/notes"]
),
"",
"nor filed locally"
);
let file_name = file.display().to_string();
assert!(said.contains(&file_name), "names the file: {said}");
assert!(
said.contains("written by an older release of the hook"),
"{said}"
);
assert!(said.contains("upgrade greenbelay"), "{said}");
scratch_cleanup(&d);
scratch_cleanup(&work);
}
#[test]
fn an_attestation_push_writes_only_green_refs() {
let (d, work, remote, head, _tree, signers) = provenance_world("attest-green-refs");
let gates = ["pre-push-cargo-test".to_string()];
in_repo(&work, || {
attest_push(&test_settings(), "origin", &[push_of(&head)], &gates, &[])
});
let refs = git(
&remote,
&["for-each-ref", "--format=%(refname)", "refs/notes"],
);
assert!(
refs.lines().any(|r| r == "refs/notes/greengate-attest"),
"{refs}"
);
assert!(
refs.lines().all(|r| r.starts_with("refs/notes/greengate-")),
"an old name was written: {refs}"
);
let note = git(
&remote,
&["notes", "--ref", "greengate-attest", "show", &head],
);
let (p, sig) = note.split_once("\n\n").expect("payload and signature");
let payload = format!("{p}\n");
assert!(payload.starts_with("greengate-attest-v2\n"), "{payload}");
assert!(verify_in(
"greengate-attest",
&payload,
sig,
&signers,
"t@t.test"
));
assert!(!verify_in(
"amont-attest",
&payload,
sig,
&signers,
"t@t.test"
));
scratch_cleanup(&d);
scratch_cleanup(&work);
}
#[test]
fn the_default_key_is_the_green_name_with_the_old_one_as_fallback() {
let home = dir("key-default");
std::fs::create_dir_all(home.join(".ssh")).unwrap();
assert_eq!(default_key_in(&home), home.join(".ssh/greengate-attest"));
assert_eq!(key_move_hint_in(&home), None);
std::fs::write(home.join(".ssh/amont-attest"), "k").unwrap();
assert_eq!(default_key_in(&home), home.join(".ssh/amont-attest"));
let hint = key_move_hint_in(&home).expect("a doctor line");
assert!(
hint.contains("mv ~/.ssh/amont-attest ~/.ssh/greengate-attest"),
"{hint}"
);
assert_eq!(hint.lines().count(), 1);
std::fs::write(home.join(".ssh/greengate-attest"), "k").unwrap();
assert_eq!(default_key_in(&home), home.join(".ssh/greengate-attest"));
assert_eq!(key_move_hint_in(&home), None);
scratch_cleanup(&home);
}
#[test]
fn a_payload_for_another_tree_is_neither_signed_nor_deleted() {
let (d, work, remote, head, _tree, _) = provenance_world("prov-mismatch");
let payloads = d.join("payloads");
std::fs::create_dir_all(&payloads).unwrap();
let file = payloads.join(&head);
std::fs::write(&file, record(&head, &"b".repeat(40))).unwrap();
in_repo(&work, || {
provenance_push_from(&payloads, "origin", &[push_of(&head)])
});
assert!(file.exists(), "a mismatched payload is kept");
let refs = git(&remote, &["for-each-ref", PROVENANCE_FULL_REF]);
assert!(refs.is_empty(), "nothing was published: {refs}");
scratch_cleanup(&d);
scratch_cleanup(&work);
}
#[test]
fn a_payload_with_a_canon_line_is_refused_and_kept() {
let (d, work, remote, head, tree, _) = provenance_world("prov-canon");
let payloads = d.join("payloads");
std::fs::create_dir_all(&payloads).unwrap();
let file = payloads.join(&head);
let old = record(&head, &tree).replacen(
&format!("tree {tree}\n"),
&format!("tree {tree}\ncanon {}\n", "c".repeat(64)),
1,
);
std::fs::write(&file, &old).unwrap();
in_repo(&work, || {
provenance_push_from(&payloads, "origin", &[push_of(&head)])
});
assert_eq!(
std::fs::read_to_string(&file).unwrap(),
old,
"kept as it was"
);
let refs = git(&remote, &["for-each-ref", PROVENANCE_FULL_REF]);
assert!(refs.is_empty(), "nothing was published: {refs}");
scratch_cleanup(&d);
scratch_cleanup(&work);
}
#[test]
fn the_canon_refusal_fits_in_80_columns() {
for commit in [
"9f1c2ab0d6e4c1b2a3f405e6d7c8b9a0f1e2d3c4".to_string(),
"e".repeat(64),
] {
let file = PathBuf::from("/Users/someone/.claude/greenbelay/provenance/greengate")
.join(&commit);
let lines = canon_refusal(&commit, &file);
assert!(lines[0].starts_with(" provenance for "), "{lines:?}");
assert!(lines[0].contains(&commit[..7]), "{lines:?}");
let all = lines.join("\n");
assert!(all.contains("canon line") && all.contains("pre-release build of the hook"));
assert!(all.contains(&format!(" {commit} in\n")), "{all}");
assert!(all.contains("upgrade greenbelay"), "{all}");
for l in &lines {
assert!(
l.chars().count() <= 80,
"{} columns: {l}",
l.chars().count()
);
}
}
}
#[test]
fn a_failed_canon_keeps_the_payload() {
let (d, work, remote, head, tree, _) = provenance_world("prov-nocanon");
let docs = git(&work, &["rev-parse", &format!("{tree}:docs")]);
let objects = PathBuf::from(git(&work, &["rev-parse", "--git-path", "objects"]));
let objects = if objects.is_absolute() {
objects
} else {
work.join(objects)
};
std::fs::remove_file(objects.join(&docs[..2]).join(&docs[2..])).unwrap();
let payloads = d.join("payloads");
std::fs::create_dir_all(&payloads).unwrap();
let file = payloads.join(&head);
std::fs::write(&file, record(&head, &tree)).unwrap();
in_repo(&work, || {
assert_eq!(canon(&tree), None);
provenance_push_from(&payloads, "origin", &[push_of(&head)])
});
assert!(file.exists(), "a payload without a canon is kept");
let refs = git(&remote, &["for-each-ref", PROVENANCE_FULL_REF]);
assert!(refs.is_empty(), "nothing was published: {refs}");
scratch_cleanup(&d);
scratch_cleanup(&work);
}
#[test]
fn a_sha256_repository_signs_a_64_hex_canon() {
let (d, work, remote, head, tree, _) = provenance_world_in("prov-sha256", Some("sha256"));
assert_eq!(tree.len(), 64);
let payloads = d.join("payloads");
std::fs::create_dir_all(&payloads).unwrap();
std::fs::write(payloads.join(&head), record(&head, &tree)).unwrap();
in_repo(&work, || {
provenance_push_from(&payloads, "origin", &[push_of(&head)])
});
let (p, _) = provenance_payload(&remote, &head);
let canon = canon_by_hand(&work, &tree);
assert_eq!(canon.len(), 64);
assert_eq!(
p.lines().nth(3),
Some(format!("canon {canon}").as_str()),
"{p}"
);
scratch_cleanup(&d);
scratch_cleanup(&work);
}
#[test]
fn a_failed_publish_keeps_the_payload_for_the_next_push() {
let (d, work, _remote, head, tree, _) = provenance_world("prov-fail");
git(
&work,
&[
"remote",
"set-url",
"origin",
d.join("gone.git").to_str().unwrap(),
],
);
let payloads = d.join("payloads");
std::fs::create_dir_all(&payloads).unwrap();
let file = payloads.join(&head);
std::fs::write(&file, record(&head, &tree)).unwrap();
in_repo(&work, || {
provenance_push_from(&payloads, "origin", &[push_of(&head)])
});
assert!(file.exists(), "an unpublished payload is kept");
scratch_cleanup(&d);
scratch_cleanup(&work);
}
#[test]
fn a_config_key_cannot_point_amont_at_other_payloads() {
let (d, work, remote, head, tree, _) = provenance_world("prov-config");
let elsewhere = d.join("elsewhere");
let name = work.file_name().unwrap().to_string_lossy().into_owned();
std::fs::create_dir_all(elsewhere.join(&name)).unwrap();
std::fs::write(elsewhere.join(&name).join(&head), record(&head, &tree)).unwrap();
for key in ["greengate.provenanceDir", "amont.agent.provenanceDir"] {
git(&work, &["config", key, elsewhere.to_str().unwrap()]);
}
in_repo(&work, || {
provenance_push(&test_settings(), "origin", &[push_of(&head)])
});
let refs = git(&remote, &["for-each-ref", PROVENANCE_FULL_REF]);
assert!(refs.is_empty(), "a configured directory was read: {refs}");
scratch_cleanup(&d);
scratch_cleanup(&work);
}
#[test]
fn no_payload_publishes_nothing() {
let (d, work, remote, head, _, _) = provenance_world("prov-none");
let payloads = d.join("payloads");
std::fs::create_dir_all(&payloads).unwrap();
in_repo(&work, || {
provenance_push_from(&payloads, "origin", &[push_of(&head)])
});
let refs = git(&remote, &["for-each-ref", PROVENANCE_FULL_REF]);
assert!(refs.is_empty(), "{refs}");
scratch_cleanup(&d);
scratch_cleanup(&work);
}
#[test]
fn a_missing_key_signs_nothing() {
assert!(sign("anything", Path::new("/nonexistent/key")).is_none());
}
#[test]
fn an_enabled_push_leaves_a_verifiable_note_on_the_remote() {
let d = dir("e2e");
let (key, signers) = keypair(&d);
let remote = d.join("remote.git");
std::fs::create_dir_all(&remote).unwrap();
git(&remote, &["init", "-q", "--bare", "--template=", "."]);
let work = repo("e2e-work");
git(
&work,
&["remote", "add", "origin", remote.to_str().unwrap()],
);
git(&work, &["config", "greengate.attest", "true"]);
git(
&work,
&["config", "greengate.attestKey", key.to_str().unwrap()],
);
std::fs::write(work.join("a.ts"), "x").unwrap();
git(&work, &["add", "a.ts"]);
git(&work, &["commit", "-qm", "chore: a"]);
let head = git(&work, &["rev-parse", "HEAD"]);
let tree = git(&work, &["rev-parse", "HEAD^{tree}"]);
let push_ref = PushRef {
local_ref: "refs/heads/main".into(),
local_oid: head.clone(),
remote_ref: "refs/heads/main".into(),
remote_oid: "0".repeat(40),
};
in_repo(&work, || {
attest_push(
&test_settings(),
"origin",
&[push_ref],
&["pre-push-run-tests-js".into()],
&[],
);
});
let body = git(&remote, &["notes", "--ref", NOTES_REF, "show", &head]);
assert!(!body.is_empty(), "no note reached the remote");
let (p, sig) = body
.split_once("\n\n")
.expect("payload, blank line, signature");
let p = format!("{p}\n"); assert!(p.starts_with(FORMAT));
assert!(
p.contains(&format!("tree {tree}")),
"attests the pushed tree"
);
assert!(
verify(&p, sig, &signers, "t@t.test"),
"the remote copy verifies"
);
scratch_cleanup(&d);
scratch_cleanup(&work);
}
#[test]
fn a_push_with_a_spec_publishes_the_inputs_ref() {
let (_d, work, remote, _) = remote_and_work("inputs");
std::fs::create_dir_all(work.join(".github")).unwrap();
std::fs::write(
work.join(".github/attest-inputs"),
"pre-push-run-tests-js a.ts\n",
)
.unwrap();
git(&work, &["add", ".github/attest-inputs"]);
git(&work, &["commit", "-qm", "chore: spec"]);
in_repo(&work, || {
attest_push(
&test_settings(),
"origin",
&[push_ref_for(&work)],
&["pre-push-run-tests-js".into()],
&[],
);
});
let listed = git(&remote, &["notes", "--ref", INPUTS_REF, "list"]);
assert!(
!listed.trim().is_empty(),
"the inputs ref reached the remote"
);
}
#[test]
fn no_opt_in_means_no_note() {
let d = dir("optout");
let (key, _) = keypair(&d);
let remote = d.join("remote.git");
std::fs::create_dir_all(&remote).unwrap();
git(&remote, &["init", "-q", "--bare", "--template=", "."]);
let work = repo("optout-work");
git(
&work,
&["remote", "add", "origin", remote.to_str().unwrap()],
);
git(
&work,
&["config", "greengate.attestKey", key.to_str().unwrap()],
);
std::fs::write(work.join("a.ts"), "x").unwrap();
git(&work, &["add", "a.ts"]);
git(&work, &["commit", "-qm", "chore: a"]);
let head = git(&work, &["rev-parse", "HEAD"]);
let push_ref = PushRef {
local_ref: "refs/heads/main".into(),
local_oid: head.clone(),
remote_ref: "refs/heads/main".into(),
remote_oid: "0".repeat(40),
};
in_repo(&work, || {
attest_push(
&test_settings(),
"origin",
&[push_ref],
&["pre-push-run-tests-js".into()],
&[],
);
});
assert!(
git(&remote, &["notes", "--ref", NOTES_REF, "list"]).is_empty(),
"an un-opted-in repo attested something"
);
scratch_cleanup(&d);
scratch_cleanup(&work);
}
#[test]
fn deletions_and_empty_gates_attest_nothing() {
let d = dir("nothing");
let (key, _) = keypair(&d);
let remote = d.join("remote.git");
std::fs::create_dir_all(&remote).unwrap();
git(&remote, &["init", "-q", "--bare", "--template=", "."]);
let work = repo("nothing-work");
git(
&work,
&["remote", "add", "origin", remote.to_str().unwrap()],
);
git(&work, &["config", "greengate.attest", "true"]);
git(
&work,
&["config", "greengate.attestKey", key.to_str().unwrap()],
);
std::fs::write(work.join("a.ts"), "x").unwrap();
git(&work, &["add", "a.ts"]);
git(&work, &["commit", "-qm", "chore: a"]);
let head = git(&work, &["rev-parse", "HEAD"]);
let deletion = PushRef {
local_ref: "(delete)".into(),
local_oid: "0".repeat(40),
remote_ref: "refs/heads/gone".into(),
remote_oid: head.clone(),
};
let real = PushRef {
local_ref: "refs/heads/main".into(),
local_oid: head,
remote_ref: "refs/heads/main".into(),
remote_oid: "0".repeat(40),
};
in_repo(&work, || {
attest_push(
&test_settings(),
"origin",
&[deletion],
&["pre-push-pytest".into()],
&[],
);
attest_push(&test_settings(), "origin", &[real], &[], &[]);
});
assert!(git(&remote, &["notes", "--ref", NOTES_REF, "list"]).is_empty());
scratch_cleanup(&d);
scratch_cleanup(&work);
}
#[test]
fn a_rejection_is_a_note_whose_signature_did_not_verify() {
let trail: Vec<String> = [
"note on abc123: signature did not verify for principal t@t.test",
"note on abc123 block 2: no principal matched",
"note on def456 carries no signature block",
"attested tree abc is not the checked-out tree def and neither its canonical tree nor an input fingerprint of abc123 matches",
"no attestation found for tree abc",
]
.iter()
.map(|s| s.to_string())
.collect();
assert_eq!(
signature_rejections(&trail),
vec![
"note on abc123: signature did not verify for principal t@t.test".to_string(),
"note on abc123 block 2: no principal matched".to_string(),
]
);
}
#[test]
fn covered_answers_in_a_fresh_clone_and_rejects_drift_and_forgery() {
let d = dir("covered");
let (key, signers) = keypair(&d);
let remote = d.join("remote.git");
std::fs::create_dir_all(&remote).unwrap();
git(&remote, &["init", "-q", "--bare", "--template=", "."]);
git(&remote, &["symbolic-ref", "HEAD", "refs/heads/main"]);
let work = repo("covered-work");
git(
&work,
&["remote", "add", "origin", remote.to_str().unwrap()],
);
git(&work, &["config", "greengate.attest", "true"]);
git(
&work,
&["config", "greengate.attestKey", key.to_str().unwrap()],
);
std::fs::write(work.join("a.ts"), "x").unwrap();
git(&work, &["add", "a.ts"]);
git(&work, &["commit", "-qm", "chore: a"]);
git(&work, &["push", "-q", "origin", "HEAD:main"]);
let head = git(&work, &["rev-parse", "HEAD"]);
let push_ref = PushRef {
local_ref: "refs/heads/main".into(),
local_oid: head.clone(),
remote_ref: "refs/heads/main".into(),
remote_oid: "0".repeat(40),
};
in_repo(&work, || {
attest_push(
&test_settings(),
"origin",
&[push_ref],
&["pre-push-pytest".into()],
&[],
);
});
let clone = d.join("ci-checkout");
git(
&d,
&[
"clone",
"-q",
"--template=",
remote.to_str().unwrap(),
clone.to_str().unwrap(),
],
);
in_repo(&clone, || {
assert_eq!(
covered(&signers, Some("t@t.test"), Some(&platform()), &[]).as_deref(),
Some("pre-push-pytest"),
"a fresh clone verifies the attestation and reads the gates"
);
assert_eq!(
covered(&signers, Some("t@t.test"), None, &[]).as_deref(),
Some("pre-push-pytest"),
"`any` covers a platform-independent suite"
);
assert_eq!(
covered(&signers, Some("t@t.test"), Some("s390x-aix"), &[]),
None,
"a pass on one platform is not evidence about another"
);
assert_eq!(
covered(&signers, Some("someone@else.test"), None, &[]),
None,
"an unlisted principal covers nothing"
);
});
std::fs::write(clone.join("b.ts"), "y").unwrap();
git(&clone, &["config", "user.email", "t@t.test"]);
git(&clone, &["config", "user.name", "t"]);
git(&clone, &["add", "b.ts"]);
git(&clone, &["commit", "-qm", "chore: b"]);
in_repo(&clone, || {
assert_eq!(
covered(&signers, Some("t@t.test"), None, &[]),
None,
"drifted tree"
);
});
let head_tree = git(&work, &["rev-parse", "HEAD^{tree}"]);
for object in [&head, &head_tree] {
git(
&work,
&[
"notes", "--ref", NOTES_REF, "add", "-f", "-m", "garbage", object,
],
);
}
git(
&work,
&[
"push",
"-q",
"origin",
&format!("+{NOTES_FULL_REF}:{NOTES_FULL_REF}"),
],
);
git(
&work,
&["push", "-q", "origin", &format!(":{INPUTS_FULL_REF}")],
);
git(&clone, &["reset", "-q", "--hard", &head]);
in_repo(&clone, || {
assert_eq!(
covered(&signers, Some("t@t.test"), None, &[]),
None,
"a foreign note is not a stamp"
);
});
scratch_cleanup(&d);
scratch_cleanup(&work);
}
#[test]
fn default_signers_is_found_from_a_subdirectory() {
let work = repo("signers-subdir");
std::fs::create_dir_all(work.join(".forgejo")).unwrap();
std::fs::write(work.join(".forgejo/allowed_signers"), "t@t.test x\n").unwrap();
let sub = work.join("packages").join("thing");
std::fs::create_dir_all(&sub).unwrap();
in_repo(&sub, || {
let found = default_signers().expect("resolved from the repo root, not the cwd");
assert!(found.ends_with(".forgejo/allowed_signers"));
assert!(found.exists(), "the path it returns must be usable as-is");
});
scratch_cleanup(&work);
}
#[test]
fn zero_oids_of_any_width_are_zero() {
assert!(is_zero(&"0".repeat(40)));
assert!(is_zero(&"0".repeat(64)));
assert!(!is_zero("0a0000"));
assert!(!is_zero(""));
}
#[test]
fn forget_removes_the_local_ref() {
let work = repo("forget");
std::fs::write(work.join("a.ts"), "x").unwrap();
git(&work, &["add", "a.ts"]);
git(&work, &["commit", "-qm", "chore: a"]);
git(
&work,
&["notes", "--ref", NOTES_REF, "add", "-m", "x", "HEAD"],
);
in_repo(&work, forget);
assert!(git(&work, &["notes", "--ref", NOTES_REF, "list"]).is_empty());
scratch_cleanup(&work);
}
pub(crate) fn both_names_signer(dir: &Path) -> (PathBuf, PathBuf) {
let key = dir.join("signer_key");
let ok = std::process::Command::new("ssh-keygen")
.args(["-q", "-t", "ed25519", "-N", "", "-C", "test", "-f"])
.arg(&key)
.status()
.expect("ssh-keygen must exist for these tests")
.success();
assert!(ok, "keygen failed");
let pubkey = std::fs::read_to_string(key.with_extension("pub")).unwrap();
let signers = dir.join("allowed_signers");
std::fs::write(
&signers,
format!(
"cluster-signer@{} namespaces=\"{},{}\" {pubkey}",
crate::cluster::PLATFORM,
git_attest::format::LEGACY.namespace,
git_attest::format::GREEN.namespace
),
)
.unwrap();
(key, signers)
}
pub(crate) fn block_with(header: &str, namespace: &str, tree: &str, key: &Path) -> String {
let payload = format!(
"{header}\ntree {tree}\ngates suite\nplatform {}\ngreengate 0.0.0\n",
crate::cluster::PLATFORM
);
let sig = git_attest::sign::sign(namespace, &payload, key).expect("sign");
block(&payload, &sig)
}
#[test]
fn a_signer_block_is_checked_under_the_namespace_its_header_names() {
use git_attest::format::{GREEN, LEGACY};
let scratch = dir("signer-names");
let (key, signers) = both_names_signer(&scratch);
let tree = "0123456789012345678901234567890123456789";
for set in [GREEN, LEGACY] {
let body = block_with(set.format, set.namespace, tree, &key);
let checked = signer_block(&body, tree, &signers)
.unwrap_or_else(|e| panic!("{}: {}", set.format, e.reason()));
assert_eq!(checked.names, set);
assert_eq!(checked.gates, ["suite"]);
}
for (header, signed_under) in [(LEGACY, GREEN), (GREEN, LEGACY)] {
let body = block_with(header.format, signed_under.namespace, tree, &key);
assert!(
matches!(
signer_block(&body, tree, &signers),
Err(BlockRefusal::Signer(_))
),
"a {} block signed under {} must be refused",
header.format,
signed_under.namespace
);
}
scratch_cleanup(&scratch);
}
#[test]
fn forget_in_removes_the_notes_ref_of_both_name_sets() {
let repo_dir = repo("forget-both");
git(&repo_dir, &["commit", "-q", "--allow-empty", "-m", "c"]);
for names in READ_NAMES {
git(
&repo_dir,
&["notes", "--ref", names.notes_ref, "add", "-m", "x", "HEAD"],
);
}
assert!(forget_in(&repo_dir));
for names in READ_NAMES {
let full = format!("refs/notes/{}", names.notes_ref);
let out = std::process::Command::new("git")
.arg("-C")
.arg(&repo_dir)
.args(["rev-parse", "--verify", "-q", &full])
.output()
.unwrap();
assert!(!out.status.success(), "{full} survived forget_in");
}
scratch_cleanup(&repo_dir);
}
#[test]
fn filed_signer_blocks_drops_a_block_of_the_other_name_set() {
use git_attest::format::{GREEN, LEGACY};
let work = repo("filed-names");
std::fs::write(work.join("a.txt"), "x").unwrap();
git(&work, &["add", "a.txt"]);
git(&work, &["commit", "-qm", "chore: a"]);
let (key, signers) = both_names_signer(&work);
std::fs::create_dir_all(work.join(".forgejo")).unwrap();
std::fs::copy(&signers, work.join(".forgejo/allowed_signers")).unwrap();
let tree = git(&work, &["rev-parse", "HEAD^{tree}"]);
let green = block_with(GREEN.format, GREEN.namespace, &tree, &key);
let legacy = block_with(LEGACY.format, LEGACY.namespace, &tree, &key);
in_repo(&work, || {
file_signer_block(&legacy, &[&tree]).expect("file the legacy block");
assert!(
filed_signer_blocks(&tree).is_empty(),
"a legacy block is not publishable while WRITE is green"
);
file_signer_block(&format!("{legacy}\n{green}"), &[&tree]).expect("file both");
let kept = filed_signer_blocks(&tree);
assert_eq!(kept.len(), 1, "{kept:?}");
assert_eq!(kept[0].names, git_attest::format::WRITE);
assert_eq!(kept[0].names, GREEN);
assert!(kept[0].is_publishable());
});
scratch_cleanup(&work);
}
#[test]
fn a_verification_says_which_name_it_went_through() {
let mut verdict = git_attest::verify::Verdict::nothing("test");
assert!(verified_lines(&verdict).is_empty());
verdict.verified_under = vec![
git_attest::format::GREEN.namespace.to_string(),
git_attest::format::LEGACY.namespace.to_string(),
];
assert_eq!(
verified_lines(&verdict),
[
format!("verified under {}", git_attest::format::GREEN.namespace),
format!("verified under {}", git_attest::format::LEGACY.namespace),
]
);
}
}