1use std::collections::{BTreeMap, BTreeSet};
4use std::panic::{catch_unwind, AssertUnwindSafe};
5use std::sync::Arc;
6use std::time::Duration;
7
8use super::constraints::CONSTRAINT_RECEIVER_AUDIENCE;
9use super::context_policy::{same_v2_context_policy, V2ContextPolicy};
10use super::crypto::{equal_keys, key_id_v2, valid_v2_id};
11use super::errors::{err, Classify, V2ErrorClass, V2Result};
12use super::evaluator::{
13 snapshot_constraint_evaluators_v2, ConstraintEvaluatorRefV2, ConstraintEvaluatorRegistryV2,
14 RegisteredEvaluator,
15};
16use super::limits::{v2_challenge_time_current, valid_v2_timestamp, validate_v2_freshness_configuration};
17use super::verify::V2ReceiverBindingHook;
18use super::wire::{
19 bundle_hash_v2, validate_required_scope_v2, verify_proof_bundle_v2_signatures, ProofBundleV2,
20 MAX_SAFE,
21};
22use crate::types::{HybridPublicKey, ParamsValue};
23
24#[derive(Debug, Clone, Default, PartialEq, Eq)]
28pub struct ExpectedChallengeV2 {
29 pub value: Vec<u8>,
30 pub issued_at: i64,
31 pub expires_at: i64,
32 pub verifier_namespace: String,
33 pub replay_epoch: i64,
34 pub verifier_id: String,
35 pub expected_agent_id: String,
36 pub expected_agent_public_key: Option<HybridPublicKey>,
37 pub expected_receiver_id: String,
38 pub expected_session_context: Option<Vec<u8>>,
39 pub context_policy: Option<V2ContextPolicy>,
40}
41
42#[derive(Debug, Clone)]
46pub struct V2PreflightResult {
47 pub(crate) state: Arc<ExpectedChallengeStateV2>,
48}
49
50#[derive(Clone)]
52pub(crate) struct ExpectedChallengeStateV2 {
53 pub value: Vec<u8>,
54 pub issued_at: i64,
55 pub expires_at: i64,
56 pub verifier_namespace: String,
57 pub replay_epoch: i64,
58 pub verifier_id: String,
59 pub expected_agent_id: String,
60 pub expected_agent_public_key: Option<HybridPublicKey>,
61 pub expected_receiver_id: String,
62 pub expected_session_context: Option<Vec<u8>>,
63 pub required_scope: String,
64 pub bundle_hash: String,
65 pub issuer_ids: Vec<String>,
66 pub future_skew: i64,
67 pub max_age: i64,
68 pub context_policy_digest: String,
69 pub context_policy: Option<V2ContextPolicy>,
70 pub no_context_policy: bool,
73 pub evaluator_refs: Vec<ConstraintEvaluatorRefV2>,
74 pub evaluators: BTreeMap<String, RegisteredEvaluator>,
75 pub evaluator_timeout: Duration,
76}
77
78impl std::fmt::Debug for ExpectedChallengeStateV2 {
79 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
80 f.debug_struct("ExpectedChallengeStateV2")
81 .field("bundle_hash", &self.bundle_hash)
82 .field("required_scope", &self.required_scope)
83 .finish_non_exhaustive()
84 }
85}
86
87fn snapshot_expected_challenge_v2(
88 expected: &ExpectedChallengeV2,
89 policy: Option<&V2ContextPolicy>,
90 required_scope: &str,
91 bundle_hash: String,
92 issuer_ids: Vec<String>,
93 max_age: i64,
94 future_skew: i64,
95) -> ExpectedChallengeStateV2 {
96 ExpectedChallengeStateV2 {
97 value: expected.value.clone(),
98 issued_at: expected.issued_at,
99 expires_at: expected.expires_at,
100 verifier_namespace: expected.verifier_namespace.clone(),
101 replay_epoch: expected.replay_epoch,
102 verifier_id: expected.verifier_id.clone(),
103 expected_agent_id: expected.expected_agent_id.clone(),
104 expected_agent_public_key: expected.expected_agent_public_key.clone(),
105 expected_receiver_id: expected.expected_receiver_id.clone(),
106 expected_session_context: expected.expected_session_context.clone(),
107 required_scope: required_scope.to_string(),
108 bundle_hash,
109 issuer_ids,
110 future_skew,
111 max_age,
112 context_policy_digest: policy.map(|p| p.digest().to_string()).unwrap_or_default(),
113 context_policy: policy.cloned(),
114 no_context_policy: policy.is_none(),
115 evaluator_refs: Vec::new(),
116 evaluators: BTreeMap::new(),
117 evaluator_timeout: Duration::ZERO,
118 }
119}
120
121fn bytes_equal(a: &Option<Vec<u8>>, b: &Option<Vec<u8>>) -> bool {
122 a.as_deref().unwrap_or(&[]) == b.as_deref().unwrap_or(&[])
123}
124
125pub(crate) fn matches_expected_challenge_v2(
127 expected: &ExpectedChallengeV2,
128 state: &ExpectedChallengeStateV2,
129) -> bool {
130 if expected.value != state.value
131 || expected.issued_at != state.issued_at
132 || expected.expires_at != state.expires_at
133 || expected.verifier_namespace != state.verifier_namespace
134 || expected.replay_epoch != state.replay_epoch
135 || expected.verifier_id != state.verifier_id
136 || expected.expected_agent_id != state.expected_agent_id
137 || expected.expected_receiver_id != state.expected_receiver_id
138 || !bytes_equal(&expected.expected_session_context, &state.expected_session_context)
139 || (expected.context_policy.is_some()
140 && !same_v2_context_policy(expected.context_policy.as_ref(), state.context_policy.as_ref()))
141 {
142 return false;
143 }
144 match (&expected.expected_agent_public_key, &state.expected_agent_public_key) {
145 (None, None) => true,
146 (Some(a), Some(b)) => equal_keys(a, b),
147 _ => false,
148 }
149}
150
151#[allow(clippy::too_many_arguments)]
157pub fn preflight_proof_bundle_v2(
158 bundle: &ProofBundleV2,
159 expected: Option<&ExpectedChallengeV2>,
160 policy: Option<&V2ContextPolicy>,
161 required_scope: &str,
162 configured_namespace: &str,
163 configured_replay_epoch: i64,
164 configured_verifier_id: &str,
165 now: i64,
166 max_age_seconds: i64,
167 future_skew_seconds: i64,
168) -> V2Result<V2PreflightResult> {
169 preflight_proof_bundle_v2_inner(
170 bundle,
171 expected,
172 policy,
173 false,
174 None,
175 None,
176 required_scope,
177 configured_namespace,
178 configured_replay_epoch,
179 configured_verifier_id,
180 now,
181 max_age_seconds,
182 future_skew_seconds,
183 )
184}
185
186#[allow(clippy::too_many_arguments)]
188pub(crate) fn preflight_proof_bundle_v2_inner(
189 bundle: &ProofBundleV2,
190 expected: Option<&ExpectedChallengeV2>,
191 policy: Option<&V2ContextPolicy>,
192 allow_no_policy: bool,
193 hook: Option<&V2ReceiverBindingHook>,
194 evaluators: Option<&ConstraintEvaluatorRegistryV2>,
195 required_scope: &str,
196 configured_namespace: &str,
197 configured_replay_epoch: i64,
198 configured_verifier_id: &str,
199 now: i64,
200 max_age_seconds: i64,
201 future_skew_seconds: i64,
202) -> V2Result<V2PreflightResult> {
203 let Some(expected) = expected else {
204 return err(
205 V2ErrorClass::ExpectedChallengeUnavailable,
206 "v2 expected challenge is unavailable",
207 );
208 };
209 if (policy.is_none() && !allow_no_policy) || policy.is_some_and(|p| !p.is_valid()) {
210 return err(V2ErrorClass::ConfigurationInvalid, "v2 context policy is missing or invalid");
211 }
212 if policy.is_none() && expected.context_policy.is_some() {
213 return err(
214 V2ErrorClass::ConfigurationInvalid,
215 "v2 challenge context policy does not match the issued policy",
216 );
217 }
218 if let Some(policy) = policy {
219 if expected.context_policy.is_some()
220 && !same_v2_context_policy(expected.context_policy.as_ref(), Some(policy))
221 {
222 return err(
223 V2ErrorClass::ConfigurationInvalid,
224 "v2 challenge context policy does not match the issued policy",
225 );
226 }
227 if policy.require_bound() {
228 if let Some(ctx) = &expected.expected_session_context {
232 if ctx.as_slice() != policy.expected_session_context_ref() {
233 return err(
234 V2ErrorClass::ConfigurationInvalid,
235 "v2 challenge context does not match the configured context policy",
236 );
237 }
238 }
239 } else if expected.expected_session_context.is_some() {
240 return err(
241 V2ErrorClass::ConfigurationInvalid,
242 "unbound v2 context policy cannot have an expected session context",
243 );
244 }
245 }
246 let mut checked = expected.clone();
247 checked.context_policy = policy.cloned();
248 validate_proof_bundle_v2_preflight(
249 bundle,
250 &checked,
251 required_scope,
252 configured_namespace,
253 configured_replay_epoch,
254 configured_verifier_id,
255 now,
256 max_age_seconds,
257 future_skew_seconds,
258 )?;
259 if let Some(hook) = hook {
260 let answer = catch_unwind(AssertUnwindSafe(|| hook(bundle, &checked)));
261 let failure = match answer {
262 Ok(Ok(())) => None,
263 Ok(Err(e)) => Some(e.to_string()),
264 Err(_) => Some("receiver-binding hook panicked".to_string()),
265 };
266 if let Some(message) = failure {
267 return err(
268 V2ErrorClass::ReceiverBindingRejected,
269 format!("v2 receiver-binding hook rejected the presentation: {message}"),
270 );
271 }
272 }
273 let bundle_hash = bundle_hash_v2(bundle)
274 .map_err(|e| e.context("v2 validated bundle hash"))
275 .classify(V2ErrorClass::Malformed)?;
276 let issuer_ids: Vec<String> = bundle
277 .delegations
278 .iter()
279 .map(|c| c.issuer_id.clone())
280 .collect::<BTreeSet<String>>()
281 .into_iter()
282 .collect();
283 let mut state = snapshot_expected_challenge_v2(
284 expected,
285 policy,
286 required_scope,
287 bundle_hash,
288 issuer_ids,
289 max_age_seconds,
290 future_skew_seconds,
291 );
292 let (sealed, refs, timeout) = snapshot_constraint_evaluators_v2(evaluators, bundle);
293 state.evaluators = sealed;
294 state.evaluator_refs = refs;
295 state.evaluator_timeout = timeout;
296 Ok(V2PreflightResult {
297 state: Arc::new(state),
298 })
299}
300
301#[allow(clippy::too_many_arguments)]
306pub fn validate_proof_bundle_v2_preflight(
307 bundle: &ProofBundleV2,
308 expected: &ExpectedChallengeV2,
309 required_scope: &str,
310 configured_namespace: &str,
311 configured_replay_epoch: i64,
312 configured_verifier_id: &str,
313 now: i64,
314 max_age_seconds: i64,
315 future_skew_seconds: i64,
316) -> V2Result<()> {
317 use V2ErrorClass::*;
318 validate_v2_verifier_identity_configuration(configured_namespace, configured_replay_epoch, configured_verifier_id)?;
319 if expected.expected_session_context.as_ref().is_some_and(|c| c.len() != 32) {
320 return err(
321 ConfigurationInvalid,
322 "v2 expected session context must be absent or exactly 32 bytes",
323 );
324 }
325 if let Some(policy) = &expected.context_policy {
326 if !policy.is_valid() {
327 return err(ConfigurationInvalid, "v2 expected context policy is invalid");
328 }
329 if policy.require_bound() {
330 if let Some(ctx) = &expected.expected_session_context {
331 if ctx.as_slice() != policy.expected_session_context_ref() {
332 return err(ConfigurationInvalid, "v2 expected context does not match its policy");
333 }
334 }
335 }
336 if !policy.require_bound() && expected.expected_session_context.is_some() {
337 return err(
338 ConfigurationInvalid,
339 "unbound v2 context policy cannot have an expected session context",
340 );
341 }
342 }
343 if let Err(e) = validate_required_scope_v2(required_scope) {
344 return err(InvalidRequiredScope, format!("v2 request scope: {}", e.message));
345 }
346 verify_proof_bundle_v2_signatures(bundle).map_err(|e| e.context("v2 cryptographic preflight"))?;
347 if expected.verifier_namespace != configured_namespace {
348 return err(NamespaceMismatch, "v2 challenge verifier namespace mismatch");
349 }
350 if !(0..=MAX_SAFE).contains(&configured_replay_epoch)
351 || !(0..=MAX_SAFE).contains(&expected.replay_epoch)
352 || expected.replay_epoch != configured_replay_epoch
353 {
354 return err(StaleReplayEpoch, "v2 challenge replay epoch is stale");
355 }
356 if expected.verifier_id != configured_verifier_id || bundle.verifier_id != configured_verifier_id {
357 return err(
358 VerifierIdMismatch,
359 "v2 challenge or proof verifier ID differs from the configured verifier key ID",
360 );
361 }
362 if expected.value.len() != 32
363 || bundle.challenge != expected.value
364 || bundle.challenge_at != expected.issued_at
365 {
366 return err(
367 ChallengeMismatch,
368 "v2 proof does not match authenticated challenge issuance",
369 );
370 }
371 if !valid_v2_timestamp(expected.issued_at)
372 || !valid_v2_timestamp(expected.expires_at)
373 || expected.expires_at <= expected.issued_at
374 {
375 return err(ConfigurationInvalid, "v2 authenticated challenge time bounds are invalid");
376 }
377 validate_v2_freshness_configuration(now, max_age_seconds, future_skew_seconds)?;
378 if !v2_challenge_time_current(
379 now,
380 expected.issued_at,
381 expected.expires_at,
382 max_age_seconds,
383 future_skew_seconds,
384 ) {
385 return err(
386 ChallengeNotFresh,
387 "v2 challenge is not fresh (future-dated, expired, or beyond maximum age)",
388 );
389 }
390 if expected.expected_agent_id.is_empty() != expected.expected_agent_public_key.is_none() {
391 return err(
392 ConfigurationInvalid,
393 "v2 expected agent ID and public key must be configured together",
394 );
395 }
396 if let Some(key) = &expected.expected_agent_public_key {
397 let id = match key_id_v2(key) {
398 Ok(id) => id,
399 Err(e) => {
400 return err(ConfigurationInvalid, format!("v2 expected agent key: {}", e.message))
401 }
402 };
403 if id != expected.expected_agent_id
404 || bundle.agent_id != id
405 || !equal_keys(&bundle.agent_pub_key, key)
406 {
407 return err(
408 ExpectedAgentMismatch,
409 "v2 presentation does not match authenticated expected agent",
410 );
411 }
412 }
413 if let Some(ctx) = &expected.expected_session_context {
414 if bundle.session_context.as_ref() != Some(ctx) {
415 return err(
416 SessionContextMismatch,
417 "v2 presentation does not match expected session context",
418 );
419 }
420 }
421 check_exact_receiver_audience_v2(bundle, &expected.expected_receiver_id)
422}
423
424pub(crate) fn validate_v2_verifier_identity_configuration(
429 namespace: &str,
430 replay_epoch: i64,
431 verifier_id: &str,
432) -> V2Result<()> {
433 use V2ErrorClass::ConfigurationInvalid;
434 if namespace.is_empty() {
435 return err(ConfigurationInvalid, "v2 configured verifier namespace must not be empty");
436 }
437 if !(0..=MAX_SAFE).contains(&replay_epoch) {
438 return err(
439 ConfigurationInvalid,
440 format!("v2 configured replay epoch must be 0..{MAX_SAFE}"),
441 );
442 }
443 if !valid_v2_id(verifier_id) {
444 return err(
445 ConfigurationInvalid,
446 "v2 configured verifier key ID must be a canonical v2 key ID",
447 );
448 }
449 Ok(())
450}
451
452fn check_exact_receiver_audience_v2(bundle: &ProofBundleV2, receiver_id: &str) -> V2Result<()> {
453 for (i, cert) in bundle.delegations.iter().enumerate() {
454 for constraint in &cert.constraints {
455 if constraint.kind != CONSTRAINT_RECEIVER_AUDIENCE {
456 continue;
457 }
458 if receiver_id.is_empty() {
459 return err(
460 V2ErrorClass::ReceiverAudienceRequired,
461 "v2 receiver audience requires an authenticated expected receiver ID",
462 );
463 }
464 let list = |key: &str| -> Vec<&ParamsValue> {
465 match constraint.params.as_ref().and_then(|p| p.get(key)) {
466 Some(ParamsValue::Array(items)) => items.iter().collect(),
467 _ => Vec::new(),
468 }
469 };
470 let matches = list("exact_receiver_ids")
471 .iter()
472 .any(|v| matches!(v, ParamsValue::Str(id) if id == receiver_id));
473 if list("trust_domain_ids").is_empty() && !matches {
477 return err(
478 V2ErrorClass::ReceiverAudienceMismatch,
479 format!("v2 receiver does not match exact-only audience at delegation {i}"),
480 );
481 }
482 }
483 }
484 Ok(())
485}