Skip to main content

proof_cli/
make.rs

1// Copyright 2026 Proof Engine Contributors
2// SPDX-License-Identifier: MIT OR Apache-2.0
3//! Creation commands: build artifacts and assemble/verify proofs.
4//! Every command re-derives ids and signatures through the library crates;
5//! this module contains no trust logic of its own.
6
7use crate::artifact::{
8    input_list, load_attestation, load_event, load_evidence, load_relationship, load_status,
9};
10use crate::Cli;
11use proof_core::model::Proposition;
12use proof_crypto::build::{CreatedEvent, CreatedEvidence, CreatedRelationship};
13use proof_verify::builder::ProofBuilder;
14
15fn created_event(content: proof_core::model::EventContent) -> Result<CreatedEvent, String> {
16    proof_crypto::build::create_event(content, &crate::limits()).map_err(|e| e.to_string())
17}
18
19fn created_evidence(content: proof_core::model::Evidence) -> Result<CreatedEvidence, String> {
20    proof_crypto::build::make_evidence(
21        content.kind,
22        content.digest.clone(),
23        content.attestation_ref,
24        content.hint,
25        &crate::limits(),
26    )
27    .map_err(|e| e.to_string())
28}
29
30fn created_relationship(
31    content: proof_core::model::Relationship,
32) -> Result<CreatedRelationship, String> {
33    proof_crypto::build::make_relationship(content, &crate::limits()).map_err(|e| e.to_string())
34}
35
36/// `build`: assemble proof artifacts into a canonical, id-bound proof file.
37/// Topology validation (grounding, dangling refs) is proof-graph's job and
38/// runs inside `ProofBuilder::build` — the CLI adds nothing on top.
39pub fn build(cli: &Cli) -> Result<String, String> {
40    let context = crate::parse_fields(cli.opt("context"))?;
41    let proposition = Proposition {
42        v: 1,
43        kind: cli.req("kind")?,
44        subject: cli.req("subject")?,
45        predicate: cli.req("predicate")?,
46        object: cli.opt("object"),
47        at_time: cli.opt_u64("at-time")?,
48        context,
49    };
50    let mut b = ProofBuilder::new(proposition, cli.req_u64("created-at")?);
51    for path in input_list(cli, "events")? {
52        let content = load_event(&path, &crate::limits())?;
53        b.add_event(created_event(content)?);
54    }
55    for path in input_list(cli, "attestations")? {
56        b.add_attestation(load_attestation(&path, &crate::limits())?);
57    }
58    for path in input_list(cli, "evidence")? {
59        let content = load_evidence(&path, &crate::limits())?;
60        b.add_evidence(created_evidence(content)?);
61    }
62    for path in input_list(cli, "relationships")? {
63        let content = load_relationship(&path, &crate::limits())?;
64        b.add_relationship(created_relationship(content)?);
65    }
66    let built = b
67        .build(&crate::limits())
68        .map_err(|e| format!("build: {e}"))?;
69    let out = cli.req("out")?;
70    crate::artifact::write_proof_file(&out, &built.id, &built.canonical)?;
71    println!("proof   {} -> {out}", built.id);
72    Ok(built.id)
73}
74
75/// Flags shared by verify/evaluate/explain: an explicit clock is mandatory —
76/// the CLI never reads the wall clock (PROPOSAL rule 4).
77pub struct CommonInputs {
78    pub verified_at: u64,
79    pub skew: u64,
80    pub revocations_known_at: Option<u64>,
81}
82
83// PE-CLI-003: explicit clock mandatory; wall clock never read.
84pub fn common(cli: &Cli) -> Result<CommonInputs, String> {
85    Ok(CommonInputs {
86        verified_at: cli.req_u64("clock")?,
87        skew: cli
88            .opt("skew")
89            .map(|v| v.parse().map_err(|_| "--skew must be a u64".to_string()))
90            .transpose()?
91            .unwrap_or(300),
92        revocations_known_at: cli.opt_u64("revocations-known-at")?,
93    })
94}
95
96/// All trust inputs are explicit flags; nothing is guessed from the proof.
97pub fn eval_inputs(cli: &Cli, c: &CommonInputs) -> proof_policy::EvalInputs {
98    let mut revoked: Vec<String> = vec![];
99    for item in cli.many("revoked") {
100        revoked.extend(item.split(',').map(str::to_string));
101    }
102    proof_policy::EvalInputs {
103        trusted_issuers: cli.many("trusted"),
104        revocations: proof_policy::RevocationSet::new(revoked),
105        verified_at: c.verified_at,
106        skew_leeway: c.skew,
107    }
108}
109
110/// `verify`: run the 10-stage pipeline. Authority keyrefs must be supplied
111/// explicitly via --authority; revocation status objects via --status.
112pub fn verify(cli: &Cli) -> Result<i32, String> {
113    let proof = crate::check::load_proof(&cli.req("proof")?)?;
114    let c = common(cli)?;
115    let statuses: Vec<proof_crypto::SignedStatus> = cli
116        .many("status")
117        .iter()
118        .map(|p| load_status(p, &crate::limits()))
119        .collect::<Result<_, _>>()?;
120    let authorities = cli.many("authority");
121    let report = proof_verify::verify_proof(
122        &proof.canonical,
123        &proof_verify::VerifyCtx {
124            verified_at: c.verified_at,
125            clock_skew_leeway: c.skew,
126            status_objects: statuses,
127            revocation_authorities: authorities,
128            revocations_known_at: c.revocations_known_at,
129            ..Default::default()
130        },
131    )
132    .map_err(|e| format!("verify: {e}"))?;
133    crate::check::emit_report(&report, cli.opt("out"))?;
134    Ok(crate::check::verdict_exit(&report))
135}
136
137/// `evaluate` / `explain`: pipeline + declarative policy over its output.
138// PE-CLI-006: explain prints prose only, never JSON over prose.
139pub fn evaluate(cli: &Cli, explain: bool) -> Result<i32, String> {
140    let proof = crate::check::load_proof(&cli.req("proof")?)?;
141    let c = common(cli)?;
142    let policy_path = cli.req("policy")?;
143    let policy_text =
144        crate::read_input_file(&policy_path).map_err(|e| format!("read policy: {e}"))?;
145    let policy_val: serde_json::Value =
146        serde_json::from_str(&policy_text).map_err(|e| format!("parse policy: {e}"))?;
147    let policy = proof_policy::parse_policy(&policy_val, &crate::limits())
148        .map_err(|e| format!("policy: {e}"))?;
149    let statuses: Vec<proof_crypto::SignedStatus> = cli
150        .many("status")
151        .iter()
152        .map(|p| load_status(p, &crate::limits()))
153        .collect::<Result<_, _>>()?;
154    let report = proof_verify::verify_proof(
155        &proof.canonical,
156        &proof_verify::VerifyCtx {
157            verified_at: c.verified_at,
158            clock_skew_leeway: c.skew,
159            trusted_issuers: cli.many("trusted"),
160            status_objects: statuses,
161            revocation_authorities: cli.many("authority"),
162            revocations_known_at: c.revocations_known_at,
163            ..Default::default()
164        },
165    )
166    .map_err(|e| format!("verify: {e}"))?;
167    let state = proof_policy::state_from_report_and_proof(&report, &proof.proof)
168        .map_err(|e| format!("state: {e}"))?;
169    let outcome = proof_policy::evaluate_policy(&state, &policy, &eval_inputs(cli, &c));
170    // Report emission: `evaluate` prints JSON to stdout unless --out is
171    // given; `explain` never dumps JSON on top of the prose (file via --out
172    // is still honored).
173    // Report emission: prose mode keeps the historical stdout report (then
174    // the decision text below); `--json` owns stdout exclusively so stdout is
175    // one script-parsable document; `--out` always writes the report file and
176    // `explain` never mixes JSON with prose (PE-CLI-006).
177    let json_mode = cli.has("json") && !explain;
178    match (explain, cli.opt("out")) {
179        (false, Some(path)) => crate::check::emit_report(&report, Some(path))?,
180        (false, None) if json_mode => {}
181        (false, None) => crate::check::emit_report(&report, None)?,
182        (true, Some(path)) => crate::check::emit_report(&report, Some(path))?,
183        (true, None) => {}
184    }
185    if explain {
186        print!("{}", proof_policy::explain_full(&report, &outcome));
187    } else if cli.has("json") {
188        // PE-CLI-007: machine-readable policy decision. Same exit-code
189        // contract as prose mode; `explain` never takes this path (PE-CLI-006).
190        let merged = serde_json::json!({
191            "policy_outcome": crate::check::outcome_json(&outcome),
192            "report": crate::check::report_json(&report),
193        });
194        println!(
195            "{}",
196            serde_json::to_string_pretty(&merged).map_err(|e| e.to_string())?
197        );
198    } else {
199        println!("decision {}", outcome.decision.as_str());
200        for r in &outcome.results {
201            println!(
202                "  [{}] {} — {}",
203                if r.passed { "ok" } else { "NO" },
204                r.requirement,
205                r.message
206            );
207        }
208    }
209    Ok(match outcome.decision {
210        proof_verify::PolicyDecision::Pass => crate::EXIT_OK,
211        proof_verify::PolicyDecision::Fail | proof_verify::PolicyDecision::Indeterminate => {
212            crate::EXIT_FAIL
213        }
214    })
215}