1use crate::policy::{Policy, Requirement};
12use crate::state::VerifiedState;
13use proof_verify::PolicyDecision;
14use std::collections::HashSet;
15
16#[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#[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 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 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
91pub fn evaluate_policy(
94 state: &VerifiedState,
95 policy: &Policy,
96 inputs: &EvalInputs,
97) -> PolicyOutcome {
98 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
140fn eval_one(req: &Requirement, state: &VerifiedState, inputs: &EvalInputs) -> RequirementResult {
142 let name = req.describe();
143 match req {
144 Requirement::SignatureValid => pass(
146 &name,
147 "pipeline established cryptographic validity for this proof",
148 ),
149 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 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 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 }
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 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 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 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 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 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}