OXYGENHUB

Coverage / src/cli/receipt.rs 85.8%

212 of 247 lines run, 19 of 48 functions · run #358 on main · run missed

1
//! Execution receipts (spec §14.6): list, show, verify and import the
2
//! signed receipts runners make.
3
4
use super::json;
5
use super::open;
6
use super::ui;
7
use anyhow::{bail, Result};
8
use oxy_core::receipt::SignedReceipt;
9
use oxy_core::repo::ReceiptInfo;
10
111×
fn status(problem: Option<&str>, revoked: bool) -> String {
121×
    match (problem, revoked) {
131×
        (Some(p), _) => ui::err(format!("{} {p}", ui::glyph("✘", "x"))),
140×
        (None, true) => ui::warn(format!("{} runner key revoked", ui::glyph("!", "!"))),
150×
        (None, false) => ui::ok(format!("{} signed", ui::glyph("✔", "v"))),
16
    }
171×
}
18
191×
fn line(sr: &SignedReceipt, problem: Option<&str>, revoked: bool) -> String {
201×
    let r = &sr.receipt;
211×
    let result = if r.passed() {
220×
        ui::ok(format!("{} passed", ui::glyph("●", "*")))
23
    } else {
241×
        ui::err(format!("{} exit {}", ui::glyph("●", "*"), r.exit_code))
25
    };
261×
    format!(
27
        "{} {}{}{}{}{}",
28
        result,
291×
        ui::subject(&r.job_name),
301×
        ui::sep() + &ui::dim(format!("{:.1} s", r.duration_ms as f64 / 1000.0)),
311×
        ui::sep() + &ui::author(&sr.runner.name),
321×
        ui::sep() + &status(problem, revoked),
331×
        ui::sep() + &ui::dim(ui::ago(sr.attest.hlc.wall_ms)),
34
    )
351×
}
36
373×
fn to_json(
383×
    attest: Option<String>,
393×
    sr: &SignedReceipt,
403×
    problem: Option<&str>,
413×
    revoked: bool,
423×
) -> String {
433×
    let r = &sr.receipt;
446×
    let refs = |v: &[oxy_core::hash::ObjectRef]| json::arr(v.iter().map(|h| json::s(&h.to_hex())));
453×
    json::obj([
463×
        ("attest", json::opt(attest.as_ref(), |a| json::s(a))),
473×
        ("receipt", json::s(&r.hash().to_hex())),
483×
        ("state", json::s(&sr.state().to_hex())),
493×
        ("run", json::s(sr.run())),
503×
        ("job", json::s(&r.job_name)),
513×
        ("exit_code", json::n(r.exit_code)),
523×
        ("duration_ms", json::n(r.duration_ms)),
533×
        ("pipeline", json::s(&r.pipeline_hash.to_hex())),
543×
        ("scope", json::s(&r.scope_tree_hash.to_hex())),
553×
        ("environment", json::s(&r.environment.to_hex())),
563×
        ("inputs", refs(&r.inputs)),
573×
        ("outputs", refs(&r.outputs)),
583×
        ("runner", json::s(&sr.runner.hash().to_hex())),
593×
        ("runner_name", json::s(&sr.runner.name)),
603×
        ("made_ms", json::n(sr.attest.hlc.wall_ms)),
613×
        ("valid", json::b(problem.is_none())),
623×
        ("problem", json::opt(problem, json::s)),
633×
        ("revoked", json::b(revoked)),
64
    ])
653×
}
66
671×
fn detail(sr: &SignedReceipt, problem: Option<&str>, revoked: bool) {
681×
    let r = &sr.receipt;
691×
    println!("{}", line(sr, problem, revoked));
701×
    println!(
71
        "{}",
721×
        ui::kv("run", if sr.run().is_empty() { "-" } else { sr.run() })
73
    );
741×
    println!(
75
        "{}",
761×
        ui::kv("state", ui::hash(format!("#{}", sr.state().short(12))))
77
    );
781×
    println!(
79
        "{}",
801×
        ui::kv("receipt", ui::hash(format!("#{}", r.hash().short(12))))
81
    );
821×
    println!(
83
        "{}",
841×
        ui::kv("pipeline", ui::hash(r.pipeline_hash.short(12)))
85
    );
861×
    println!("{}", ui::kv("scope", ui::hash(r.scope_tree_hash.short(12))));
871×
    println!(
88
        "{}",
891×
        ui::kv("environment", ui::hash(r.environment.short(12)))
90
    );
911×
    println!(
92
        "{}",
931×
        ui::kv(
941×
            "runner",
951×
            format!("{} {}", sr.runner.name, ui::dim(sr.runner.hash().short(12)))
96
        )
97
    );
982×
    for (what, v) in [("input", &r.inputs), ("output", &r.outputs)] {
992×
        for h in v.iter() {
1000×
            println!("{}", ui::kv(what, ui::hash(h.short(12))));
1010×
        }
102
    }
1031×
}
104
105
/// `oxy receipt list [REV]`: the receipts kept for a state.
1062×
pub fn list(rev: Option<&str>, as_json: bool) -> Result<i32> {
1072×
    let repo = open()?;
1082×
    let heads = match rev {
1090×
        Some(r) => repo.resolve_heads(r)?,
1102×
        None => repo.bookmark_heads()?,
111
    };
1122×
    let found = repo.receipts(&heads)?;
1132×
    if as_json {
1142×
        println!(
115
            "{}",
1162×
            json::arr(found.iter().map(|i| to_json(
1171×
                Some(i.attest.to_hex()),
1181×
                &i.signed,
1191×
                i.problem.as_deref(),
1201×
                i.revoked
121
            )))
122
        );
1232×
        return Ok(0);
1240×
    }
1250×
    if found.is_empty() {
1260×
        println!("{}", ui::dim("No receipts for this state."));
1270×
    }
1280×
    for i in &found {
1290×
        println!(
1300×
            "{} {}",
1310×
            ui::hash(format!("#{}", i.attest.short(12))),
1320×
            line(&i.signed, i.problem.as_deref(), i.revoked)
1330×
        );
1340×
    }
1350×
    Ok(0)
1362×
}
137
1384×
fn find(repo: &oxy_core::repo::Repo, prefix: &str, rev: Option<&str>) -> Result<ReceiptInfo> {
1394×
    let heads = match rev {
1400×
        Some(r) => repo.resolve_heads(r)?,
1414×
        None => repo.bookmark_heads()?,
142
    };
1434×
    let p = prefix.trim_start_matches('#').to_ascii_lowercase();
1444×
    let mut hits: Vec<ReceiptInfo> = repo
1454×
        .receipts(&heads)?
1464×
        .into_iter()
1474×
        .filter(|i| i.attest.to_hex().starts_with(&p))
1484×
        .collect();
1494×
    match hits.len() {
1504×
        1 => Ok(hits.remove(0)),
1510×
        0 => bail!("no receipt #{p} for this state; `oxy receipt list` shows them"),
1520×
        n => bail!("#{p} matches {n} receipts; give more of the hash"),
153
    }
1544×
}
155
156
/// `oxy receipt show HASH [--rev REV]`.
1571×
pub fn show(prefix: &str, rev: Option<&str>, as_json: bool) -> Result<i32> {
1581×
    let repo = open()?;
1591×
    let i = find(&repo, prefix, rev)?;
1601×
    if as_json {
1611×
        println!(
1621×
            "{}",
1631×
            to_json(
1641×
                Some(i.attest.to_hex()),
1651×
                &i.signed,
1661×
                i.problem.as_deref(),
1671×
                i.revoked
1681×
            )
1691×
        );
1701×
    } else {
1710×
        detail(&i.signed, i.problem.as_deref(), i.revoked);
1720×
    }
1731×
    Ok(if i.problem.is_some() { 1 } else { 0 })
1741×
}
175
176
/// `oxy receipt export HASH FILE [--format slsa]`: the signed receipt, to
177
/// hand to anyone, or SLSA provenance of it for tools outside Oxygen.
1783×
pub fn export(prefix: &str, file: &str, rev: Option<&str>, format: &str) -> Result<i32> {
1793×
    let repo = open()?;
1803×
    let i = find(&repo, prefix, rev)?;
1813×
    if format == "slsa" {
1822×
        return export_slsa(&repo, &i, file);
1831×
    }
1841×
    std::fs::write(file, i.signed.encode())?;
1851×
    println!(
186
        "{} {} {}",
1871×
        ui::done("Exported receipt"),
1881×
        ui::hash(format!("#{}", i.attest.short(12))),
1891×
        ui::path(file)
190
    );
1911×
    Ok(0)
1923×
}
193
194
/// What SLSA calls the build type of a Flow job.
195
pub const BUILD_TYPE: &str = "https://oxygenhub.io/oxygenflow/job/v1";
196
197
/// The in-toto Statement v1, with an SLSA provenance v1 predicate, of what
198
/// a receipt says (spec §14.6). Its subjects are the job's outputs (the
199
/// state it ran on when it made none), named by their Oxygen object hashes;
200
/// the signed receipt itself rides along as a byproduct, so an Oxygen
201
/// verifier can still check the runner's own signature.
2021×
pub fn statement(sr: &SignedReceipt) -> serde_json::Value {
203
    use serde_json::json;
2041×
    let r = &sr.receipt;
2051×
    let subject: Vec<_> = if r.outputs.is_empty() {
2061×
        vec![json!({ "name": "state", "digest": { "oxygen-state": sr.state().to_hex() } })]
207
    } else {
2080×
        r.outputs
2090×
            .iter()
2100×
            .map(|o| json!({ "name": o.to_hex(), "digest": { "oxygen-blob": o.to_hex() } }))
2110×
            .collect()
212
    };
2132×
    let rfc3339 = |ms: u64| super::format::when(ms).replacen(' ', "T", 1);
2141×
    let made = sr.attest.hlc.wall_ms;
2151×
    let mut deps = vec![
2161×
        json!({ "name": "state", "digest": { "oxygen-state": sr.state().to_hex() } }),
2171×
        json!({ "name": "scope", "digest": { "oxygen-scope": r.scope_tree_hash.to_hex() } }),
218
    ];
2191×
    deps.extend(
2201×
        r.inputs
2211×
            .iter()
2221×
            .map(|h| json!({ "name": h.to_hex(), "digest": { "oxygen-blob": h.to_hex() } })),
223
    );
2241×
    json!({
2251×
        "_type": "https://in-toto.io/Statement/v1",
2261×
        "subject": subject,
2271×
        "predicateType": "https://slsa.dev/provenance/v1",
2281×
        "predicate": {
2291×
            "buildDefinition": {
2301×
                "buildType": BUILD_TYPE,
2311×
                "externalParameters": {
2321×
                    "job": r.job_name,
2331×
                    "pipeline": r.pipeline_hash.to_hex(),
234
                },
2351×
                "internalParameters": {
2361×
                    "environment": r.environment.to_hex(),
237
                },
2381×
                "resolvedDependencies": deps,
239
            },
2401×
            "runDetails": {
2411×
                "builder": {
2421×
                    "id": format!("urn:oxygen:runner:{}", sr.runner.hash().to_hex()),
2431×
                    "version": { "name": sr.runner.name },
244
                },
2451×
                "metadata": {
2461×
                    "invocationId": sr.run(),
2471×
                    "startedOn": rfc3339(made.saturating_sub(r.duration_ms)),
2481×
                    "finishedOn": rfc3339(made),
249
                },
2501×
                "byproducts": [{
2511×
                    "name": "oxygen-receipt",
2521×
                    "mediaType": "application/vnd.oxygen.receipt+cbor",
2531×
                    "content": oxy_core::dsse::base64(&sr.encode()),
2541×
                    "annotations": {
2551×
                        "exitCode": r.exit_code,
2561×
                        "durationMs": r.duration_ms,
2571×
                        "runner": sr.runner.name,
258
                    },
259
                }],
260
            },
261
        },
262
    })
2631×
}
264
2652×
fn export_slsa(repo: &oxy_core::repo::Repo, i: &ReceiptInfo, file: &str) -> Result<i32> {
2662×
    if let Some(p) = &i.problem {
2670×
        bail!(
268
            "receipt #{} does not verify ({p}); provenance is only made of a valid one",
2690×
            i.attest.short(12)
270
        );
2712×
    }
2722×
    let Some((key, sk)) = repo.secret_key()? else {
2731×
        bail!("SLSA provenance is signed with your key, and none is set up here; run `oxy identity create`");
274
    };
2751×
    let payload = serde_json::to_vec(&statement(&i.signed))?;
2761×
    std::fs::write(
2771×
        file,
2781×
        oxy_core::dsse::envelope(oxy_core::dsse::IN_TOTO, &payload, &key.to_hex(), &sk),
2790×
    )?;
2801×
    println!(
281
        "{} {} {} {}",
2821×
        ui::done("Exported SLSA provenance of receipt"),
2831×
        ui::hash(format!("#{}", i.attest.short(12))),
2841×
        ui::path(file),
2851×
        ui::dim(format!("signed by {}", key.short(12)))
286
    );
2871×
    println!(
288
        "{}",
2891×
        ui::dim(format!(
290
            "  check it: oxy identity export --pem key.pem, then cosign verify-blob-attestation --key key.pem --type slsaprovenance1 --insecure-ignore-tlog=true --check-claims=false --signature {file}"
291
        ))
292
    );
2931×
    Ok(0)
2942×
}
295
2964×
fn read(file: &str) -> Result<SignedReceipt> {
2974×
    let bytes = std::fs::read(file).map_err(|e| anyhow::anyhow!("{file}: {e}"))?;
2984×
    SignedReceipt::decode(&bytes).map_err(|e| anyhow::anyhow!("{file}: not a signed receipt: {e}"))
2994×
}
300
301
/// `oxy receipt verify FILE`: check a signed receipt without keeping it.
3022×
pub fn verify(file: &str, as_json: bool) -> Result<i32> {
3032×
    let sr = read(file)?;
3042×
    let problem = sr.verify().err().map(|e| e.to_string());
3052×
    if as_json {
3061×
        println!("{}", to_json(None, &sr, problem.as_deref(), false));
3071×
    } else {
3081×
        detail(&sr, problem.as_deref(), false);
3091×
    }
3102×
    Ok(if problem.is_some() { 1 } else { 0 })
3112×
}
312
313
/// `oxy receipt import FILE`: verify a signed receipt and keep it.
3142×
pub fn import(file: &str) -> Result<i32> {
3152×
    let repo = open()?;
3162×
    let sr = read(file)?;
3172×
    let r = repo.add_receipt(&sr)?;
3181×
    println!(
319
        "{} {} {} {} {}",
3201×
        ui::done("Kept receipt"),
3211×
        ui::hash(format!("#{}", r.short(12))),
3221×
        ui::subject(&sr.receipt.job_name),
3231×
        ui::dim("by"),
3241×
        ui::author(&sr.runner.name)
325
    );
3261×
    Ok(0)
3272×
}