Skip to main content

proof_cli/
lib.rs

1// Copyright 2026 Proof Engine Contributors
2// SPDX-License-Identifier: MIT OR Apache-2.0
3//! proof-cli: command-line front end over the library crates (Phase 7).
4//! Adds no trust logic of its own: every artifact is re-verified on load,
5//! every time input is an explicit flag, keys are supplied per invocation.
6
7pub mod artifact;
8pub mod check;
9pub mod demo;
10pub mod make;
11
12use std::collections::{HashMap, HashSet};
13
14/// Exit codes: 0 PASS, 1 FAIL/INDETERMINATE verdict, 2 usage or engine error.
15pub const EXIT_OK: i32 = 0;
16pub const EXIT_FAIL: i32 = 1;
17pub const EXIT_ERR: i32 = 2;
18
19/// Parsed command line: subcommand + positional args + `--flag value` flags.
20/// Deliberately hand-rolled (no new dependencies in V0.1).
21#[derive(Debug, Default)]
22pub struct Cli {
23    pub command: String,
24    pub positional: Vec<String>,
25    values: HashMap<String, String>,
26    multi: HashMap<String, Vec<String>>,
27    flags: HashSet<String>,
28}
29
30impl Cli {
31    pub fn parse(args: &[String]) -> Result<Cli, String> {
32        let mut it = args.iter().peekable();
33        let command = it
34            .next()
35            .ok_or_else(|| "missing command (try `help`)".to_string())?
36            .clone();
37        let mut cli = Cli {
38            command,
39            ..Cli::default()
40        };
41        while let Some(a) = it.next() {
42            let Some(name) = a.strip_prefix("--") else {
43                cli.positional.push(a.clone());
44                continue;
45            };
46            let (name, inline) = match name.split_once('=') {
47                Some((n, v)) => (n.to_string(), Some(v.to_string())),
48                None => (name.to_string(), None),
49            };
50            // A `--flag` with no inline value takes the next token as its
51            // value only when that token does not look like another flag.
52            // Peek first: a boolean flag must never swallow `--other` tokens.
53            let value = match inline {
54                Some(v) => v,
55                None => match it.peek() {
56                    Some(v) if !v.starts_with("--") => it.next().unwrap().clone(),
57                    _ => {
58                        // Boolean flag (no value).
59                        cli.flags.insert(name);
60                        continue;
61                    }
62                },
63            };
64            cli.multi
65                .entry(name.clone())
66                .or_default()
67                .push(value.clone());
68            cli.values.insert(name, value);
69        }
70        Ok(cli)
71    }
72    /// Value of a required flag.
73    pub fn req(&self, name: &str) -> Result<String, String> {
74        self.values
75            .get(name)
76            .cloned()
77            .ok_or_else(|| format!("missing required flag --{name}"))
78    }
79
80    /// Value of an optional flag.
81    pub fn opt(&self, name: &str) -> Option<String> {
82        self.values.get(name).cloned()
83    }
84
85    /// All values of a repeatable flag, in order.
86    pub fn many(&self, name: &str) -> Vec<String> {
87        self.multi.get(name).cloned().unwrap_or_default()
88    }
89
90    /// True when a boolean flag was present.
91    pub fn has(&self, name: &str) -> bool {
92        self.flags.contains(name)
93    }
94
95    /// True when --quiet is set (suppress progress output).
96    pub fn quiet(&self) -> bool {
97        self.has("quiet")
98    }
99
100    /// Required u64 flag.
101    pub fn req_u64(&self, name: &str) -> Result<u64, String> {
102        self.req(name)?
103            .parse()
104            .map_err(|_| format!("--{name} must be a u64"))
105    }
106
107    /// Optional u64 flag.
108    pub fn opt_u64(&self, name: &str) -> Result<Option<u64>, String> {
109        match self.opt(name) {
110            None => Ok(None),
111            Some(v) => v
112                .parse()
113                .map(Some)
114                .map_err(|_| format!("--{name} must be a u64")),
115        }
116    }
117}
118
119/// Parse `k=v[,k=v…]` into flat metadata / claim fields. Values are text,
120/// `true`/`false`, or unsigned integers (matching the closed MetaValue set).
121pub fn parse_fields(
122    spec: Option<String>,
123) -> Result<Vec<(String, proof_core::model::MetaValue)>, String> {
124    let Some(spec) = spec else {
125        return Ok(vec![]);
126    };
127    let mut out = vec![];
128    for pair in spec.split(',') {
129        let Some((k, v)) = pair.split_once('=') else {
130            return Err(format!("bad field `{pair}` (expected k=v)"));
131        };
132        if k.is_empty() || v.is_empty() {
133            return Err(format!("bad field `{pair}` (empty key or value)"));
134        }
135        let mv = if v == "true" {
136            proof_core::model::MetaValue::Bool(true)
137        } else if v == "false" {
138            proof_core::model::MetaValue::Bool(false)
139        } else if let Ok(n) = v.parse::<u64>() {
140            proof_core::model::MetaValue::Uint(n)
141        } else {
142            proof_core::model::MetaValue::Text(v.to_string())
143        };
144        out.push((k.to_string(), mv));
145    }
146    Ok(out)
147}
148
149/// Load an Ed25519 key from `--seed`: `test` selects the fixed test key
150/// (fixtures/demos ONLY); otherwise 64 hex chars = 32 seed bytes.
151pub fn load_key(seed: &str) -> Result<proof_crypto::Ed25519Key, String> {
152    load_key_material(seed, "--seed")
153}
154
155fn load_key_material(seed: &str, what: &str) -> Result<proof_crypto::Ed25519Key, String> {
156    if seed == "test" {
157        return Ok(proof_crypto::build::fixtures::test_key());
158    }
159    let bytes = hex::decode(seed).map_err(|e| format!("{what} bad hex: {e}"))?;
160    let arr: [u8; 32] = bytes
161        .try_into()
162        .map_err(|_| format!("{what} must be `test` or 64 hex chars (32 bytes)"))?;
163    Ok(proof_crypto::Ed25519Key::from_seed(&arr))
164}
165
166/// Load a key for commands taking `--seed`/`--seed-file`. `--seed-file`
167/// reads the seed from a file (capped by MAX_INPUT_FILE_BYTES) so raw key
168/// material never lands in argv, shell history, or process listings;
169/// `--seed` keeps working for demos/tests. The two flags must not combine.
170pub fn load_key_opt(cli: &Cli) -> Result<proof_crypto::Ed25519Key, String> {
171    match (cli.opt("seed"), cli.opt("seed-file")) {
172        (Some(_), Some(_)) => Err("--seed and --seed-file are mutually exclusive".into()),
173        (None, Some(path)) => {
174            let seed = read_input_file(&path)?;
175            load_key_material(seed.trim(), "--seed-file")
176        }
177        (Some(seed), None) => load_key(&seed),
178        (None, None) => Err("missing required flag --seed (or --seed-file)".into()),
179    }
180}
181
182pub fn limits() -> proof_core::Limits {
183    proof_core::Limits::default()
184}
185
186/// Print progress to stderr unless --quiet is set.
187pub fn progress(quiet: bool, msg: &str) {
188    if !quiet {
189        eprintln!("{msg}");
190    }
191}
192
193/// Cap for any file the CLI reads (artifacts, proofs, policies). Well above
194/// the largest legitimate input (1 MiB proof → ~2 MiB hex JSON): oversized
195/// files are refused with a clean error instead of being buffered without
196/// bound (Phase 7 hostile review H1).
197pub const MAX_INPUT_FILE_BYTES: u64 = 8 << 20;
198
199/// Read a CLI input file with the size cap enforced during buffering (no
200/// TOCTOU window: at most one byte over the cap is ever read).
201// PE-SEC-002: 8 MiB cap enforced during buffering.
202pub fn read_input_file(path: &str) -> Result<String, String> {
203    use std::io::Read;
204    let mut f = std::fs::File::open(path).map_err(|e| format!("read {path}: {e}"))?;
205    let mut buf = Vec::new();
206    f.by_ref()
207        .take(MAX_INPUT_FILE_BYTES + 1)
208        .read_to_end(&mut buf)
209        .map_err(|e| format!("read {path}: {e}"))?;
210    if buf.len() as u64 > MAX_INPUT_FILE_BYTES {
211        return Err(format!(
212            "{path}: file too large (>{MAX_INPUT_FILE_BYTES} bytes)"
213        ));
214    }
215    String::from_utf8(buf).map_err(|_| format!("{path}: invalid UTF-8"))
216}
217
218pub const USAGE: &str = "\
219proof-cli — Proof Engine command line (V1.0)
220
221Exit codes: 0 = PASS/valid, 1 = FAIL/INDETERMINATE verdict, 2 = usage or engine error.
222All commands accept --quiet to suppress progress output on stderr.
223
224Creation commands (write JSON artifact files wrapping canonical CBOR bytes):
225  create-event --type <event.type> --subject <id> --effective-at <u64>
226               --payload-hex <64 hex> [--meta k=v,...] --out <file>
227  attest       --seed <test|64hex> --subject <id> --claim-type <t> [--claim k=v,...]
228               --issued-at <u64> [--expires-at <u64>] [--evidence-ref <id>] --out <file>
229  add-evidence --kind <kind> --digest-hex <64 hex> [--attestation-ref <id>] [--hint <t>]
230               --out <file>
231  relate       --from <id> --type <TYPE> --to <id> [--evidence-ref <id>]
232               [--attestation-ref <id>] --out <file>
233  build        --kind <t> --subject <s> --predicate <p> [--object <o>] [--at-time <u64>]
234               [--context k=v,...] --created-at <u64> --events <f[,f…]>
235               --attestations <f[,f…]> --evidence <f[,f…]> --relationships <f[,f…]>
236               --out <file>
237  revoke       --seed <test|64hex> --target <id> [--reason <t>] --at <u64> --out <file>
238  supersede    --seed <test|64hex> --old <id> --new <id> --at <u64> --out <file>
239
240Verification commands:
241  verify       --proof <file> --clock <u64> [--skew <u64=300>]
242               [--revocations-known-at <u64>] [--status <file>]… [--authority <keyref>]…
243  evaluate     --proof <file> --policy <file> --clock <u64> [--skew <u64=300>]
244               [--trusted <keyref>]… [--revoked <id,id,…>] [--revocations-known-at <u64>]
245                [--json] — machine-readable policy_outcome + report JSON on stdout
246  explain      (same flags as evaluate; prints the full explanation)
247
248  demo         [--out <dir>=demo/out] — deterministic end-to-end killer use-case
249  help         — this text
250
251Artifacts are JSON wrappers around canonical CBOR bytes (hex); bytes are
252re-verified on every load — ids recomputed, signatures checked. Seeds are for
253demos/tests only; production key handling is out of scope for V1.0.
254Prefer --seed-file <path> over --seed <hex>: raw key material in argv is
255visible to ps(1) and shell history; the two flags never combine.";