Skip to main content

proof_cli/
check.rs

1// Copyright 2026 Proof Engine Contributors
2// SPDX-License-Identifier: MIT OR Apache-2.0
3//! Verification-side output: proof loading, report emission, exit codes.
4//! Exit code contract: 0 = PASS, 1 = FAIL/INDETERMINATE, 2 = error.
5
6use proof_verify::Validity;
7use proof_verify::VerifyReport;
8
9/// A loaded proof artifact. The pipeline re-verifies every stage over the
10/// canonical bytes (including the envelope id), so loading only needs to
11/// extract schema-valid bytes; nothing here is trusted.
12pub struct LoadedProof {
13    pub canonical: Vec<u8>,
14    #[allow(dead_code)]
15    pub proof: proof_core::model::Proof,
16}
17
18/// Load a proof artifact file (JSON wrapper, canonical CBOR hex inside).
19// PE-CLI-002: schema-decode only; pipeline re-verifies id/canonical/sigs.
20pub fn load_proof(path: &str) -> Result<LoadedProof, String> {
21    let text = crate::read_input_file(path)?;
22    let v: serde_json::Value =
23        serde_json::from_str(&text).map_err(|e| format!("parse {path}: {e}"))?;
24    let hex_str = v
25        .get("cbor")
26        .and_then(|x| x.as_str())
27        .ok_or_else(|| format!("{path}: missing `cbor`"))?;
28    let bytes = hex::decode(hex_str).map_err(|e| format!("{path}: bad hex: {e}"))?;
29    let limits = crate::limits();
30    let value = proof_format::decode_strict(&bytes, &limits).map_err(|e| format!("{path}: {e}"))?;
31    let proof =
32        proof_format::schema::cbor_to_proof(&value, &limits).map_err(|e| format!("{path}: {e}"))?;
33    eprintln!("loaded proof {} ({path})", proof.proof_id);
34    Ok(LoadedProof {
35        canonical: bytes,
36        proof,
37    })
38}
39
40fn validity_str(v: Validity) -> &'static str {
41    if v == Validity::Valid {
42        "valid"
43    } else {
44        "invalid"
45    }
46}
47
48/// Explicit JSON projection of the report (the report type is not Serialize;
49/// the CLI owns its output format). Stable field order, machine-readable.
50// PE-CLI-004 ยท PE-CLI-007: pub(crate) so `evaluate --json` can embed the
51// pipeline report alongside the policy outcome.
52pub fn report_json(r: &VerifyReport) -> serde_json::Value {
53    serde_json::json!({
54        "proof_id": r.proof_id,
55        "cryptographic_validity": validity_str(r.cryptographic_validity),
56        "evidence_validity": validity_str(r.evidence_validity),
57        "policy_decision": r.policy_decision.as_str(),
58        "lifecycle_checked": r.lifecycle_checked,
59        "lifecycle": r
60            .lifecycle
61            .iter()
62            .map(|l| {
63                serde_json::json!({
64                    "object": l.object,
65                    "status": l.status.as_str(),
66                    "code": l.code.map(|c| c.as_str()),
67                    "message": l.message,
68                })
69            })
70            .collect::<Vec<_>>(),
71        "status_objects": r.status_objects,
72        "checks": r
73            .checks
74            .iter()
75            .map(|c| {
76                serde_json::json!({
77                    "stage": c.stage,
78                    "object": c.object,
79                    "ok": c.ok,
80                    "code": c.code.map(|c| c.as_str()),
81                    "message": c.message,
82                })
83            })
84            .collect::<Vec<_>>(),
85    })
86}
87
88/// Emit the report: stdout (machine-readable) when no `--out` is given,
89/// otherwise written to the file with only a progress note on stderr.
90// PE-CLI-004: machine-readable stdout/file; progress stderr.
91pub fn emit_report(report: &VerifyReport, out: Option<String>) -> Result<(), String> {
92    let v = report_json(report);
93    let text = serde_json::to_string_pretty(&v).map_err(|e| e.to_string())?;
94    match out {
95        Some(path) => {
96            std::fs::write(
97                &path,
98                text + "
99",
100            )
101            .map_err(|e| format!("write {path}: {e}"))?;
102            eprintln!("report  -> {path}");
103        }
104        None => println!("{text}"),
105    }
106    Ok(())
107}
108
109/// `verify` exit code: PASS only when both crypto AND evidence are valid.
110pub fn verdict_exit(report: &VerifyReport) -> i32 {
111    if report.passed_crypto() && report.evidence_validity == Validity::Valid {
112        crate::EXIT_OK
113    } else {
114        crate::EXIT_FAIL
115    }
116}
117
118/// PE-CLI-007: stable JSON projection of the policy outcome for `evaluate
119/// --json` (`proof-cli/src/make.rs`). Field set is the machine contract.
120pub fn outcome_json(outcome: &proof_policy::PolicyOutcome) -> serde_json::Value {
121    serde_json::json!({
122        "policy_id": outcome.policy_id,
123        "decision": outcome.decision.as_str(),
124        "note": outcome.note,
125        "results": outcome
126            .results
127            .iter()
128            .map(|r| {
129                serde_json::json!({
130                    "requirement": r.requirement,
131                    "passed": r.passed,
132                    "message": r.message,
133                })
134            })
135            .collect::<Vec<_>>(),
136    })
137}