//! Execution receipts (spec §14.6): list, show, verify and import the //! signed receipts runners make. use super::json; use super::open; use super::ui; use anyhow::{bail, Result}; use oxy_core::receipt::SignedReceipt; use oxy_core::repo::ReceiptInfo; fn status(problem: Option<&str>, revoked: bool) -> String { match (problem, revoked) { (Some(p), _) => ui::err(format!("{} {p}", ui::glyph("✘", "x"))), (None, true) => ui::warn(format!("{} runner key revoked", ui::glyph("!", "!"))), (None, false) => ui::ok(format!("{} signed", ui::glyph("✔", "v"))), } } fn line(sr: &SignedReceipt, problem: Option<&str>, revoked: bool) -> String { let r = &sr.receipt; let result = if r.passed() { ui::ok(format!("{} passed", ui::glyph("●", "*"))) } else { ui::err(format!("{} exit {}", ui::glyph("●", "*"), r.exit_code)) }; format!( "{} {}{}{}{}{}", result, ui::subject(&r.job_name), ui::sep() + &ui::dim(format!("{:.1} s", r.duration_ms as f64 / 1000.0)), ui::sep() + &ui::author(&sr.runner.name), ui::sep() + &status(problem, revoked), ui::sep() + &ui::dim(ui::ago(sr.attest.hlc.wall_ms)), ) } fn to_json( attest: Option, sr: &SignedReceipt, problem: Option<&str>, revoked: bool, ) -> String { let r = &sr.receipt; let refs = |v: &[oxy_core::hash::ObjectRef]| json::arr(v.iter().map(|h| json::s(&h.to_hex()))); json::obj([ ("attest", json::opt(attest.as_ref(), |a| json::s(a))), ("receipt", json::s(&r.hash().to_hex())), ("state", json::s(&sr.state().to_hex())), ("run", json::s(sr.run())), ("job", json::s(&r.job_name)), ("exit_code", json::n(r.exit_code)), ("duration_ms", json::n(r.duration_ms)), ("pipeline", json::s(&r.pipeline_hash.to_hex())), ("scope", json::s(&r.scope_tree_hash.to_hex())), ("environment", json::s(&r.environment.to_hex())), ("inputs", refs(&r.inputs)), ("outputs", refs(&r.outputs)), ("runner", json::s(&sr.runner.hash().to_hex())), ("runner_name", json::s(&sr.runner.name)), ("made_ms", json::n(sr.attest.hlc.wall_ms)), ("valid", json::b(problem.is_none())), ("problem", json::opt(problem, json::s)), ("revoked", json::b(revoked)), ]) } fn detail(sr: &SignedReceipt, problem: Option<&str>, revoked: bool) { let r = &sr.receipt; println!("{}", line(sr, problem, revoked)); println!( "{}", ui::kv("run", if sr.run().is_empty() { "-" } else { sr.run() }) ); println!( "{}", ui::kv("state", ui::hash(format!("#{}", sr.state().short(12)))) ); println!( "{}", ui::kv("receipt", ui::hash(format!("#{}", r.hash().short(12)))) ); println!( "{}", ui::kv("pipeline", ui::hash(r.pipeline_hash.short(12))) ); println!("{}", ui::kv("scope", ui::hash(r.scope_tree_hash.short(12)))); println!( "{}", ui::kv("environment", ui::hash(r.environment.short(12))) ); println!( "{}", ui::kv( "runner", format!("{} {}", sr.runner.name, ui::dim(sr.runner.hash().short(12))) ) ); for (what, v) in [("input", &r.inputs), ("output", &r.outputs)] { for h in v.iter() { println!("{}", ui::kv(what, ui::hash(h.short(12)))); } } } /// `oxy receipt list [REV]`: the receipts kept for a state. pub fn list(rev: Option<&str>, as_json: bool) -> Result { let repo = open()?; let heads = match rev { Some(r) => repo.resolve_heads(r)?, None => repo.bookmark_heads()?, }; let found = repo.receipts(&heads)?; if as_json { println!( "{}", json::arr(found.iter().map(|i| to_json( Some(i.attest.to_hex()), &i.signed, i.problem.as_deref(), i.revoked ))) ); return Ok(0); } if found.is_empty() { println!("{}", ui::dim("No receipts for this state.")); } for i in &found { println!( "{} {}", ui::hash(format!("#{}", i.attest.short(12))), line(&i.signed, i.problem.as_deref(), i.revoked) ); } Ok(0) } fn find(repo: &oxy_core::repo::Repo, prefix: &str, rev: Option<&str>) -> Result { let heads = match rev { Some(r) => repo.resolve_heads(r)?, None => repo.bookmark_heads()?, }; let p = prefix.trim_start_matches('#').to_ascii_lowercase(); let mut hits: Vec = repo .receipts(&heads)? .into_iter() .filter(|i| i.attest.to_hex().starts_with(&p)) .collect(); match hits.len() { 1 => Ok(hits.remove(0)), 0 => bail!("no receipt #{p} for this state; `oxy receipt list` shows them"), n => bail!("#{p} matches {n} receipts; give more of the hash"), } } /// `oxy receipt show HASH [--rev REV]`. pub fn show(prefix: &str, rev: Option<&str>, as_json: bool) -> Result { let repo = open()?; let i = find(&repo, prefix, rev)?; if as_json { println!( "{}", to_json( Some(i.attest.to_hex()), &i.signed, i.problem.as_deref(), i.revoked ) ); } else { detail(&i.signed, i.problem.as_deref(), i.revoked); } Ok(if i.problem.is_some() { 1 } else { 0 }) } /// `oxy receipt export HASH FILE [--format slsa]`: the signed receipt, to /// hand to anyone, or SLSA provenance of it for tools outside Oxygen. pub fn export(prefix: &str, file: &str, rev: Option<&str>, format: &str) -> Result { let repo = open()?; let i = find(&repo, prefix, rev)?; if format == "slsa" { return export_slsa(&repo, &i, file); } std::fs::write(file, i.signed.encode())?; println!( "{} {} {}", ui::done("Exported receipt"), ui::hash(format!("#{}", i.attest.short(12))), ui::path(file) ); Ok(0) } /// What SLSA calls the build type of a Flow job. pub const BUILD_TYPE: &str = "https://oxygenhub.io/oxygenflow/job/v1"; /// The in-toto Statement v1, with an SLSA provenance v1 predicate, of what /// a receipt says (spec §14.6). Its subjects are the job's outputs (the /// state it ran on when it made none), named by their Oxygen object hashes; /// the signed receipt itself rides along as a byproduct, so an Oxygen /// verifier can still check the runner's own signature. pub fn statement(sr: &SignedReceipt) -> serde_json::Value { use serde_json::json; let r = &sr.receipt; let subject: Vec<_> = if r.outputs.is_empty() { vec![json!({ "name": "state", "digest": { "oxygen-state": sr.state().to_hex() } })] } else { r.outputs .iter() .map(|o| json!({ "name": o.to_hex(), "digest": { "oxygen-blob": o.to_hex() } })) .collect() }; let rfc3339 = |ms: u64| super::format::when(ms).replacen(' ', "T", 1); let made = sr.attest.hlc.wall_ms; let mut deps = vec![ json!({ "name": "state", "digest": { "oxygen-state": sr.state().to_hex() } }), json!({ "name": "scope", "digest": { "oxygen-scope": r.scope_tree_hash.to_hex() } }), ]; deps.extend( r.inputs .iter() .map(|h| json!({ "name": h.to_hex(), "digest": { "oxygen-blob": h.to_hex() } })), ); json!({ "_type": "https://in-toto.io/Statement/v1", "subject": subject, "predicateType": "https://slsa.dev/provenance/v1", "predicate": { "buildDefinition": { "buildType": BUILD_TYPE, "externalParameters": { "job": r.job_name, "pipeline": r.pipeline_hash.to_hex(), }, "internalParameters": { "environment": r.environment.to_hex(), }, "resolvedDependencies": deps, }, "runDetails": { "builder": { "id": format!("urn:oxygen:runner:{}", sr.runner.hash().to_hex()), "version": { "name": sr.runner.name }, }, "metadata": { "invocationId": sr.run(), "startedOn": rfc3339(made.saturating_sub(r.duration_ms)), "finishedOn": rfc3339(made), }, "byproducts": [{ "name": "oxygen-receipt", "mediaType": "application/vnd.oxygen.receipt+cbor", "content": oxy_core::dsse::base64(&sr.encode()), "annotations": { "exitCode": r.exit_code, "durationMs": r.duration_ms, "runner": sr.runner.name, }, }], }, }, }) } fn export_slsa(repo: &oxy_core::repo::Repo, i: &ReceiptInfo, file: &str) -> Result { if let Some(p) = &i.problem { bail!( "receipt #{} does not verify ({p}); provenance is only made of a valid one", i.attest.short(12) ); } let Some((key, sk)) = repo.secret_key()? else { bail!("SLSA provenance is signed with your key, and none is set up here; run `oxy identity create`"); }; let payload = serde_json::to_vec(&statement(&i.signed))?; std::fs::write( file, oxy_core::dsse::envelope(oxy_core::dsse::IN_TOTO, &payload, &key.to_hex(), &sk), )?; println!( "{} {} {} {}", ui::done("Exported SLSA provenance of receipt"), ui::hash(format!("#{}", i.attest.short(12))), ui::path(file), ui::dim(format!("signed by {}", key.short(12))) ); println!( "{}", ui::dim(format!( " check it: oxy identity export --pem key.pem, then cosign verify-blob-attestation --key key.pem --type slsaprovenance1 --check-claims=false --signature {file}" )) ); Ok(0) } fn read(file: &str) -> Result { let bytes = std::fs::read(file).map_err(|e| anyhow::anyhow!("{file}: {e}"))?; SignedReceipt::decode(&bytes).map_err(|e| anyhow::anyhow!("{file}: not a signed receipt: {e}")) } /// `oxy receipt verify FILE`: check a signed receipt without keeping it. pub fn verify(file: &str, as_json: bool) -> Result { let sr = read(file)?; let problem = sr.verify().err().map(|e| e.to_string()); if as_json { println!("{}", to_json(None, &sr, problem.as_deref(), false)); } else { detail(&sr, problem.as_deref(), false); } Ok(if problem.is_some() { 1 } else { 0 }) } /// `oxy receipt import FILE`: verify a signed receipt and keep it. pub fn import(file: &str) -> Result { let repo = open()?; let sr = read(file)?; let r = repo.add_receipt(&sr)?; println!( "{} {} {} {} {}", ui::done("Kept receipt"), ui::hash(format!("#{}", r.short(12))), ui::subject(&sr.receipt.job_name), ui::dim("by"), ui::author(&sr.runner.name) ); Ok(0) }