Skip to main content

proof_policy/
eval.rs

1// Copyright 2026 Proof Engine Contributors
2// SPDX-License-Identifier: MIT OR Apache-2.0
3//! Deterministic policy evaluator (implicit AND). Pure function of
4//! (state, policy, explicit trust inputs) — no I/O, no crypto, no AI.
5// PE-TRUST-005: trusted_issuers is caller input; constrain it by evaluation
6// time for key-rotation semantics (TRUST.md "Key lifetime").
7// PE-NEUT-002: broken cryptographic/evidence preconditions short-circuit to
8// INDETERMINATE here — PASS is only ever produced by satisfied requirements,
9// never by signature validity alone (valid ≠ trusted ≠ accepted).
10
11use crate::policy::{Policy, Requirement};
12use crate::state::VerifiedState;
13use proof_verify::PolicyDecision;
14use std::collections::HashSet;
15
16/// Caller-supplied revocation data. V0.1 semantics: an id present here is
17/// revoked; anything else is "no revocation known" (NOT "fresh"). Freshness
18/// windows and transparency-anchored status land in Phase 6.
19#[derive(Debug, Clone, Default)]
20pub struct RevocationSet {
21    pub revoked: HashSet<String>,
22}
23
24impl RevocationSet {
25    pub fn empty() -> Self {
26        Self::default()
27    }
28
29    pub fn new(ids: impl IntoIterator<Item = String>) -> Self {
30        Self {
31            revoked: ids.into_iter().collect(),
32        }
33    }
34}
35
36/// Explicit trust inputs. `verified_at` must be a trustworthy clock reading;
37/// `skew_leeway` (default 300s) absorbs honest clock drift only.
38#[derive(Debug, Clone)]
39pub struct EvalInputs {
40    pub trusted_issuers: Vec<String>,
41    pub revocations: RevocationSet,
42    pub verified_at: u64,
43    pub skew_leeway: u64,
44}
45
46impl Default for EvalInputs {
47    fn default() -> Self {
48        Self {
49            trusted_issuers: vec![],
50            revocations: RevocationSet::empty(),
51            // Zero clock fails time requirements until the caller supplies a
52            // real one — fail-closed default.
53            verified_at: 0,
54            skew_leeway: 300,
55        }
56    }
57}
58
59#[derive(Debug, Clone)]
60pub struct RequirementResult {
61    pub requirement: String,
62    pub passed: bool,
63    pub message: String,
64}
65
66#[derive(Debug, Clone)]
67pub struct PolicyOutcome {
68    pub policy_id: String,
69    pub decision: PolicyDecision,
70    /// Why, when the decision is INDETERMINATE (proof-side failure).
71    pub note: Option<String>,
72    pub results: Vec<RequirementResult>,
73}
74
75fn pass(req: &str, message: impl Into<String>) -> RequirementResult {
76    RequirementResult {
77        requirement: req.into(),
78        passed: true,
79        message: message.into(),
80    }
81}
82
83fn fail(req: &str, message: impl Into<String>) -> RequirementResult {
84    RequirementResult {
85        requirement: req.into(),
86        passed: false,
87        message: message.into(),
88    }
89}
90
91/// Evaluate a validated policy against verified state. Deterministic: same
92/// inputs always yield the same outcome.
93pub fn evaluate_policy(
94    state: &VerifiedState,
95    policy: &Policy,
96    inputs: &EvalInputs,
97) -> PolicyOutcome {
98    // Broken evidence makes policy evaluation meaningless — and must never
99    // degrade into PASS. INDETERMINATE, not FAIL: the policy wasn't refuted,
100    // its preconditions weren't met.
101    // PE-NEUT-002: verification, trust, and policy verdicts stay distinct —
102    // a broken proof is a precondition failure, never a domain opinion.
103    if !state.crypto_valid || !state.evidence_valid {
104        return PolicyOutcome {
105            policy_id: policy.id.clone(),
106            decision: PolicyDecision::Indeterminate,
107            note: Some(format!(
108                "proof not valid (crypto={}, evidence={}); policy not evaluated",
109                onoff(state.crypto_valid),
110                onoff(state.evidence_valid)
111            )),
112            results: vec![],
113        };
114    }
115    let mut results = Vec::with_capacity(policy.requirements.len());
116    for req in &policy.requirements {
117        results.push(eval_one(req, state, inputs));
118    }
119    let decision = if results.iter().all(|r| r.passed) {
120        PolicyDecision::Pass
121    } else {
122        PolicyDecision::Fail
123    };
124    PolicyOutcome {
125        policy_id: policy.id.clone(),
126        decision,
127        note: None,
128        results,
129    }
130}
131
132fn onoff(b: bool) -> &'static str {
133    if b {
134        "valid"
135    } else {
136        "invalid"
137    }
138}
139
140/// PE-POLICY-001..008 dispatch (PE-POLICY-009 gate above in evaluate_policy).
141fn eval_one(req: &Requirement, state: &VerifiedState, inputs: &EvalInputs) -> RequirementResult {
142    let name = req.describe();
143    match req {
144        // PE-POLICY-001
145        Requirement::SignatureValid => pass(
146            &name,
147            "pipeline established cryptographic validity for this proof",
148        ),
149        // PE-POLICY-002 · PE-TRUST-001 · PE-NEUT-002 (valid signature and
150        // trusted issuer are never conflated: both the trust list AND a
151        // signature-verified attestation are required).
152        Requirement::IssuerTrusted { issuer } => {
153            let listed = inputs.trusted_issuers.iter().any(|t| t == issuer);
154            let present = state.verified_issuers.iter().any(|i| i == issuer);
155            match (listed, present) {
156                (true, true) => pass(&name, format!("issuer {issuer} verified and trusted")),
157                (false, _) => fail(&name, format!("issuer {issuer} not in trust list")),
158                (true, false) => fail(
159                    &name,
160                    format!("trusted issuer {issuer} has no verified attestation here"),
161                ),
162            }
163        }
164        // PE-POLICY-003
165        Requirement::IssuerExcluded { issuer } => {
166            if state.verified_issuers.iter().any(|i| i == issuer) {
167                fail(
168                    &name,
169                    format!("excluded issuer {issuer} has a verified attestation in this proof"),
170                )
171            } else {
172                pass(
173                    &name,
174                    format!("excluded issuer {issuer} absent from this proof"),
175                )
176            }
177        }
178        Requirement::RelationshipExists { relationship } => {
179            if state.rel_types.contains(relationship) {
180                pass(
181                    &name,
182                    format!("edge {} present in validated graph", relationship.as_str()),
183                )
184            } else {
185                fail(
186                    &name,
187                    format!("no {} edge in validated graph", relationship.as_str()),
188                )
189            }
190        }
191        // PE-POLICY-004
192        Requirement::NotExpired => {
193            for (id, (issued, expires)) in state
194                .attestation_ids
195                .iter()
196                .zip(state.attestation_times.iter())
197            {
198                if *issued > inputs.verified_at.saturating_add(inputs.skew_leeway) {
199                    return fail(
200                        &name,
201                        format!("attestation {id} issued in the future relative to verifier clock"),
202                    );
203                }
204                if let Some(exp) = expires {
205                    if inputs.verified_at > exp.saturating_add(inputs.skew_leeway) {
206                        return fail(&name, format!("attestation {id} expired"));
207                    }
208                }
209                // expires_at == None: no bounded validity to violate (a policy
210                // needing mandatory expiry wants a future requirement type).
211            }
212            pass(
213                &name,
214                format!(
215                    "{} attestation(s) within validity at {}",
216                    state.attestation_ids.len(),
217                    inputs.verified_at
218                ),
219            )
220        }
221        // PE-POLICY-005
222        Requirement::NotRevoked => {
223            for id in &state.attestation_ids {
224                if inputs.revocations.revoked.contains(id) {
225                    return fail(&name, format!("attestation {id} revoked"));
226                }
227            }
228            pass(
229                &name,
230                format!(
231                    "no known revocation among {} attestation(s)",
232                    state.attestation_ids.len()
233                ),
234            )
235        }
236        // PE-POLICY-006
237        Requirement::NotSuperseded => {
238            if state.superseded_ids.is_empty() {
239                pass(&name, "no attestation in this proof is superseded")
240            } else {
241                fail(
242                    &name,
243                    format!(
244                        "superseded attestation(s) present: {}",
245                        state.superseded_ids.join(", ")
246                    ),
247                )
248            }
249        }
250        // PE-POLICY-007
251        Requirement::EvidencePresent { kind } => {
252            if state.evidence_kinds.contains(kind) {
253                pass(&name, format!("evidence {} present", kind.as_str()))
254            } else {
255                fail(&name, format!("evidence {} missing", kind.as_str()))
256            }
257        }
258        // PE-POLICY-007
259        Requirement::TransparencyPresent => {
260            if state.has_transparency() {
261                pass(&name, "transparency_receipt present")
262            } else {
263                fail(&name, "no transparency_receipt in proof")
264            }
265        }
266        // V1.1: Proof freshness (replay protection)
267        Requirement::ProofFresh { max_age_seconds } => {
268            let age = inputs.verified_at.saturating_sub(state.proof_created_at);
269            if age <= *max_age_seconds {
270                pass(&name, format!("proof age {age}s <= {max_age_seconds}s"))
271            } else {
272                fail(&name, format!("proof too old: {age}s > {max_age_seconds}s"))
273            }
274        }
275    }
276}