Skip to main content

ratify_protocol/v2/
authorization.rs

1//! Post-claim local authorization and the ordered post-status stages
2//! (SPEC-v2 §5.2, §6.3 to §6.7). Mirrors Go `authorization_v2.go` and
3//! `evaluateConstraintV2` / `loadV2TimeZone` from `constraints_v2.go`.
4
5use std::sync::atomic::Ordering;
6use std::sync::Arc;
7
8use super::audience::{evaluate_receiver_audience_inner, V2AudienceMembership};
9use super::claim_store::{TokenState, V2EvaluationToken, V2RateReservationStore, V2StoreError};
10use super::constraints::{
11    is_registered_constraint_type_v2, parse_hhmm_v2, valid_iso4217_alpha_v2, ConstraintContextV2,
12    ConstraintV2, CONSTRAINT_MAX_AMOUNT, CONSTRAINT_MAX_RATE, CONSTRAINT_RECEIVER_AUDIENCE,
13    CONSTRAINT_RESOURCE_PATH, CONSTRAINT_TIME_WINDOW,
14};
15use super::context::V2Context;
16use super::context_policy::{evaluate_proof_bundle_v2_context_policy, same_v2_context_policy, V2ContextPolicy};
17use super::crypto::equal_keys;
18use super::errors::{plain, V2Error, V2ErrorClass, V2Result};
19use super::evaluator::{
20    extension_params_json_v2, run_constraint_evaluator_v2, ConstraintEvaluationInputV2, ConstraintFailure,
21};
22use super::limits::{checked_add_v2, valid_v2_timestamp, V2_MAX_DELEGATION_LIFETIME_SECONDS, V2_MAX_TIMESTAMP_SECONDS};
23use super::operation_context::protocol_claim_id_v2;
24use super::preflight::{matches_expected_challenge_v2, ExpectedChallengeStateV2, ExpectedChallengeV2};
25use super::rate_reservation::build_v2_rate_reservation_batch_inner;
26use super::receipt::StatusEvidenceEntryV2;
27use super::status::{V2CertificateStatusCheck, V2StatusAssessment};
28use super::tzdb::{civil_from_unix, load_zone, unix_from_civil_utc, Zone, TZDB_VERSION};
29use super::wire::{bundle_hash_v2, validate_required_scope_v2, validate_scopes_v2, verify_proof_bundle_v2_signatures, ProofBundleV2, MAX_SAFE};
30use crate::resource_path::{normalize_resource_path, resource_path_matches};
31use crate::scope::{intersect_scopes, SCOPE_IDENTITY_DELEGATE};
32use crate::types::HybridPublicKey;
33
34/// The IANA tzdata release embedded in this crate and used for every
35/// `time_window` evaluation (SPEC-v2 §5.2; Go `TZDBVersionV2`). A verifier
36/// configures the release it requires; any other configured value, or none,
37/// makes every `time_window` constraint_unverifiable.
38pub const TZDB_VERSION_V2: &str = TZDB_VERSION;
39
40/// Verifier-owned inputs for the deterministic authorization checks that
41/// follow a successful challenge claim. There is no caller-supplied
42/// evaluation time: every time-sensitive check uses the claim store's
43/// authoritative claim time sealed in `claim_token`. `future_skew_seconds`
44/// must equal the value sealed at claim.
45#[derive(Debug, Clone)]
46pub struct V2LocalAuthorizationOptions {
47    pub future_skew_seconds: i64,
48    pub required_scope: String,
49    pub trusted_root_id: String,
50    pub trusted_root_key: HybridPublicKey,
51    pub trust_configured: bool,
52    pub context: ConstraintContextV2,
53    /// The caller-configured IANA tzdata release required for `time_window`;
54    /// it must equal [`TZDB_VERSION_V2`].
55    pub tzdb_version: String,
56    pub context_policy: Option<V2ContextPolicy>,
57    pub expected_challenge: Option<ExpectedChallengeV2>,
58    pub claim_token: Option<V2EvaluationToken>,
59}
60
61impl Default for V2LocalAuthorizationOptions {
62    fn default() -> Self {
63        V2LocalAuthorizationOptions {
64            future_skew_seconds: 0,
65            required_scope: String::new(),
66            trusted_root_id: String::new(),
67            trusted_root_key: HybridPublicKey {
68                ed25519: Vec::new(),
69                ml_dsa_65: Vec::new(),
70            },
71            trust_configured: false,
72            context: ConstraintContextV2::default(),
73            tzdb_version: String::new(),
74            context_policy: None,
75            expected_challenge: None,
76            claim_token: None,
77        }
78    }
79}
80
81/// An intermediate result, not a terminal authorization decision. Callers
82/// must still evaluate issuer status and any deferred checks before an
83/// action can be allowed.
84#[derive(Debug, Clone, PartialEq, Eq, Default)]
85pub struct V2LocalAuthorizationAssessment {
86    /// Copied from the sealed preflight state so a terminal receipt remains
87    /// bound to the claimed proof after a mismatch.
88    pub bundle_hash: String,
89    pub issuer_ids: Vec<String>,
90    pub agent_id: String,
91    pub root_id: String,
92    pub required_scope: String,
93    pub delegation_digest: Vec<u8>,
94    pub effective_scope: Vec<String>,
95    pub context_assessment: String,
96    pub context_policy_digest: Option<String>,
97    pub status_assessment: String,
98    pub delegation_valid_until: i64,
99    pub local_time_valid_until: i64,
100    pub extension_valid_until: i64,
101    pub status_fresh_until: i64,
102    pub audience_fresh_until: i64,
103    pub status_evidence: Vec<StatusEvidenceEntryV2>,
104    pub audience_evidence_digests: Vec<String>,
105    pub rate_store_unavailable: bool,
106    pub rate_admission_deferred: bool,
107    pub status_checks: Vec<V2CertificateStatusCheck>,
108    pub deferred: Vec<V2DeferredConstraint>,
109    pub local_policy_failure: Option<V2LocalPolicyFailure>,
110    pub status: String,
111    pub reason: String,
112    pub detail: String,
113}
114
115/// A pure local verdict that must not become terminal until every
116/// authenticated chain CertificateRef has completed status evaluation.
117#[derive(Debug, Clone, PartialEq, Eq, Default)]
118pub struct V2LocalPolicyFailure {
119    pub status: String,
120    pub reason: String,
121    pub detail: String,
122}
123
124/// A constraint requiring the ordered status, membership, or
125/// rate-reservation stage.
126#[derive(Debug, Clone, PartialEq, Eq, Default)]
127pub struct V2DeferredConstraint {
128    pub delegation_index: usize,
129    pub constraint_index: usize,
130    pub issuer_id: String,
131    pub cert_id: String,
132    pub kind: String,
133    pub canonical_json: Vec<u8>,
134}
135
136fn v2_local_assessment(status: &str, reason: &str, scope: Vec<String>, detail: &str) -> V2LocalAuthorizationAssessment {
137    V2LocalAuthorizationAssessment {
138        effective_scope: scope,
139        context_assessment: "not_evaluated".into(),
140        status: status.into(),
141        reason: reason.into(),
142        detail: detail.into(),
143        ..Default::default()
144    }
145}
146
147/// Go `v2InterruptedAssessment`.
148pub(crate) fn v2_interrupted_assessment(detail: &str) -> V2LocalAuthorizationAssessment {
149    v2_local_assessment("authorization_unverified", "evaluation_interrupted", Vec::new(), detail)
150}
151
152/// Go `EvaluateProofBundleV2LocalAuthorization`: trust-root binding,
153/// delegation times, effective scope, and deterministic constraints. The
154/// caller must invoke it only after preflight and atomic challenge claim. It
155/// performs no status lookup, rate reservation, or other external call
156/// (extension evaluators sealed at preflight are pure).
157pub fn evaluate_proof_bundle_v2_local_authorization(
158    bundle: &ProofBundleV2,
159    opts: &V2LocalAuthorizationOptions,
160) -> V2LocalAuthorizationAssessment {
161    let (mut assessment, started) = evaluate_local_inner(bundle, opts);
162    if let Some(token) = &opts.claim_token {
163        let state = &token.state;
164        assessment.bundle_hash = state.expected.bundle_hash.clone();
165        assessment.issuer_ids = state.expected.issuer_ids.clone();
166        if started && !assessment.status.is_empty() {
167            let mut m = state.lock();
168            m.evaluation_status = assessment.status.clone();
169            m.evaluation_reason = assessment.reason.clone();
170            if assessment.status == "pending_external_checks" {
171                m.pending_assessment = Some(assessment.clone());
172            }
173            state.evaluation_complete.store(true, Ordering::SeqCst);
174        }
175    }
176    assessment
177}
178
179fn evaluate_local_inner(
180    bundle: &ProofBundleV2,
181    opts: &V2LocalAuthorizationOptions,
182) -> (V2LocalAuthorizationAssessment, bool) {
183    let Some(token) = &opts.claim_token else {
184        return (
185            v2_local_assessment(
186                "preflight_binding_mismatch",
187                "claim_required",
188                Vec::new(),
189                "local authorization requires a successful atomic challenge claim",
190            ),
191            false,
192        );
193    };
194    let state: &TokenState = &token.state;
195    let expected: &ExpectedChallengeStateV2 = &state.expected;
196    let claim_id = protocol_claim_id_v2(&expected.verifier_namespace, expected.replay_epoch, &expected.value);
197    if claim_id.as_deref().ok() != Some(state.claim_id.as_str())
198        || state.proof_digest != expected.bundle_hash
199        || state.owner_token.len() != 32
200    {
201        return (
202            v2_interrupted_assessment("local authorization state differs from successful preflight or atomic claim"),
203            false,
204        );
205    }
206    if state
207        .used
208        .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
209        .is_err()
210    {
211        return (
212            v2_local_assessment(
213                "evaluation_in_progress",
214                "claim_in_progress",
215                Vec::new(),
216                "the claim's single evaluation token has already been used",
217            ),
218            false,
219        );
220    }
221    let a = evaluate_local_started(bundle, opts, state, expected);
222    (a, true)
223}
224
225fn evaluate_local_started(
226    bundle: &ProofBundleV2,
227    opts: &V2LocalAuthorizationOptions,
228    state: &TokenState,
229    expected: &ExpectedChallengeStateV2,
230) -> V2LocalAuthorizationAssessment {
231    if !state.claim_time_valid {
232        return v2_interrupted_assessment(
233            "claim store returned an authoritative claim time outside the authenticated freshness bounds",
234        );
235    }
236    if let Some(e) = &opts.expected_challenge {
237        if !matches_expected_challenge_v2(e, expected) {
238            return v2_interrupted_assessment(
239                "local authorization challenge state differs from successful preflight or atomic claim",
240            );
241        }
242    }
243    let now = state.claimed_at;
244    state.lock().evaluated_at = now;
245    if opts.required_scope != state.required_scope || opts.future_skew_seconds != state.future_skew {
246        return v2_interrupted_assessment("local authorization state differs from successful preflight or atomic claim");
247    }
248    if opts.required_scope != expected.required_scope {
249        return v2_interrupted_assessment("required scope differs from the scope validated during preflight");
250    }
251    match bundle_hash_v2(bundle) {
252        Ok(h) if h == state.proof_digest => {}
253        _ => return v2_interrupted_assessment("proof bundle differs from the bundle validated during preflight"),
254    }
255    if bundle.challenge != expected.value
256        || bundle.challenge_at != expected.issued_at
257        || bundle.verifier_id != expected.verifier_id
258    {
259        return v2_interrupted_assessment("proof challenge differs from the challenge validated during preflight");
260    }
261    if let Err(e) = validate_required_scope_v2(&opts.required_scope) {
262        return v2_interrupted_assessment(&format!(
263            "required scope changed after successful preflight: {}",
264            e.message
265        ));
266    }
267    if verify_proof_bundle_v2_signatures(bundle).is_err() {
268        return v2_interrupted_assessment("proof signature changed after successful preflight");
269    }
270    let Some(root) = bundle.delegations.last() else {
271        return v2_local_assessment(
272            "delegation_not_authorized",
273            "not_delegated",
274            Vec::new(),
275            "proof has no delegation certificates",
276        );
277    };
278    if !opts.trust_configured {
279        return v2_local_assessment(
280            "authorization_unverified",
281            "trust_unavailable",
282            Vec::new(),
283            "caller-authenticated trust configuration is unavailable",
284        );
285    }
286    if opts.trusted_root_id != root.issuer_id || !equal_keys(&opts.trusted_root_key, &root.issuer_pub_key) {
287        return v2_local_assessment(
288            "unauthorized",
289            "unauthorized",
290            Vec::new(),
291            "delegation chain does not terminate at the configured trust root",
292        );
293    }
294    for (i, cert) in bundle.delegations.iter().enumerate() {
295        // Checked integer seconds: both timestamps inside the v2 domain, a
296        // bounded lifetime, and issued_at no later than now + skew.
297        let latest_issue = checked_add_v2(now, state.future_skew);
298        let bad = !valid_v2_timestamp(cert.issued_at)
299            || !valid_v2_timestamp(cert.expires_at)
300            || cert.issued_at >= cert.expires_at
301            || cert.expires_at - cert.issued_at > V2_MAX_DELEGATION_LIFETIME_SECONDS
302            || latest_issue.is_none_or(|latest| cert.issued_at > latest);
303        if bad {
304            return v2_local_assessment(
305                "invalid",
306                "proof_invalid",
307                Vec::new(),
308                &format!("delegation {i} has invalid time bounds"),
309            );
310        }
311    }
312    for (i, cert) in bundle.delegations.iter().enumerate() {
313        if now >= cert.expires_at {
314            return v2_local_assessment(
315                "expired",
316                "delegation_expired",
317                Vec::new(),
318                &format!("delegation {i} has expired"),
319            );
320        }
321    }
322    for (i, cert) in bundle.delegations.iter().enumerate() {
323        if let Err(e) = validate_scopes_v2(&cert.scope) {
324            return v2_local_assessment(
325                "invalid_scope",
326                "invalid_scope",
327                Vec::new(),
328                &format!("delegation {i}: {}", e.message),
329            );
330        }
331    }
332    for i in 0..bundle.delegations.len() {
333        if let Some(parent) = bundle.delegations.get(i + 1) {
334            if !parent.scope.iter().any(|s| s == SCOPE_IDENTITY_DELEGATE) {
335                return v2_local_assessment(
336                    "delegation_not_authorized",
337                    "delegation_not_authorized",
338                    Vec::new(),
339                    &format!("parent delegation {} does not grant {SCOPE_IDENTITY_DELEGATE:?}", i + 1),
340                );
341            }
342        }
343    }
344    let scope_lists: Vec<&[String]> = bundle.delegations.iter().map(|c| c.scope.as_slice()).collect();
345    let effective = intersect_scopes(&scope_lists);
346    let mut local_policy_failure: Option<V2LocalPolicyFailure> = None;
347    if !effective.contains(&opts.required_scope) {
348        local_policy_failure = Some(V2LocalPolicyFailure {
349            status: "scope_denied".into(),
350            reason: "scope_denied".into(),
351            detail: format!(
352                "required scope {:?} is not in the effective delegation scope",
353                opts.required_scope
354            ),
355        });
356    }
357    if opts.context_policy.is_some()
358        && !same_v2_context_policy(opts.context_policy.as_ref(), expected.context_policy.as_ref())
359    {
360        return v2_interrupted_assessment("context policy differs from the policy sealed during successful preflight");
361    }
362    let context_assessment = evaluate_proof_bundle_v2_context_policy(Some(bundle), expected.context_policy.as_ref());
363    if context_assessment.status != "passed" && local_policy_failure.is_none() {
364        local_policy_failure = Some(V2LocalPolicyFailure {
365            status: context_assessment.status.clone(),
366            reason: context_assessment.reason.clone(),
367            detail: context_assessment.detail.clone(),
368        });
369    }
370    let (deferred, constraint_status, mut constraint_failures, extension_valid_until) =
371        evaluate_v2_local_constraints(bundle, opts, expected, now);
372    if !constraint_status.is_empty() {
373        constraint_failures.sort();
374        let candidate = V2LocalPolicyFailure {
375            status: constraint_status.clone(),
376            reason: constraint_status,
377            detail: constraint_failures.join("; "),
378        };
379        if local_policy_failure.is_none() {
380            local_policy_failure = Some(candidate);
381        }
382    }
383    let no_local_failure = local_policy_failure.is_none();
384    let mut assessment = pending_v2_local_assessment(bundle, opts, effective, deferred, local_policy_failure);
385    assessment.extension_valid_until = extension_valid_until;
386    assessment.delegation_valid_until = bundle
387        .delegations
388        .iter()
389        .map(|c| c.expires_at)
390        .min()
391        .unwrap_or_default();
392    if no_local_failure {
393        match local_time_window_valid_until_v2(bundle, &opts.tzdb_version, now) {
394            Ok(h) => assessment.local_time_valid_until = h,
395            Err(e) => {
396                assessment.local_policy_failure = Some(V2LocalPolicyFailure {
397                    status: "constraint_unverifiable".into(),
398                    reason: "constraint_unverifiable".into(),
399                    detail: e.message,
400                });
401            }
402        }
403    }
404    assessment.context_assessment = context_assessment.assessment;
405    assessment.context_policy_digest = context_assessment.policy_digest;
406    assessment
407}
408
409fn pending_v2_local_assessment(
410    bundle: &ProofBundleV2,
411    opts: &V2LocalAuthorizationOptions,
412    effective: Vec<String>,
413    deferred: Vec<V2DeferredConstraint>,
414    failure: Option<V2LocalPolicyFailure>,
415) -> V2LocalAuthorizationAssessment {
416    let mut a = v2_local_assessment(
417        "pending_external_checks",
418        "external_checks_required",
419        effective,
420        "local checks recorded; status and deferred authorization checks remain",
421    );
422    a.agent_id = bundle.agent_id.clone();
423    a.root_id = opts.trusted_root_id.clone();
424    a.required_scope = opts.required_scope.clone();
425    a.delegation_digest = bundle.delegation_digest.clone();
426    a.local_policy_failure = failure;
427    a.status_checks = bundle
428        .delegations
429        .iter()
430        .enumerate()
431        .map(|(i, cert)| V2CertificateStatusCheck {
432            delegation_index: i,
433            issuer_id: cert.issuer_id.clone(),
434            subject_id: cert.subject_id.clone(),
435            cert_id: cert.cert_id.clone(),
436        })
437        .collect();
438    a.deferred = deferred;
439    a
440}
441
442/// Go `evaluateV2LocalConstraints`: every locally decidable constraint in
443/// chain order. A registered v2 type uses its built-in rule; an extension
444/// type uses the evaluator sealed for it at preflight; any other type is
445/// constraint_unknown. Also returns the earliest extension pass horizon
446/// (0 = none).
447fn evaluate_v2_local_constraints(
448    bundle: &ProofBundleV2,
449    opts: &V2LocalAuthorizationOptions,
450    sealed: &ExpectedChallengeStateV2,
451    now: i64,
452) -> (Vec<V2DeferredConstraint>, String, Vec<String>, i64) {
453    let mut deferred = Vec::new();
454    let mut constraint_status = String::new();
455    let mut constraint_failures = Vec::new();
456    let mut extension_horizon = 0i64;
457    for (i, cert) in bundle.delegations.iter().enumerate() {
458        for (j, constraint) in cert.constraints.iter().enumerate() {
459            if constraint.kind == CONSTRAINT_MAX_RATE || constraint.kind == CONSTRAINT_RECEIVER_AUDIENCE {
460                match constraint.canonical_json() {
461                    Ok(encoded) => deferred.push(V2DeferredConstraint {
462                        delegation_index: i,
463                        constraint_index: j,
464                        issuer_id: cert.issuer_id.clone(),
465                        cert_id: cert.cert_id.clone(),
466                        kind: constraint.kind.clone(),
467                        canonical_json: encoded,
468                    }),
469                    Err(e) => {
470                        if constraint_precedence_v2("constraint_unverifiable") > constraint_precedence_v2(&constraint_status) {
471                            constraint_status = "constraint_unverifiable".into();
472                        }
473                        constraint_failures.push(format!(
474                            "delegation {i} constraint {j} cannot be encoded: {}",
475                            e.message
476                        ));
477                    }
478                }
479                continue;
480            }
481            let result: Result<(), ConstraintFailure> = match sealed.evaluators.get(&constraint.kind) {
482                Some(entry) if !is_registered_constraint_type_v2(&constraint.kind) => {
483                    match extension_params_json_v2(constraint) {
484                        Err(e) => Err(ConstraintFailure::Unverifiable(format!(
485                            "{} params cannot be encoded: {}",
486                            constraint.kind, e.message
487                        ))),
488                        Ok(params) => run_constraint_evaluator_v2(
489                            entry,
490                            sealed.evaluator_timeout,
491                            ConstraintEvaluationInputV2 {
492                                kind: constraint.kind.clone(),
493                                params_json: params,
494                                delegation_index: i,
495                                constraint_index: j,
496                                issuer_id: cert.issuer_id.clone(),
497                                cert_id: cert.cert_id.clone(),
498                                context: opts.context.clone(),
499                                evaluation_time: now,
500                            },
501                        )
502                        .map(|horizon| {
503                            if horizon != 0 && (extension_horizon == 0 || horizon < extension_horizon) {
504                                extension_horizon = horizon;
505                            }
506                        }),
507                    }
508                }
509                _ => evaluate_constraint_v2(constraint, &opts.context, &opts.tzdb_version, now),
510            };
511            if let Err(failure) = result {
512                let (status, message) = match failure {
513                    ConstraintFailure::Denied(m) => ("constraint_denied", m),
514                    ConstraintFailure::Unverifiable(m) => ("constraint_unverifiable", m),
515                    ConstraintFailure::Unknown(m) => ("constraint_unknown", m),
516                };
517                if constraint_status.is_empty() || constraint_precedence_v2(status) > constraint_precedence_v2(&constraint_status) {
518                    constraint_status = status.into();
519                }
520                constraint_failures.push(format!("delegation {i} constraint {j}: {message}"));
521            }
522        }
523    }
524    (deferred, constraint_status, constraint_failures, extension_horizon)
525}
526
527/// Go `loadV2TimeZone`: an IANA zone from the embedded, pinned database
528/// after checking the configured database version.
529fn load_v2_time_zone(configured_version: &str, tz: &str) -> Result<Arc<Zone>, String> {
530    if configured_version.is_empty() {
531        return Err("no tzdb_version is configured".into());
532    }
533    if configured_version != TZDB_VERSION_V2 {
534        return Err(format!(
535            "configured tzdb_version {configured_version:?} differs from the loaded IANA tzdata {TZDB_VERSION_V2}"
536        ));
537    }
538    load_zone(tz).map_err(|e| e.message().to_string())
539}
540
541/// `now.In(loc)`: (UTC offset, local civil date and clock).
542struct LocalTime {
543    offset: i64,
544    year: i64,
545    month: u32,
546    day: u32,
547    minute_of_day: i64,
548}
549
550fn local_time(zone: &Zone, now: i64) -> LocalTime {
551    let info = zone.lookup(now);
552    let (year, month, day, hour, minute, _) = civil_from_unix(now.wrapping_add(info.offset_seconds));
553    LocalTime {
554        offset: info.offset_seconds,
555        year,
556        month,
557        day,
558        minute_of_day: i64::from(hour) * 60 + i64::from(minute),
559    }
560}
561
562/// Go `evaluateConstraintV2`: one registered locally decidable constraint.
563/// `max_rate` and `ratify.receiver_audience` are deferred stages and never
564/// reach here.
565pub(crate) fn evaluate_constraint_v2(
566    c: &ConstraintV2,
567    ctx: &ConstraintContextV2,
568    tzdb_version: &str,
569    now: i64,
570) -> Result<(), ConstraintFailure> {
571    use ConstraintFailure::*;
572    match c.kind.as_str() {
573        CONSTRAINT_RESOURCE_PATH => {
574            // SPEC-v2 §5.2 order: the signed path_prefix is checked before
575            // any request input.
576            if !c.path_prefix.is_empty() {
577                if let Err(e) = normalize_resource_path(&c.path_prefix) {
578                    return Err(Denied(format!("malformed path_prefix: {e}")));
579                }
580            }
581            if !ctx.has_resource || ctx.requested_resource_id.is_empty() {
582                return Err(Unverifiable("no requested resource in context".into()));
583            }
584            if ctx.requested_resource_id != c.resource_id {
585                return Err(Denied("requested resource does not match the authorized resource".into()));
586            }
587            if c.path_prefix.is_empty() {
588                return Ok(());
589            }
590            if ctx.requested_path.is_empty() {
591                return Err(Unverifiable("no requested path in context".into()));
592            }
593            if let Err(e) = normalize_resource_path(&ctx.requested_path) {
594                return Err(Denied(format!("invalid requested path: {e}")));
595            }
596            if !resource_path_matches(&c.path_prefix, &ctx.requested_path) {
597                return Err(Denied(format!(
598                    "requested path {:?} is outside the authorized prefix {:?}",
599                    ctx.requested_path, c.path_prefix
600                )));
601            }
602            Ok(())
603        }
604        CONSTRAINT_TIME_WINDOW => {
605            let zone = load_v2_time_zone(tzdb_version, &c.tz)
606                .map_err(|e| Unverifiable(format!("time zone {:?} cannot be evaluated: {e}", c.tz)))?;
607            let start = parse_hhmm_v2(&c.start).map_err(|e| Denied(e.message))?;
608            let end = parse_hhmm_v2(&c.end).map_err(|e| Denied(e.message))?;
609            let local = local_time(&zone, now);
610            let cur = local.minute_of_day;
611            let inside = if start <= end { (start..=end).contains(&cur) } else { cur >= start || cur <= end };
612            if !inside {
613                return Err(Denied(format!(
614                    "current {:02}:{:02} is outside [{}, {}] {}",
615                    cur / 60,
616                    cur % 60,
617                    c.start,
618                    c.end,
619                    zone.name()
620                )));
621            }
622            Ok(())
623        }
624        CONSTRAINT_MAX_AMOUNT => {
625            if !ctx.has_amount {
626                return Err(Unverifiable("no requested amount in context".into()));
627            }
628            if ctx.requested_amount_micros < 0
629                || ctx.requested_amount_micros > MAX_SAFE
630                || !valid_iso4217_alpha_v2(&ctx.requested_currency)
631            {
632                return Err(Unverifiable(
633                    "requested amount is not a nonnegative safe integer in ISO-4217 micro-units".into(),
634                ));
635            }
636            if ctx.requested_currency != c.currency {
637                return Err(Denied(format!(
638                    "currency mismatch: requested {:?}, constraint {:?}",
639                    ctx.requested_currency, c.currency
640                )));
641            }
642            if ctx.requested_amount_micros > c.max_amount_micros {
643                return Err(Denied(format!(
644                    "amount {} exceeds max {} micro-units of {}",
645                    ctx.requested_amount_micros, c.max_amount_micros, c.currency
646                )));
647            }
648            Ok(())
649        }
650        CONSTRAINT_MAX_RATE | CONSTRAINT_RECEIVER_AUDIENCE => Err(Unverifiable(format!(
651            "{} requires its dedicated post-status stage",
652            c.kind
653        ))),
654        _ => Err(Unknown(format!("unknown constraint type: {}", c.kind))),
655    }
656}
657
658/// Go `nextUTCOffsetChangeV2`: the first instant after `now` at which the UTC
659/// offset of `zone` differs from its offset at `now` (SPEC-v2 §5.2), or `None`
660/// when it never changes again within the timestamp domain. Explicit
661/// transitions come from the transition table, then the POSIX TZ footer rule
662/// recurs every year; a transition that keeps the offset is not a change.
663///
664/// Past a year's last footer transition the zone period reports the start of
665/// the year plus 365 days as its end. That bound keeps the offset, so the loop
666/// steps past it instead of ending the period there.
667fn next_utc_offset_change_v2(zone: &Zone, now: i64) -> Option<i64> {
668    let offset = zone.lookup(now).offset_seconds;
669    let mut candidate = now;
670    while candidate <= V2_MAX_TIMESTAMP_SECONDS {
671        let mut end = zone.lookup(candidate).end?;
672        if end <= candidate {
673            // The leap-year bound can equal the instant it was computed from;
674            // resume at the next UTC year, which has no footer transition
675            // before it.
676            let year = civil_from_unix(candidate).0;
677            end = unix_from_civil_utc(year + 1, 1, 1, 0, 0, 0);
678        }
679        if zone.lookup(end).offset_seconds != offset {
680            return Some(end);
681        }
682        candidate = end;
683    }
684    None
685}
686
687/// Go `localTimeWindowValidUntilV2`: bound an allow at the end of each
688/// currently accepted local minute window or the next time-zone offset
689/// transition, whichever is first.
690pub(crate) fn local_time_window_valid_until_v2(bundle: &ProofBundleV2, tzdb_version: &str, now: i64) -> V2Result<i64> {
691    let mut horizon = 0i64;
692    for cert in &bundle.delegations {
693        for constraint in &cert.constraints {
694            if constraint.kind != CONSTRAINT_TIME_WINDOW {
695                continue;
696            }
697            let zone = load_v2_time_zone(tzdb_version, &constraint.tz).map_err(V2Error::plain)?;
698            let start = parse_hhmm_v2(&constraint.start)?;
699            let end = parse_hhmm_v2(&constraint.end)?;
700            let local = local_time(&zone, now);
701            let minute = local.minute_of_day;
702            let inside = if start <= end { (start..=end).contains(&minute) } else { minute >= start || minute <= end };
703            if !inside {
704                return plain("time window is no longer current");
705            }
706            let day_offset = i64::from(start > end && minute >= start);
707            let mut until = unix_from_civil_utc(
708                local.year,
709                local.month,
710                i64::from(local.day) + day_offset,
711                0,
712                end + 1,
713                0,
714            )
715            .wrapping_sub(local.offset);
716            if let Some(change) = next_utc_offset_change_v2(&zone, now) {
717                if change < until {
718                    until = change;
719                }
720            }
721            if until <= now {
722                return plain("time window has no valid terminal horizon");
723            }
724            // A horizon past the timestamp domain is clamped to its upper
725            // bound (SPEC-v2 §2.5, §5.2).
726            let contribution = until.min(V2_MAX_TIMESTAMP_SECONDS);
727            if horizon == 0 || contribution < horizon {
728                horizon = contribution;
729            }
730        }
731    }
732    Ok(horizon)
733}
734
735/// Go `allowHorizonV2`.
736pub(crate) fn allow_horizon_v2(a: &V2LocalAuthorizationAssessment) -> i64 {
737    let mut horizon = a.delegation_valid_until.min(a.status_fresh_until);
738    if a.audience_fresh_until > 0 {
739        horizon = horizon.min(a.audience_fresh_until);
740    }
741    if a.local_time_valid_until > 0 {
742        horizon = horizon.min(a.local_time_valid_until);
743    }
744    if a.extension_valid_until > 0 {
745        horizon = horizon.min(a.extension_valid_until);
746    }
747    horizon.min(V2_MAX_TIMESTAMP_SECONDS)
748}
749
750/// Go `combinableWithAudienceV2`.
751fn combinable_with_audience_v2(failure: Option<&V2LocalPolicyFailure>, deferred: &[V2DeferredConstraint]) -> bool {
752    match failure {
753        Some(f) if f.status == "constraint_unknown" || f.status == "constraint_unverifiable" => {
754            deferred.iter().any(|d| d.kind == CONSTRAINT_RECEIVER_AUDIENCE)
755        }
756        _ => false,
757    }
758}
759
760/// Go `constraintPrecedenceV2`.
761fn constraint_precedence_v2(status: &str) -> u8 {
762    match status {
763        "constraint_denied" => 3,
764        "constraint_unknown" => 2,
765        "constraint_unverifiable" => 1,
766        _ => 0,
767    }
768}
769
770/// Go `resolveClaimProofBundleV2AfterStatus`: complete the ordered
771/// post-claim status stage for the sealed pending assessment. Internal:
772/// status results reach a claim only through the authenticated evidence path
773/// of SPEC-v2 §6.5.
774pub(crate) fn resolve_claim_proof_bundle_v2_after_status(
775    token: &V2EvaluationToken,
776    aggregate: impl FnOnce(&[V2CertificateStatusCheck]) -> V2Result<V2StatusAssessment>,
777) -> V2Result<V2LocalAuthorizationAssessment> {
778    let state = &token.state;
779    let mut m = state.lock();
780    let pending = match &m.pending_assessment {
781        Some(p)
782            if state.evaluation_complete.load(Ordering::SeqCst)
783                && m.evaluation_status == "pending_external_checks" =>
784        {
785            p.clone()
786        }
787        _ => return plain("v2 claim does not have a pending status assessment"),
788    };
789    let mut a = pending;
790    if a.bundle_hash != state.expected.bundle_hash || a.required_scope != state.expected.required_scope {
791        return plain("pending status assessment differs from its claimed proof");
792    }
793    let aggregated = aggregate(&a.status_checks)?;
794    a.status_assessment = aggregated.assessment.clone();
795    a.status_fresh_until = aggregated.fresh_until;
796    a.status_evidence = aggregated.evidence.clone();
797    match aggregated.assessment.as_str() {
798        "revoked" => {
799            a.status = "revoked".into();
800            a.reason = "delegation_revoked".into();
801            a.detail = "at least one delegation certificate is revoked".into();
802        }
803        "unavailable" => {
804            a.status = "authorization_unverified".into();
805            a.reason = "status_unavailable".into();
806            a.detail = "one or more delegation certificate statuses are unavailable".into();
807        }
808        "stale" => {
809            a.status = "authorization_unverified".into();
810            a.reason = "status_stale".into();
811            a.detail = "one or more delegation certificate statuses are stale".into();
812        }
813        "current" => {
814            if a.local_policy_failure.is_some() && combinable_with_audience_v2(a.local_policy_failure.as_ref(), &a.deferred) {
815                // SPEC-v2 §5.2, §6.4: a proven audience violation on another
816                // link outranks a local unknown or unverifiable constraint,
817                // so the audience stage still runs. Rate never follows.
818                a.deferred.retain(|d| d.kind == CONSTRAINT_RECEIVER_AUDIENCE);
819                a.status = "pending_external_checks".into();
820                a.reason = "deferred_policy_checks_required".into();
821                a.detail = "status is current; audience must be aggregated with a pending local constraint result".into();
822                m.pending_assessment = Some(a.clone());
823                m.evaluation_status = a.status.clone();
824                m.evaluation_reason = a.reason.clone();
825                return Ok(a);
826            } else if let Some(local) = a.local_policy_failure.clone() {
827                a.status = local.status;
828                a.reason = local.reason;
829                a.detail = local.detail;
830            } else if !a.deferred.is_empty() {
831                a.status = "pending_external_checks".into();
832                a.reason = "deferred_policy_checks_required".into();
833                a.detail = "status is current; deferred audience or rate checks remain".into();
834                m.pending_assessment = Some(a.clone());
835                m.evaluation_status = a.status.clone();
836                m.evaluation_reason = a.reason.clone();
837                return Ok(a);
838            } else {
839                a.status = "authorized_agent".into();
840                a.reason = "authorized".into();
841                a.detail = "proof, status, and local authorization checks passed".into();
842                m.allow_valid_until = allow_horizon_v2(&a);
843            }
844        }
845        _ => return plain("v2 status aggregator returned an unknown assessment"),
846    }
847    m.evaluation_status = a.status.clone();
848    m.evaluation_reason = a.reason.clone();
849    m.pending_assessment = None;
850    Ok(a)
851}
852
853/// Go `ResolveClaimProofBundleV2AfterAudience`: consume caller-authenticated,
854/// complete membership results only after every certificate status is
855/// current. Membership freshness is evaluated at the authoritative claim
856/// time sealed in the token. Errors are `configuration_invalid` (Go returns
857/// them unclassified; they mean the token is not in this stage or the sealed
858/// state is inconsistent).
859pub fn resolve_claim_proof_bundle_v2_after_audience(
860    token: &V2EvaluationToken,
861    memberships: &[V2AudienceMembership],
862) -> V2Result<V2LocalAuthorizationAssessment> {
863    resolve_after_audience_inner(token, memberships).map_err(|e| e.classify(V2ErrorClass::ConfigurationInvalid))
864}
865
866pub(crate) fn resolve_after_audience_inner(
867    token: &V2EvaluationToken,
868    memberships: &[V2AudienceMembership],
869) -> V2Result<V2LocalAuthorizationAssessment> {
870    let state = &token.state;
871    let mut m = state.lock();
872    let ok = match &m.pending_assessment {
873        Some(p) => {
874            state.evaluation_complete.load(Ordering::SeqCst)
875                && m.evaluation_status == "pending_external_checks"
876                && p.status_assessment == "current"
877                && (p.local_policy_failure.is_none()
878                    || combinable_with_audience_v2(p.local_policy_failure.as_ref(), &p.deferred))
879        }
880        None => false,
881    };
882    let Some(mut a) = m.pending_assessment.clone().filter(|_| ok) else {
883        return plain("v2 claim does not have current status and pending audience checks");
884    };
885    if a.bundle_hash != state.expected.bundle_hash || a.required_scope != state.expected.required_scope {
886        m.evaluation_status = "authorization_unverified".into();
887        m.evaluation_reason = "evaluation_interrupted".into();
888        m.pending_assessment = None;
889        return plain("pending audience assessment differs from its claimed proof");
890    }
891    let result = match evaluate_receiver_audience_inner(
892        &a.deferred,
893        &state.expected.expected_receiver_id,
894        memberships,
895        m.evaluated_at,
896        state.future_skew,
897    ) {
898        Ok(r) => r,
899        Err(e) => {
900            m.evaluation_status = "authorization_unverified".into();
901            m.evaluation_reason = "evaluation_interrupted".into();
902            m.pending_assessment = None;
903            return Err(e);
904        }
905    };
906    a.audience_evidence_digests = result.evidence_digests.clone();
907    a.audience_fresh_until = result.fresh_until;
908    if let Some(local) = a.local_policy_failure.clone() {
909        // Aggregate independently of link order: denied, then unknown, then
910        // unverifiable (SPEC-v2 §5.2).
911        if result.status == "passed" || constraint_precedence_v2(&local.status) > constraint_precedence_v2(&result.status) {
912            a.status = local.status;
913            a.reason = local.reason;
914            a.detail = local.detail;
915        } else {
916            a.status = result.status.clone();
917            a.reason = result.status.clone();
918            a.detail = "receiver audience did not authorize this receiver".into();
919        }
920        a.deferred = Vec::new();
921        m.pending_assessment = None;
922    } else if result.status != "passed" {
923        a.status = result.status.clone();
924        a.reason = result.status.clone();
925        a.detail = "receiver audience did not authorize this receiver".into();
926        m.pending_assessment = None;
927    } else {
928        a.deferred.retain(|d| d.kind != CONSTRAINT_RECEIVER_AUDIENCE);
929        if a.deferred.is_empty() {
930            a.status = "authorized_agent".into();
931            a.reason = "authorized".into();
932            a.detail = "proof, status, audience, and local authorization checks passed".into();
933            m.allow_valid_until = allow_horizon_v2(&a);
934            m.pending_assessment = None;
935        } else {
936            a.status = "pending_external_checks".into();
937            a.reason = "rate_reservation_required".into();
938            a.detail = "audience passed; rate reservation remains".into();
939            m.pending_assessment = Some(a.clone());
940        }
941    }
942    m.evaluation_status = a.status.clone();
943    m.evaluation_reason = a.reason.clone();
944    Ok(a)
945}
946
947/// Go `ResolveClaimProofBundleV2AfterRate`: the final external Protocol
948/// constraint stage. The caller must finalize the returned terminal result
949/// through the same claim store; an ambiguous store error never authorizes.
950/// A rate store that panics is treated as unavailable. Errors are
951/// `evaluation_cancelled` for a done context and `configuration_invalid`
952/// otherwise (Go returns them unclassified).
953pub fn resolve_claim_proof_bundle_v2_after_rate(
954    ctx: &V2Context,
955    store: Option<&dyn V2RateReservationStore>,
956    token: &V2EvaluationToken,
957) -> V2Result<V2LocalAuthorizationAssessment> {
958    if ctx.is_done() {
959        return Err(V2Error::new(V2ErrorClass::EvaluationCancelled, "v2 rate evaluation context is done"));
960    }
961    resolve_after_rate_inner(ctx, store, token).map_err(|e| e.classify(V2ErrorClass::ConfigurationInvalid))
962}
963
964pub(crate) fn resolve_after_rate_inner(
965    ctx: &V2Context,
966    store: Option<&dyn V2RateReservationStore>,
967    token: &V2EvaluationToken,
968) -> V2Result<V2LocalAuthorizationAssessment> {
969    if ctx.is_done() {
970        return plain("v2 rate evaluation context is done");
971    }
972    let state = &token.state;
973    let mut m = state.lock();
974    let ok = match &m.pending_assessment {
975        Some(p) => {
976            state.evaluation_complete.load(Ordering::SeqCst)
977                && m.evaluation_status == "pending_external_checks"
978                && p.status_assessment == "current"
979                && p.local_policy_failure.is_none()
980        }
981        None => false,
982    };
983    let Some(mut a) = m.pending_assessment.clone().filter(|_| ok) else {
984        return plain("v2 claim does not have current status and pending rate checks");
985    };
986    if a.bundle_hash != state.expected.bundle_hash
987        || a.required_scope != state.expected.required_scope
988        || state.rate_batch.is_empty()
989    {
990        m.evaluation_status = "authorization_unverified".into();
991        m.evaluation_reason = "evaluation_interrupted".into();
992        m.pending_assessment = None;
993        return plain("pending rate assessment differs from its claimed proof");
994    }
995    if a.deferred.iter().any(|d| d.kind != CONSTRAINT_MAX_RATE) {
996        return plain("audience or unknown checks remain before rate reservation");
997    }
998    let batch = match build_v2_rate_reservation_batch_inner(&a.deferred) {
999        Ok(b) if b == state.rate_batch => b,
1000        _ => {
1001            m.evaluation_status = "authorization_unverified".into();
1002            m.evaluation_reason = "evaluation_interrupted".into();
1003            m.pending_assessment = None;
1004            return plain("pending rate checks differ from sealed signed batch");
1005        }
1006    };
1007    let result: Result<(), V2StoreError> = match store {
1008        None => Err(V2StoreError::Unavailable("v2 rate reservation store is unavailable".into())),
1009        Some(store) if store.rate_at_finalization_view().is_some() => {
1010            m.rate_at_finalization = true;
1011            a.rate_admission_deferred = true;
1012            Ok(())
1013        }
1014        Some(store) => {
1015            let owner = state.owner_token.clone();
1016            let call = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1017                store.reserve_v2_rate_batch(ctx, &state.claim_id, &owner, &a.bundle_hash, &batch)
1018            }));
1019            call.unwrap_or_else(|_| Err(V2StoreError::Unavailable("rate store panicked".into())))
1020        }
1021    };
1022    match result {
1023        Ok(()) => {
1024            a.status = "authorized_agent".into();
1025            a.reason = "authorized".into();
1026            a.detail = if m.rate_at_finalization {
1027                "proof, status, and audience passed; rate admission is deferred to durable finalization".into()
1028            } else {
1029                "proof, status, audience, and rate checks passed".into()
1030            };
1031            m.allow_valid_until = allow_horizon_v2(&a);
1032        }
1033        Err(V2StoreError::RateLimitExceeded) => {
1034            a.status = "constraint_denied".into();
1035            a.reason = "constraint_denied".into();
1036            a.detail = "signed rate limit has no remaining capacity".into();
1037        }
1038        Err(_) => {
1039            a.status = "constraint_unverifiable".into();
1040            a.reason = "constraint_unverifiable".into();
1041            a.detail = "rate reservation could not be verified".into();
1042            a.rate_store_unavailable = true;
1043        }
1044    }
1045    a.deferred = Vec::new();
1046    m.pending_assessment = None;
1047    m.evaluation_status = a.status.clone();
1048    m.evaluation_reason = a.reason.clone();
1049    Ok(a)
1050}
1051
1052/// Go `interruptV2Evaluation`: turn the claim's evaluation into the terminal
1053/// indeterminate/evaluation_interrupted result. Any provisional rate
1054/// admission is abandoned because the result is not allow.
1055pub(crate) fn interrupt_v2_evaluation(token: &V2EvaluationToken) {
1056    let state = &token.state;
1057    let mut m = state.lock();
1058    m.evaluation_status = "authorization_unverified".into();
1059    m.evaluation_reason = "evaluation_interrupted".into();
1060    m.allow_valid_until = 0;
1061    m.rate_at_finalization = false;
1062    m.pending_assessment = None;
1063    state.evaluation_complete.store(true, Ordering::SeqCst);
1064}