Skip to main content

ratify_protocol/v2/
verify.rs

1//! The live Protocol v2 decision path (SPEC-v2 §6). Mirrors Go
2//! `verify_v2.go`.
3
4use std::collections::BTreeMap;
5use std::fmt;
6use std::panic::{catch_unwind, AssertUnwindSafe};
7use std::sync::Arc;
8
9use super::audience::V2AudienceMembership;
10use super::authorization::{
11    evaluate_proof_bundle_v2_local_authorization, interrupt_v2_evaluation, resolve_after_audience_inner,
12    resolve_after_rate_inner, resolve_claim_proof_bundle_v2_after_status, v2_interrupted_assessment,
13    V2DeferredConstraint, V2LocalAuthorizationAssessment, V2LocalAuthorizationOptions,
14};
15use super::claim_store::{
16    claim_proof_bundle_v2_inner, finalize_claim_proof_bundle_v2_inner, terminal_decision_for_v2_evaluation,
17    ClaimStoreV2, FinalizeFailure, V2ChallengeClaim, V2ClaimDisposition,
18    V2RateReservationStore, V2StoreError,
19};
20use super::constraints::{ConstraintContextV2, CONSTRAINT_RECEIVER_AUDIENCE};
21use super::context::V2Context;
22use super::context_policy::V2ContextPolicy;
23use super::crypto::{equal_keys, key_id_v2, valid_v2_id};
24use super::errors::{err, V2Error, V2ErrorClass, V2Result};
25use super::evaluation_progress::{
26    initial_v2_evaluation_progress, receipt_skeleton, record_v2_progress_safely, terminal_result_json,
27    V2EvaluationProgress,
28};
29use super::evaluator::{validate_v2_request_context, ConstraintEvaluatorRegistryV2};
30use super::journal::SecurityJournalStoreV2;
31use super::limits::{validate_v2_freshness_configuration, V2_MAX_FUTURE_SKEW_SECONDS, V2_MAX_STATUS_LIFETIME_SECONDS};
32use super::preflight::{
33    preflight_proof_bundle_v2_inner, validate_v2_verifier_identity_configuration, ExpectedChallengeV2,
34};
35use super::receipt::verification_receipt_v2_body;
36use super::release::CommittedV2Outcome;
37use super::status::RevocationStatusPolicyV2;
38use super::status_provenance::{run_v2_status_stage, V2StatusEvidenceProvider, V2StatusKeyConfig, V2StatusStageInputs};
39use super::wire::{decode_proof_bundle_v2, DelegationCertV2, ProofBundleV2, MAX_SAFE};
40use crate::types::HybridPublicKey;
41
42/// A provider or hook failure (trust, audience, receiver binding). The
43/// message is diagnostic only; the verifier handles every failure fail-closed.
44#[derive(Debug, Clone, PartialEq, Eq)]
45pub struct V2ProviderError {
46    pub message: String,
47}
48
49impl V2ProviderError {
50    pub fn new(message: impl Into<String>) -> Self {
51        V2ProviderError {
52            message: message.into(),
53        }
54    }
55}
56
57impl fmt::Display for V2ProviderError {
58    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59        f.write_str(&self.message)
60    }
61}
62
63impl std::error::Error for V2ProviderError {}
64
65/// A trust provider's answer for one verified chain (SPEC-v2 §6.1).
66#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
67pub enum V2TrustOutcome {
68    /// The chain terminates at the returned configured root.
69    Trusted,
70    /// Trust configuration is available and the chain does not terminate at
71    /// any configured root.
72    Untrusted,
73    /// No trust configuration, or the source is unavailable.
74    Unavailable,
75    /// More than one configured candidate matches, or the resolver cannot
76    /// decide uniquely. Never becomes trusted.
77    Ambiguous,
78}
79
80impl V2TrustOutcome {
81    /// `trusted`, `untrusted`, `unavailable`, or `ambiguous`.
82    pub fn as_str(self) -> &'static str {
83        match self {
84            V2TrustOutcome::Trusted => "trusted",
85            V2TrustOutcome::Untrusted => "untrusted",
86            V2TrustOutcome::Unavailable => "unavailable",
87            V2TrustOutcome::Ambiguous => "ambiguous",
88        }
89    }
90
91    /// Parse one of the four spellings.
92    pub fn parse(text: &str) -> Option<Self> {
93        Some(match text {
94            "trusted" => V2TrustOutcome::Trusted,
95            "untrusted" => V2TrustOutcome::Untrusted,
96            "unavailable" => V2TrustOutcome::Unavailable,
97            "ambiguous" => V2TrustOutcome::Ambiguous,
98            _ => return None,
99        })
100    }
101}
102
103/// The caller-authenticated trust provider result. `root_key` is the
104/// complete root public key for `Trusted`; the verifier recomputes its key
105/// ID and requires it and the key to equal the chain's terminal issuer,
106/// treating a mismatch as ambiguous. Unavailable, ambiguous, an error, or a
107/// panic yields indeterminate/trust_unavailable.
108#[derive(Debug, Clone, PartialEq, Eq)]
109pub struct V2TrustResolution {
110    pub outcome: V2TrustOutcome,
111    pub root_key: HybridPublicKey,
112}
113
114impl V2TrustResolution {
115    fn unavailable() -> Self {
116        V2TrustResolution {
117            outcome: V2TrustOutcome::Unavailable,
118            root_key: HybridPublicKey {
119                ed25519: Vec::new(),
120                ml_dsa_65: Vec::new(),
121            },
122        }
123    }
124}
125
126/// The application's pure pre-consumption hook. It runs after the built-in
127/// expected-agent, session-context and exact-audience checks and before the
128/// claim. It must not perform I/O or have side effects.
129pub type V2ReceiverBindingHook =
130    Arc<dyn Fn(&ProofBundleV2, &ExpectedChallengeV2) -> Result<(), V2ProviderError> + Send + Sync>;
131
132/// The trust provider, selected by authenticated configuration; it never
133/// follows a location or identifier taken from the proof.
134pub type V2TrustProvider =
135    Arc<dyn Fn(&V2Context, &[DelegationCertV2]) -> Result<V2TrustResolution, V2ProviderError> + Send + Sync>;
136
137/// The receiver-audience membership provider.
138pub type V2AudienceProvider = Arc<
139    dyn Fn(&V2Context, &[V2DeferredConstraint], &str) -> Result<Vec<V2AudienceMembership>, V2ProviderError>
140        + Send
141        + Sync,
142>;
143
144/// The verifier-owned dependencies of the live v2 decision path.
145/// `claim_store` is required. A callback that returns an error or panics is
146/// handled fail-closed: trust -> trust_unavailable, status -> unavailable
147/// for that issuer, audience -> constraint_unverifiable, rate ->
148/// constraint_unverifiable. If the caller's context has ended when a
149/// callback fails, nothing is committed (evaluation_cancelled) and the claim
150/// remains in progress for lease-expiry recovery.
151#[derive(Clone, Default)]
152pub struct V2VerifyCallbacks {
153    pub receiver_binding: Option<V2ReceiverBindingHook>,
154    pub claim_store: Option<Arc<dyn ClaimStoreV2>>,
155    pub trust: Option<V2TrustProvider>,
156    /// A bounded batch of signed status objects for one issuer; never a
157    /// status result.
158    pub status_evidence: Option<V2StatusEvidenceProvider>,
159    /// The rollback-protected, anchored security journal the evidence is
160    /// applied to. Without it every status is unavailable.
161    pub status_journal: Option<Arc<dyn SecurityJournalStoreV2>>,
162    pub audience: Option<V2AudienceProvider>,
163    pub rate: Option<Arc<dyn V2RateReservationStore>>,
164}
165
166impl fmt::Debug for V2VerifyCallbacks {
167    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168        f.debug_struct("V2VerifyCallbacks")
169            .field("receiver_binding", &self.receiver_binding.is_some())
170            .field("claim_store", &self.claim_store.is_some())
171            .field("trust", &self.trust.is_some())
172            .field("status_evidence", &self.status_evidence.is_some())
173            .field("status_journal", &self.status_journal.is_some())
174            .field("audience", &self.audience.is_some())
175            .field("rate", &self.rate.is_some())
176            .finish()
177    }
178}
179
180/// One live verification. `context_policy: None` means the verifier
181/// explicitly configured no context policy; the terminal result can then
182/// never be allow (SPEC-v2 §6.7). `now` is the caller's clock and is used
183/// only for the pre-claim freshness check; every post-claim time-sensitive
184/// check uses the claim store's authoritative time.
185#[derive(Debug, Clone, Default)]
186pub struct V2VerifyRequest {
187    pub bundle: Vec<u8>,
188    pub expected: Option<ExpectedChallengeV2>,
189    pub context_policy: Option<V2ContextPolicy>,
190    pub required_scope: String,
191    pub verifier_namespace: String,
192    pub replay_epoch: i64,
193    /// The caller-authenticated verifier key ID (SPEC-v2 §2.4, §6.1).
194    /// Required: an empty or non-canonical value is `configuration_invalid`
195    /// before the ExpectedChallenge is examined, and both the
196    /// ExpectedChallenge and the proof bundle must name it
197    /// (`verifier_id_mismatch` otherwise).
198    pub verifier_id: String,
199    pub now: i64,
200    pub max_challenge_age_seconds: i64,
201    pub future_skew_seconds: i64,
202    pub context: ConstraintContextV2,
203    /// The configured IANA tzdata release for `time_window`; it must equal
204    /// [`super::TZDB_VERSION_V2`].
205    pub tzdb_version: String,
206    pub status_keys: BTreeMap<String, V2StatusKeyConfig>,
207    pub status_policy: RevocationStatusPolicyV2,
208    /// The caller-authenticated extension evaluator registry; `None`
209    /// registers none, so every extension type is constraint_unknown.
210    pub constraint_evaluators: Option<ConstraintEvaluatorRegistryV2>,
211}
212
213/// Where a verification stopped.
214#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
215pub enum V2VerifyStage {
216    /// A pre-claim failure. No challenge was consumed, no
217    /// trust/status/policy callback ran, and no Protocol receipt exists.
218    Preflight,
219    /// Preflight passed but the claim already existed. The result is not
220    /// disclosed and no evaluation callback ran.
221    Replay,
222    /// The claim was created but nothing was committed. The claim stays in
223    /// progress for lease-expiry recovery.
224    Evaluating,
225    /// A terminal Protocol result and its receipt outbox body were
226    /// committed. A committed outcome is NOT actionable; only
227    /// [`super::release_v2_decision`] produces an actionable decision.
228    Committed,
229}
230
231impl V2VerifyStage {
232    /// `preflight`, `replay`, `evaluating`, or `committed`.
233    pub fn as_str(self) -> &'static str {
234        match self {
235            V2VerifyStage::Preflight => "preflight",
236            V2VerifyStage::Replay => "replay",
237            V2VerifyStage::Evaluating => "evaluating",
238            V2VerifyStage::Committed => "committed",
239        }
240    }
241}
242
243/// The result of [`verify_proof_bundle_v2`]. It deliberately has no
244/// decision field: for `Committed`, `committed` is the opaque handoff to
245/// [`super::release_v2_decision`]. `error` (and `error_class`) is present
246/// exactly for `Preflight` and `Evaluating` (Go returns the error itself only
247/// for `Evaluating`).
248#[derive(Debug)]
249pub struct V2VerifyOutcome {
250    pub stage: V2VerifyStage,
251    pub error: Option<V2Error>,
252    pub error_class: Option<V2ErrorClass>,
253    pub disposition: Option<V2ClaimDisposition>,
254    pub claim: V2ChallengeClaim,
255    pub committed: Option<CommittedV2Outcome>,
256}
257
258/// The evaluator's progress: `persisted` is exactly what was last recorded
259/// in the claim store; `trust_completed` notes that trust resolution ran.
260struct EvaluationProgress {
261    persisted: V2EvaluationProgress,
262    trust_completed: bool,
263}
264
265/// Go `VerifyProofBundleV2`: the live decision path in the SPEC-v2 §6
266/// order. A pre-claim failure returns `Preflight` with a classified error
267/// and invokes no claim, trust, status, audience, or rate callback. A
268/// committed outcome is never an authorization.
269pub fn verify_proof_bundle_v2(ctx: &V2Context, req: &V2VerifyRequest, cb: &V2VerifyCallbacks) -> V2VerifyOutcome {
270    let preflight_failure = |e: V2Error| V2VerifyOutcome {
271        stage: V2VerifyStage::Preflight,
272        error_class: Some(e.class),
273        error: Some(e),
274        disposition: None,
275        claim: V2ChallengeClaim::default(),
276        committed: None,
277    };
278    // SPEC-v2 §6.2 step 1 (bounded strict decode), then step 2
279    // (configuration, including the claim store). No callback runs before
280    // both pass.
281    let bundle = match decode_proof_bundle_v2(&req.bundle) {
282        Ok(b) => b,
283        Err(e) => return preflight_failure(e),
284    };
285    let Some(store) = cb.claim_store.as_deref() else {
286        return preflight_failure(V2Error::new(
287            V2ErrorClass::ConfigurationInvalid,
288            "v2 verification requires a context and claim store",
289        ));
290    };
291    if let Err(e) = validate_v2_verify_configuration(req) {
292        return preflight_failure(e);
293    }
294    let preflight = match preflight_proof_bundle_v2_inner(
295        &bundle,
296        req.expected.as_ref(),
297        req.context_policy.as_ref(),
298        true,
299        cb.receiver_binding.as_ref(),
300        req.constraint_evaluators.as_ref(),
301        &req.required_scope,
302        &req.verifier_namespace,
303        req.replay_epoch,
304        &req.verifier_id,
305        req.now,
306        req.max_challenge_age_seconds,
307        req.future_skew_seconds,
308    ) {
309        Ok(p) => p,
310        Err(e) => return preflight_failure(e),
311    };
312    let claimed = catch_unwind(AssertUnwindSafe(|| {
313        claim_proof_bundle_v2_inner(ctx, store, &bundle, &preflight, &req.verifier_namespace, req.replay_epoch, req.now)
314    }))
315    .unwrap_or_else(|_| Err(V2Error::new(V2ErrorClass::ClaimStoreUnavailable, "claim store panicked")));
316    let (claim, disposition, token) = match claimed {
317        Ok(c) => c,
318        Err(e) => return preflight_failure(e.classify(V2ErrorClass::ClaimStoreUnavailable)),
319    };
320    let token = match (disposition, token) {
321        (V2ClaimDisposition::Created, Some(token)) => token,
322        (V2ClaimDisposition::Created, None) => {
323            return preflight_failure(V2Error::new(
324                V2ErrorClass::ClaimStoreUnavailable,
325                "v2 claim store created a claim without an evaluator capability",
326            ))
327        }
328        _ => {
329            return V2VerifyOutcome {
330                stage: V2VerifyStage::Replay,
331                error: None,
332                error_class: None,
333                disposition: Some(disposition),
334                claim,
335                committed: None,
336            }
337        }
338    };
339    let evaluating = |claim: &V2ChallengeClaim, e: V2Error| V2VerifyOutcome {
340        stage: V2VerifyStage::Evaluating,
341        error_class: Some(e.class),
342        error: Some(e),
343        disposition: Some(disposition),
344        claim: claim.clone(),
345        committed: None,
346    };
347    let cancelled = |claim: &V2ChallengeClaim| {
348        evaluating(
349            claim,
350            V2Error::new(
351                V2ErrorClass::EvaluationCancelled,
352                "v2 evaluation cancelled before commit: context done",
353            ),
354        )
355    };
356
357    let mut progress = EvaluationProgress {
358        persisted: initial_v2_evaluation_progress(),
359        trust_completed: false,
360    };
361    // Persist progress before an external lookup starts and after it
362    // completes (SPEC-v2 §7.5). A failed write stops evaluation before the
363    // next provider call.
364    let record = |p: &V2EvaluationProgress| -> V2Result<()> {
365        record_v2_progress_safely(ctx, store, &token, p).map_err(|e| {
366            if ctx.is_done() {
367                V2Error::new(
368                    V2ErrorClass::EvaluationCancelled,
369                    "v2 evaluation cancelled before commit: context done",
370                )
371            } else {
372                e
373            }
374        })
375    };
376    let mut opts = V2LocalAuthorizationOptions {
377        future_skew_seconds: req.future_skew_seconds,
378        required_scope: req.required_scope.clone(),
379        context: req.context.clone(),
380        tzdb_version: req.tzdb_version.clone(),
381        context_policy: req.context_policy.clone(),
382        expected_challenge: req.expected.clone(),
383        claim_token: Some(token.clone()),
384        ..Default::default()
385    };
386    // The claim's own consistency is checked before trust; an inconsistent
387    // claim is interrupted with every assessment not_evaluated.
388    if token.state.claim_time_valid {
389        if let Some(root) = bundle.delegations.last() {
390            progress.persisted.trust_assessment = "unavailable".into(); // resolution started
391            if let Err(e) = record(&progress.persisted) {
392                return evaluating(&claim, e);
393            }
394            let resolution = call_v2_trust_safely(ctx, cb.trust.as_ref(), &bundle.delegations);
395            if resolution.is_err() && ctx.is_done() {
396                return cancelled(&claim);
397            }
398            let mut trust = "unavailable";
399            if let Ok(resolution) = resolution {
400                match resolution.outcome {
401                    V2TrustOutcome::Trusted => {
402                        if let Ok(root_id) = key_id_v2(&resolution.root_key) {
403                            if root_id == root.issuer_id && equal_keys(&resolution.root_key, &root.issuer_pub_key) {
404                                trust = "trusted";
405                                opts.trusted_root_id = root_id;
406                                opts.trusted_root_key = resolution.root_key.clone();
407                            }
408                        }
409                    }
410                    // Configured trust that excludes this chain: the local
411                    // evaluation compares against an empty root and denies.
412                    V2TrustOutcome::Untrusted => trust = "untrusted",
413                    V2TrustOutcome::Unavailable | V2TrustOutcome::Ambiguous => {}
414                }
415            }
416            opts.trust_configured = trust != "unavailable";
417            progress.trust_completed = true;
418            progress.persisted.trust_assessment = trust.into();
419        }
420    }
421    let mut assessment = evaluate_proof_bundle_v2_local_authorization(&bundle, &opts);
422    let claimed_at = token.state.claimed_at;
423    if progress.trust_completed {
424        if progress.persisted.trust_assessment == "trusted"
425            && (assessment.context_assessment == "bound" || assessment.context_assessment == "not_required")
426        {
427            if let Some(digest) = &assessment.context_policy_digest {
428                progress.persisted.context_assessment = assessment.context_assessment.clone();
429                progress.persisted.context_policy_digest = Some(digest.clone());
430            }
431        }
432        if assessment.status == "pending_external_checks" {
433            progress.persisted.status_assessment = "unavailable".into(); // status started
434        }
435        if let Err(e) = record(&progress.persisted) {
436            return evaluating(&claim, e);
437        }
438    }
439
440    if assessment.status == "pending_external_checks" {
441        let inputs = V2StatusStageInputs {
442            status_evidence: cb.status_evidence.as_ref(),
443            status_journal: cb.status_journal.as_deref(),
444            status_keys: &req.status_keys,
445            status_policy: &req.status_policy,
446        };
447        let stage = run_v2_status_stage(ctx, &bundle, &assessment.status_checks, &inputs, claimed_at);
448        if stage.cancelled {
449            return cancelled(&claim);
450        }
451        progress.persisted.status_assessment = stage.assessment.assessment.clone();
452        progress.persisted.status_evidence = stage.assessment.evidence.clone();
453        if let Err(e) = record(&progress.persisted) {
454            return evaluating(&claim, e);
455        }
456        let status_assessment = stage.assessment;
457        match resolve_claim_proof_bundle_v2_after_status(&token, |_| Ok(status_assessment)) {
458            Ok(resolved) => assessment = resolved,
459            Err(_) => {
460                interrupt_v2_evaluation(&token);
461                assessment = v2_interrupted_assessment("evaluation interrupted after status");
462            }
463        }
464    }
465    if assessment.status == "pending_external_checks"
466        && assessment.deferred.iter().any(|d| d.kind == CONSTRAINT_RECEIVER_AUDIENCE)
467    {
468        let audience_deferred: Vec<V2DeferredConstraint> = assessment
469            .deferred
470            .iter()
471            .filter(|d| d.kind == CONSTRAINT_RECEIVER_AUDIENCE)
472            .cloned()
473            .collect();
474        let receiver_id = req
475            .expected
476            .as_ref()
477            .map(|e| e.expected_receiver_id.clone())
478            .unwrap_or_default();
479        let memberships = match call_v2_audience_safely(ctx, cb.audience.as_ref(), &audience_deferred, &receiver_id) {
480            Ok(m) => m,
481            Err(_) => {
482                if ctx.is_done() {
483                    return cancelled(&claim);
484                }
485                Vec::new()
486            }
487        };
488        match resolve_after_audience_inner(&token, &memberships) {
489            Ok(resolved) => assessment = resolved,
490            Err(_) => {
491                interrupt_v2_evaluation(&token);
492                assessment = v2_interrupted_assessment("evaluation interrupted after audience");
493            }
494        }
495    }
496    if assessment.status == "pending_external_checks" {
497        if ctx.is_done() {
498            return cancelled(&claim);
499        }
500        match resolve_after_rate_inner(ctx, cb.rate.as_deref(), &token) {
501            Ok(resolved) => assessment = resolved,
502            Err(_) => {
503                if ctx.is_done() {
504                    return cancelled(&claim);
505                }
506                interrupt_v2_evaluation(&token);
507                assessment = v2_interrupted_assessment("evaluation interrupted after rate");
508            }
509        }
510    }
511
512    // The claim store reads T_final inside the finalization compare-and-set
513    // and rejects a regressed clock or an allow at or beyond its horizon or
514    // the challenge expiry; nothing is then committed (SPEC-v2 §7.2, §7.5).
515    for attempt in 0..2 {
516        let (decision, terminal, body) = match build_v2_terminal_result(&bundle, &assessment, &progress, &claim, claimed_at) {
517            Ok(t) => t,
518            Err(e) => return evaluating(&claim, e),
519        };
520        let finalized = catch_unwind(AssertUnwindSafe(|| {
521            finalize_claim_proof_bundle_v2_inner(ctx, store, &token, &terminal, &body)
522        }))
523        .unwrap_or_else(|_| Err(FinalizeFailure::Own(V2Error::plain("claim store finalization panicked"))));
524        let (rate_limited, finalize_err) = match finalized {
525            Ok(_) => {
526                let horizon = if decision == "allow" { token.state.allow_horizon() } else { 0 };
527                return V2VerifyOutcome {
528                    stage: V2VerifyStage::Committed,
529                    error: None,
530                    error_class: None,
531                    disposition: Some(disposition),
532                    claim: claim.clone(),
533                    committed: Some(CommittedV2Outcome::new(&claim, &body, horizon)),
534                };
535            }
536            Err(FinalizeFailure::Own(e)) => (false, e),
537            Err(FinalizeFailure::Store(e)) => (matches!(e, V2StoreError::RateLimitExceeded), e.into_v2()),
538        };
539        let finalize_err = finalize_err.classify(V2ErrorClass::ClaimStoreUnavailable);
540        if ctx.is_done() {
541            return cancelled(&claim);
542        }
543        if !rate_limited || attempt > 0 {
544            return evaluating(&claim, finalize_err);
545        }
546        // A barrier store proved definitive capacity exhaustion and rolled
547        // back; the same claim finalizes once as constraint_denied.
548        assessment.status = "constraint_denied".into();
549        assessment.reason = "constraint_denied".into();
550        assessment.detail = "signed rate limit has no remaining capacity".into();
551    }
552    evaluating(
553        &claim,
554        V2Error::new(V2ErrorClass::ClaimStoreUnavailable, "v2 terminal finalization did not complete"),
555    )
556}
557
558/// Go `validateV2VerifyConfiguration`: out-of-bounds configuration and an
559/// invalid supplied request context are rejected before claim.
560fn validate_v2_verify_configuration(req: &V2VerifyRequest) -> V2Result<()> {
561    validate_v2_freshness_configuration(req.now, req.max_challenge_age_seconds, req.future_skew_seconds)?;
562    validate_v2_verifier_identity_configuration(&req.verifier_namespace, req.replay_epoch, &req.verifier_id)?;
563    // The live verifier has one future skew (SPEC-v2 §6.1): status freshness
564    // uses future_skew_seconds, so a status policy carrying another skew is a
565    // configuration error rather than a second, silently different bound.
566    if req.status_policy.clock_skew_seconds != req.future_skew_seconds {
567        return err(
568            V2ErrorClass::ConfigurationInvalid,
569            "v2 status policy skew must equal future_skew_seconds",
570        );
571    }
572    validate_v2_request_context(&req.context)?;
573    validate_v2_status_configuration(&req.status_keys, &req.status_policy)
574}
575
576/// Go `validateV2StatusConfiguration`: the caller-authenticated status
577/// policy bounds and status-key configuration (SPEC-v2 §2.5, §6.5).
578pub(crate) fn validate_v2_status_configuration(
579    keys: &BTreeMap<String, V2StatusKeyConfig>,
580    policy: &RevocationStatusPolicyV2,
581) -> V2Result<()> {
582    if !(1..=V2_MAX_STATUS_LIFETIME_SECONDS).contains(&policy.max_list_lifetime_seconds)
583        || !(1..=V2_MAX_STATUS_LIFETIME_SECONDS).contains(&policy.max_status_age_seconds)
584        || !(0..=V2_MAX_FUTURE_SKEW_SECONDS).contains(&policy.clock_skew_seconds)
585    {
586        return err(
587            V2ErrorClass::ConfigurationInvalid,
588            format!(
589                "v2 status policy must bound list lifetime and status age to 1..{V2_MAX_STATUS_LIFETIME_SECONDS} seconds and skew to 0..{V2_MAX_FUTURE_SKEW_SECONDS}"
590            ),
591        );
592    }
593    for (issuer_id, config) in keys {
594        if !valid_v2_id(issuer_id) || config.epoch == 0 || config.epoch > MAX_SAFE as u64 {
595            return err(
596                V2ErrorClass::ConfigurationInvalid,
597                "v2 status-key configuration has an invalid issuer or epoch",
598            );
599        }
600        if let Err(e) = key_id_v2(&config.key) {
601            return err(
602                V2ErrorClass::ConfigurationInvalid,
603                format!("v2 status-key configuration has an invalid key: {}", e.message),
604            );
605        }
606    }
607    Ok(())
608}
609
610/// Go `buildV2TerminalResult`: map a terminal assessment to the receipt
611/// tuple of SPEC-v2 §5.8 and the §6.7 table and validate it by preparing the
612/// exact receipt outbox body. `verified_at` is the authoritative claim time.
613/// Returns `(decision, terminal_result, receipt_body)`.
614fn build_v2_terminal_result(
615    bundle: &ProofBundleV2,
616    assessment: &V2LocalAuthorizationAssessment,
617    progress: &EvaluationProgress,
618    claim: &V2ChallengeClaim,
619    verified_at: i64,
620) -> V2Result<(&'static str, Vec<u8>, Vec<u8>)> {
621    let Some(decision) = terminal_decision_for_v2_evaluation(&assessment.status, &assessment.reason) else {
622        return Err(V2Error::plain(format!(
623            "v2 evaluation did not reach a terminal result: {}/{}",
624            assessment.status, assessment.reason
625        )));
626    };
627    let mut trust = progress.persisted.trust_assessment.clone();
628    let mut status_assessment = if assessment.status_assessment.is_empty() {
629        "not_evaluated".to_string()
630    } else {
631        assessment.status_assessment.clone()
632    };
633    let mut context_assessment = if assessment.context_assessment.is_empty() {
634        "not_evaluated".to_string()
635    } else {
636        assessment.context_assessment.clone()
637    };
638    let mut evidence = assessment.status_evidence.clone();
639    if assessment.reason == "not_delegated" {
640        trust = "not_evaluated".into();
641    }
642    if status_assessment == "not_evaluated" {
643        evidence = Vec::new();
644    }
645    let mut policy_digest = if context_assessment != "not_evaluated" && context_assessment != "unbound" {
646        assessment.context_policy_digest.clone()
647    } else {
648        None
649    };
650    if assessment.reason == "evaluation_interrupted" {
651        // Per-dimension progress, exactly as lease-expiry recovery reports it.
652        let p = progress.persisted.clone();
653        trust = p.trust_assessment;
654        status_assessment = p.status_assessment;
655        context_assessment = p.context_assessment;
656        policy_digest = p.context_policy_digest;
657        evidence = p.status_evidence;
658    }
659    let mut granted = Vec::new();
660    if decision == "allow" {
661        granted = assessment.effective_scope.clone();
662        granted.sort();
663        granted.dedup();
664    }
665    let mut receipt = receipt_skeleton();
666    receipt.verifier_id = bundle.verifier_id.clone();
667    receipt.agent_id = bundle.agent_id.clone();
668    receipt.bundle_hash = claim.bundle_hash.clone();
669    receipt.issuer_ids = claim.issuer_ids.clone();
670    receipt.decision = decision.into();
671    receipt.decision_reason = assessment.reason.clone();
672    receipt.identity_status = assessment.status.clone();
673    receipt.trust_assessment = trust;
674    receipt.status_assessment = status_assessment;
675    receipt.challenge_assessment = "current".into();
676    receipt.context_assessment = context_assessment;
677    receipt.context_policy_digest = policy_digest;
678    receipt.verified_at = verified_at;
679    receipt.required_scope = claim.required_scope.clone();
680    receipt.granted_scope = granted;
681    receipt.status_evidence = evidence;
682    receipt.constraint_evaluators = claim.constraint_evaluators.clone();
683    let body = verification_receipt_v2_body(&receipt)
684        .map_err(|e| e.context("v2 terminal receipt body is inconsistent with the evaluated result"))?;
685    let terminal = terminal_result_json(decision, &assessment.reason, &assessment.status)?;
686    Ok((decision, terminal, body))
687}
688
689// ---------------------------------------------------------------------------
690// Fail-closed callback adapters. A panic is treated exactly like an error.
691
692/// Go `callV2TrustSafely`: a missing provider answers unavailable.
693pub(crate) fn call_v2_trust_safely(
694    ctx: &V2Context,
695    trust: Option<&V2TrustProvider>,
696    chain: &[DelegationCertV2],
697) -> Result<V2TrustResolution, V2ProviderError> {
698    let Some(trust) = trust else {
699        return Ok(V2TrustResolution::unavailable());
700    };
701    let chain = chain.to_vec();
702    catch_unwind(AssertUnwindSafe(|| trust(ctx, &chain)))
703        .unwrap_or_else(|_| Err(V2ProviderError::new("trust resolver panicked")))
704}
705
706fn call_v2_audience_safely(
707    ctx: &V2Context,
708    audience: Option<&V2AudienceProvider>,
709    deferred: &[V2DeferredConstraint],
710    receiver_id: &str,
711) -> Result<Vec<V2AudienceMembership>, V2ProviderError> {
712    let Some(audience) = audience else {
713        return Ok(Vec::new());
714    };
715    catch_unwind(AssertUnwindSafe(|| audience(ctx, deferred, receiver_id)))
716        .unwrap_or_else(|_| Err(V2ProviderError::new("audience provider panicked")))
717}