Skip to main content

ratify_protocol/v2/
claim_store.rs

1//! The atomic challenge claim, the single-use evaluator capability, and
2//! terminal finalization (SPEC-v2 §6.2, §7.2, §7.3, §7.5). Mirrors Go
3//! `claim_store_v2.go`.
4
5use std::fmt;
6use std::sync::atomic::{AtomicBool, Ordering};
7use std::sync::{Arc, Mutex, MutexGuard};
8
9use sha2::{Digest, Sha256};
10
11use super::authorization::V2LocalAuthorizationAssessment;
12use super::context::V2Context;
13use super::errors::{err, plain, V2Error, V2ErrorClass, V2Result};
14use super::evaluation_progress::{terminal_result_json, V2EvaluationProgress, V2InterruptedClaim};
15use super::evaluator::ConstraintEvaluatorRefV2;
16use super::json::{parse_json, JV};
17use super::limits::v2_challenge_time_current;
18use super::operation_context::{challenge_claim_digest_v2, protocol_claim_id_from_digest_v2, protocol_claim_id_v2};
19use super::preflight::{validate_proof_bundle_v2_preflight, ExpectedChallengeStateV2, ExpectedChallengeV2, V2PreflightResult};
20use super::rate_reservation::{signed_v2_rate_reservation_batch, V2RateReservation};
21use super::receipt::decode_verification_receipt_body_v2;
22use super::wire::{bundle_hash_v2, ProofBundleV2};
23
24// ---------------------------------------------------------------------------
25// Store errors
26
27/// A Part B store, clock, or checkpoint failure.
28///
29/// Go stores return an `error` that is either classified (`*V2Error`), one
30/// of a few exact sentinel values, or a plain (unclassified) error to which
31/// the verifier assigns the class SPEC-v2 names for that step. This enum
32/// carries exactly those three kinds.
33#[derive(Debug, Clone, PartialEq, Eq)]
34pub enum V2StoreError {
35    /// A failure whose class the store fixed deliberately; the verifier keeps
36    /// it (for example `clock_regressed`, `claim_lease_lost`).
37    Classified(V2Error),
38    /// An unclassified failure (Go: a plain error). The verifier assigns the
39    /// class Go assigns at that step (usually `claim_store_unavailable`).
40    Unavailable(String),
41    /// Go `ErrV2ClaimProofConflict`: the challenge was already claimed by a
42    /// different proof (class `claim_replay`).
43    ClaimProofConflict,
44    /// Go `ErrV2RateLimitExceeded`: a complete atomic batch had no capacity.
45    RateLimitExceeded,
46    /// Go `ErrV2ReleaseStateMismatch`: a different release record exists.
47    ReleaseStateMismatch,
48    /// Go `ErrV2AcknowledgementNotFound`.
49    AcknowledgementNotFound,
50    /// Go `ErrV2ChallengeIssuanceConflict`: a record already exists for the
51    /// issuance key; the store never overwrites it.
52    ChallengeIssuanceConflict,
53    /// Go `ErrV2ChallengeIssuanceNotFound`.
54    ChallengeIssuanceNotFound,
55}
56
57impl V2StoreError {
58    /// Go `V2ErrorClassOf` for this error: `None` means unclassified.
59    ///
60    /// `RateLimitExceeded` reaches a caller only from
61    /// [`finalize_claim_proof_bundle_v2`], which Go classifies as
62    /// `claim_store_unavailable` while the sentinel stays matchable; this
63    /// variant reports that class so the two agree.
64    pub fn class(&self) -> Option<V2ErrorClass> {
65        match self {
66            V2StoreError::Classified(e) => Some(e.class),
67            V2StoreError::ClaimProofConflict => Some(V2ErrorClass::ClaimReplay),
68            V2StoreError::RateLimitExceeded => Some(V2ErrorClass::ClaimStoreUnavailable),
69            _ => None,
70        }
71    }
72
73    /// The Go error value this store error stands for: classified when Go's
74    /// would be, provisional (unclassified) otherwise.
75    pub(crate) fn into_v2(self) -> V2Error {
76        match self {
77            V2StoreError::Classified(e) => e,
78            V2StoreError::ClaimProofConflict => {
79                V2Error::new(V2ErrorClass::ClaimReplay, self_message(&V2StoreError::ClaimProofConflict))
80            }
81            other => V2Error::plain(self_message(&other)),
82        }
83    }
84
85    /// The error with every unclassified kind given `class`.
86    pub(crate) fn classified_or(self, class: V2ErrorClass) -> V2Error {
87        self.into_v2().classify(class)
88    }
89}
90
91fn self_message(e: &V2StoreError) -> String {
92    match e {
93        V2StoreError::Classified(e) => e.message.clone(),
94        V2StoreError::Unavailable(m) => m.clone(),
95        V2StoreError::ClaimProofConflict => "v2 challenge was already claimed by a different proof".into(),
96        V2StoreError::RateLimitExceeded => "v2 signed rate limit has no remaining capacity".into(),
97        V2StoreError::ReleaseStateMismatch => "v2 claim already records a different release".into(),
98        V2StoreError::AcknowledgementNotFound => "v2 checkpoint acknowledgement not found".into(),
99        V2StoreError::ChallengeIssuanceConflict => "v2 challenge issuance record already exists".into(),
100        V2StoreError::ChallengeIssuanceNotFound => "v2 challenge issuance record not found".into(),
101    }
102}
103
104impl fmt::Display for V2StoreError {
105    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
106        match self {
107            V2StoreError::Classified(e) => write!(f, "{e}"),
108            other => f.write_str(&self_message(other)),
109        }
110    }
111}
112
113impl std::error::Error for V2StoreError {}
114
115impl From<V2Error> for V2StoreError {
116    fn from(e: V2Error) -> Self {
117        V2StoreError::Classified(e)
118    }
119}
120
121// ---------------------------------------------------------------------------
122// Claim
123
124/// The immutable identity a verifier persists when it consumes a fresh
125/// challenge. A [`ClaimStoreV2`] must atomically enforce uniqueness on
126/// (namespace, replay_epoch, challenge_digest), store proof_digest and every
127/// other field as immutable claim values, and return the existing state only
128/// for an exact retry without starting another evaluation. A changed scope or
129/// context policy is not an exact retry even when the signed proof bytes are
130/// identical.
131#[derive(Debug, Clone, PartialEq, Eq, Default)]
132pub struct V2ChallengeClaim {
133    pub claim_id: String,
134    pub namespace: String,
135    pub replay_epoch: i64,
136    pub challenge_digest: String,
137    pub proof_digest: String,
138    pub bundle_hash: String,
139    pub issuer_ids: Vec<String>,
140    pub required_scope: String,
141    pub context_policy_digest: String,
142    pub verifier_id: String,
143    pub agent_id: String,
144    pub requires_rate: bool,
145    pub rate_batch: Vec<V2RateReservation>,
146    pub issued_at: i64,
147    pub expires_at: i64,
148    pub max_age_seconds: i64,
149    pub clock_skew_seconds: i64,
150    pub stream_id: Option<Vec<u8>>,
151    pub stream_seq: Option<i64>,
152    /// The sealed extension evaluator snapshot for the chain (SPEC-v2 §5.2,
153    /// §6.3), sorted by type; every terminal receipt for the claim, including
154    /// evaluation_interrupted, carries it.
155    pub constraint_evaluators: Vec<ConstraintEvaluatorRefV2>,
156}
157
158/// The atomic claim outcome.
159#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
160pub enum V2ClaimDisposition {
161    Created,
162    InProgress,
163    TerminalReplay,
164}
165
166impl V2ClaimDisposition {
167    /// The spelling shared by every SDK (`created`, `in_progress`,
168    /// `terminal_replay`).
169    pub fn as_str(self) -> &'static str {
170        match self {
171            V2ClaimDisposition::Created => "created",
172            V2ClaimDisposition::InProgress => "in_progress",
173            V2ClaimDisposition::TerminalReplay => "terminal_replay",
174        }
175    }
176}
177
178impl fmt::Display for V2ClaimDisposition {
179    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
180        f.write_str(self.as_str())
181    }
182}
183
184/// The claim transaction's result, including its authoritative timestamp.
185/// The store, not the caller, chooses `claimed_at` from its configured
186/// security clock. `owner_token` is returned only to the process that
187/// atomically created the claim; stores persist only a one-way hash of it.
188#[derive(Debug, Clone, PartialEq, Eq)]
189pub struct V2ClaimResult {
190    pub disposition: V2ClaimDisposition,
191    pub claimed_at: i64,
192    pub owner_token: Vec<u8>,
193}
194
195/// A Part B authoritative security clock in integer seconds
196/// (0..V2_MAX_TIMESTAMP_SECONDS). A reading below the greatest reading the
197/// clock has returned is a regression and fails with a
198/// [`V2StoreError::Classified`] `clock_regressed` error.
199pub trait V2AuthoritativeClock: Send + Sync {
200    fn authoritative_time_v2(&self, ctx: &V2Context) -> Result<i64, V2StoreError>;
201}
202
203/// The storage boundary for challenge consumption (Go `ClaimStoreV2`; see
204/// SPEC-v2 §7.3 and the Go documentation for the full contract).
205///
206/// `claim_v2` must be atomic across processes and durable across restart,
207/// advance any stream sequence in the same transaction, and recheck expiry
208/// and maximum age with the authoritative clock inside it. A different
209/// proof_digest or any other immutable field for the same replay key returns
210/// [`V2StoreError::ClaimProofConflict`] without disclosing the existing
211/// result. A created result includes a random 32-byte owner token.
212///
213/// `finalize_v2_claim` compares the token against the stored digest without
214/// an early exit and performs a state-and-live-lease compare-and-set, reading
215/// its authoritative clock as T_final inside it: a regressed reading fails
216/// with `clock_regressed`; a non-zero `allow_valid_until` commits only while
217/// T_final < allow_valid_until and T_final < the challenge expiry, else
218/// `allow_horizon_passed`. It returns `true` when it commits, `false` when the
219/// same owner already committed the identical result and receipt body.
220///
221/// `record_v2_evaluation_progress` persists progress under the owner token
222/// and live lease (`claim_lease_lost` or `claim_already_terminal`
223/// otherwise). `load_v2_interrupted_claim` fails with `claim_lease_live`
224/// while an evaluating claim's lease is live. `recover_interrupted_v2_claim`
225/// validates the result and receipt body as finalization does
226/// ([`validate_v2_finalization_payload`]) and commits only
227/// indeterminate/evaluation_interrupted after the lease expired; a refused
228/// recovery commits nothing.
229///
230/// This trait does not make a memory-only implementation safe for
231/// production.
232pub trait ClaimStoreV2: V2AuthoritativeClock {
233    fn claim_v2(&self, ctx: &V2Context, claim: V2ChallengeClaim) -> Result<V2ClaimResult, V2StoreError>;
234    fn finalize_v2_claim(
235        &self,
236        ctx: &V2Context,
237        claim_id: &str,
238        owner_token: &[u8],
239        terminal_result: &[u8],
240        receipt_body: &[u8],
241        allow_valid_until: i64,
242    ) -> Result<bool, V2StoreError>;
243    fn record_v2_evaluation_progress(
244        &self,
245        ctx: &V2Context,
246        claim_id: &str,
247        owner_token: &[u8],
248        progress: V2EvaluationProgress,
249    ) -> Result<(), V2StoreError>;
250    fn load_v2_interrupted_claim(&self, ctx: &V2Context, claim_id: &str) -> Result<V2InterruptedClaim, V2StoreError>;
251    fn recover_interrupted_v2_claim(
252        &self,
253        ctx: &V2Context,
254        claim_id: &str,
255        terminal_result: &[u8],
256        receipt_body: &[u8],
257    ) -> Result<bool, V2StoreError>;
258    /// Go's `store.(V2RateAtFinalizationStore)` type assertion: a store that
259    /// implements [`V2RateAtFinalizationStore`] returns `Some(self)`.
260    fn rate_at_finalization_view(&self) -> Option<&dyn V2RateAtFinalizationStore> {
261        None
262    }
263}
264
265/// Atomically reserves the complete claim-sealed rate batch. An exact live
266/// retry is idempotent. Implementations must not call back into the token.
267/// `Ok` means every counter remains provisionally held;
268/// [`V2StoreError::RateLimitExceeded`] means definitive capacity exhaustion;
269/// any other error is unavailable or ambiguous and never authorizes.
270pub trait V2RateReservationStore: Send + Sync {
271    fn reserve_v2_rate_batch(
272        &self,
273        ctx: &V2Context,
274        claim_id: &str,
275        owner_token: &[u8],
276        bundle_hash: &str,
277        batch: &[V2RateReservation],
278    ) -> Result<(), V2StoreError>;
279    /// Go's `store.(V2RateAtFinalizationStore)` type assertion: a store that
280    /// implements [`V2RateAtFinalizationStore`] returns `Some(self)`.
281    fn rate_at_finalization_view(&self) -> Option<&dyn V2RateAtFinalizationStore> {
282        None
283    }
284}
285
286/// Admits the sealed rate batch atomically during finalization (external
287/// barrier preparation). The capability must remain active for the claim's
288/// lifetime and must reject a claim with a legacy reservation. Its
289/// `finalize_v2_claim` may return the exact [`V2StoreError::RateLimitExceeded`]
290/// only after definitive rollback. Implementors also return `Some(self)` from
291/// both `rate_at_finalization_view` methods.
292pub trait V2RateAtFinalizationStore: ClaimStoreV2 + V2RateReservationStore {
293    fn admits_v2_rate_at_finalization(&self);
294}
295
296/// Go `ChallengeClaimTimeCurrentV2`: whether an authoritative time is inside
297/// the claim's sealed challenge bounds using exclusive deadlines.
298pub fn challenge_claim_time_current_v2(claim: &V2ChallengeClaim, now: i64) -> bool {
299    v2_challenge_time_current(
300        now,
301        claim.issued_at,
302        claim.expires_at,
303        claim.max_age_seconds,
304        claim.clock_skew_seconds,
305    )
306}
307
308// ---------------------------------------------------------------------------
309// Evaluator capability
310
311/// Grants one local evaluation attempt for a newly created claim. It is
312/// single-use and is never returned for an exact retry. Cloning shares the
313/// same capability (Go passes the pointer).
314#[derive(Clone)]
315pub struct V2EvaluationToken {
316    pub(crate) state: Arc<TokenState>,
317}
318
319impl fmt::Debug for V2EvaluationToken {
320    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
321        f.debug_struct("V2EvaluationToken")
322            .field("claim_id", &self.state.claim_id)
323            .finish_non_exhaustive()
324    }
325}
326
327pub(crate) struct TokenState {
328    pub claim_id: String,
329    pub claim: V2ChallengeClaim,
330    pub proof_digest: String,
331    pub required_scope: String,
332    pub future_skew: i64,
333    pub expected: Arc<ExpectedChallengeStateV2>,
334    pub used: AtomicBool,
335    pub evaluation_complete: AtomicBool,
336    pub claim_time_valid: bool,
337    pub claimed_at: i64,
338    pub rate_batch: Vec<V2RateReservation>,
339    pub owner_token: Vec<u8>,
340    pub m: Mutex<TokenMut>,
341}
342
343#[derive(Default)]
344pub(crate) struct TokenMut {
345    pub finalization_digest: [u8; 32],
346    pub finalization_started: bool,
347    pub evaluated_at: i64,
348    pub rate_at_finalization: bool,
349    pub allow_valid_until: i64,
350    pub evaluation_status: String,
351    pub evaluation_reason: String,
352    pub pending_assessment: Option<V2LocalAuthorizationAssessment>,
353}
354
355impl TokenState {
356    pub(crate) fn lock(&self) -> MutexGuard<'_, TokenMut> {
357        self.m.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
358    }
359
360    /// Go `allowHorizon`: the exclusive allow deadline sealed for this claim
361    /// (0 unless the evaluation reached allow).
362    pub(crate) fn allow_horizon(&self) -> i64 {
363        self.lock().allow_valid_until
364    }
365}
366
367// ---------------------------------------------------------------------------
368// ClaimProofBundleV2
369
370/// Go `ClaimProofBundleV2`: repeat the security-relevant freshness and
371/// binding checks immediately before invoking the atomic claim store. No
372/// trust, status, or policy callback runs before this succeeds. An
373/// unclassified failure is reported as `claim_store_unavailable`, as the live
374/// verifier reports it; a missing or different successful preflight is
375/// `configuration_invalid`; a different proof is `claim_replay`.
376pub fn claim_proof_bundle_v2(
377    ctx: &V2Context,
378    store: &dyn ClaimStoreV2,
379    bundle: &ProofBundleV2,
380    preflight: &V2PreflightResult,
381    configured_namespace: &str,
382    configured_replay_epoch: i64,
383    now: i64,
384) -> V2Result<(V2ChallengeClaim, V2ClaimDisposition, Option<V2EvaluationToken>)> {
385    claim_proof_bundle_v2_inner(ctx, store, bundle, preflight, configured_namespace, configured_replay_epoch, now)
386        .map_err(|e| e.classify(V2ErrorClass::ClaimStoreUnavailable))
387}
388
389pub(crate) fn claim_proof_bundle_v2_inner(
390    ctx: &V2Context,
391    store: &dyn ClaimStoreV2,
392    bundle: &ProofBundleV2,
393    preflight: &V2PreflightResult,
394    configured_namespace: &str,
395    configured_replay_epoch: i64,
396    now: i64,
397) -> V2Result<(V2ChallengeClaim, V2ClaimDisposition, Option<V2EvaluationToken>)> {
398    let sealed = &preflight.state;
399    if sealed.context_policy.is_none() && !sealed.no_context_policy {
400        return err(V2ErrorClass::ConfigurationInvalid, "v2 successful preflight state is required before claim");
401    }
402    let bundle_hash = match bundle_hash_v2(bundle) {
403        Ok(h) if h == sealed.bundle_hash => h,
404        _ => return err(V2ErrorClass::ConfigurationInvalid, "v2 proof bundle differs from successful preflight"),
405    };
406    let expected = ExpectedChallengeV2 {
407        value: sealed.value.clone(),
408        issued_at: sealed.issued_at,
409        expires_at: sealed.expires_at,
410        verifier_namespace: sealed.verifier_namespace.clone(),
411        replay_epoch: sealed.replay_epoch,
412        verifier_id: sealed.verifier_id.clone(),
413        expected_agent_id: sealed.expected_agent_id.clone(),
414        expected_agent_public_key: sealed.expected_agent_public_key.clone(),
415        expected_receiver_id: sealed.expected_receiver_id.clone(),
416        expected_session_context: sealed.expected_session_context.clone(),
417        context_policy: sealed.context_policy.clone(),
418    };
419    validate_proof_bundle_v2_preflight(
420        bundle,
421        &expected,
422        &sealed.required_scope,
423        configured_namespace,
424        configured_replay_epoch,
425        &sealed.verifier_id,
426        now,
427        sealed.max_age,
428        sealed.future_skew,
429    )
430    .map_err(|e| e.context("v2 claim-time preflight"))?;
431    let challenge_digest = challenge_claim_digest_v2(&sealed.value)?;
432    let claim_id = protocol_claim_id_v2(&sealed.verifier_namespace, sealed.replay_epoch, &sealed.value)?;
433    let rate_batch = signed_v2_rate_reservation_batch(bundle)
434        .map_err(|e| e.context("v2 signed rate batch").classify(V2ErrorClass::Malformed))?;
435    let claim = V2ChallengeClaim {
436        claim_id,
437        namespace: sealed.verifier_namespace.clone(),
438        replay_epoch: sealed.replay_epoch,
439        challenge_digest: format!("sha384:{}", hex::encode(&challenge_digest)),
440        proof_digest: bundle_hash.clone(),
441        bundle_hash: sealed.bundle_hash.clone(),
442        issuer_ids: sealed.issuer_ids.clone(),
443        required_scope: sealed.required_scope.clone(),
444        context_policy_digest: sealed.context_policy_digest.clone(),
445        verifier_id: sealed.verifier_id.clone(),
446        agent_id: bundle.agent_id.clone(),
447        requires_rate: !rate_batch.is_empty(),
448        rate_batch,
449        issued_at: sealed.issued_at,
450        expires_at: sealed.expires_at,
451        max_age_seconds: sealed.max_age,
452        clock_skew_seconds: sealed.future_skew,
453        stream_id: bundle.stream_id.clone(),
454        stream_seq: bundle.stream_seq,
455        constraint_evaluators: sealed.evaluator_refs.clone(),
456    };
457    // SPEC-v2 §6.11: cancellation before the claim consumes nothing, so a
458    // caller that has already cancelled never reaches the store.
459    if ctx.is_done() {
460        return err(
461            V2ErrorClass::EvaluationCancelled,
462            "v2 claim cancelled before the store was called: context done",
463        );
464    }
465    let result = store.claim_v2(ctx, claim.clone()).map_err(V2StoreError::into_v2)?;
466    match result.disposition {
467        V2ClaimDisposition::Created => {
468            if result.owner_token.len() != 32 {
469                return plain("v2 claim store returned an invalid evaluator owner token");
470            }
471            // The store's authoritative claim time must itself satisfy the
472            // exclusive challenge deadlines; otherwise evaluation is
473            // interrupted.
474            let claim_time_valid = v2_challenge_time_current(
475                result.claimed_at,
476                sealed.issued_at,
477                sealed.expires_at,
478                sealed.max_age,
479                sealed.future_skew,
480            );
481            let token = V2EvaluationToken {
482                state: Arc::new(TokenState {
483                    claim_id: claim.claim_id.clone(),
484                    claim: claim.clone(),
485                    proof_digest: claim.proof_digest.clone(),
486                    required_scope: sealed.required_scope.clone(),
487                    future_skew: sealed.future_skew,
488                    expected: Arc::clone(sealed),
489                    used: AtomicBool::new(false),
490                    evaluation_complete: AtomicBool::new(false),
491                    claim_time_valid,
492                    claimed_at: result.claimed_at,
493                    rate_batch: claim.rate_batch.clone(),
494                    owner_token: result.owner_token.clone(),
495                    m: Mutex::new(TokenMut::default()),
496                }),
497            };
498            Ok((claim, result.disposition, Some(token)))
499        }
500        V2ClaimDisposition::InProgress | V2ClaimDisposition::TerminalReplay => {
501            if !result.owner_token.is_empty() {
502                return plain("v2 exact retry must not receive evaluator ownership");
503            }
504            Ok((claim, result.disposition, None))
505        }
506    }
507}
508
509// ---------------------------------------------------------------------------
510// FinalizeClaimProofBundleV2
511
512/// Why the finalization helper did not commit: its own refusal (Go: a plain
513/// error from the helper) or the store's error.
514#[derive(Debug, Clone)]
515pub(crate) enum FinalizeFailure {
516    Own(V2Error),
517    Store(V2StoreError),
518}
519
520/// Go `FinalizeClaimProofBundleV2`: commit a terminal local evaluation
521/// through the same opaque capability that won the atomic claim. Results that
522/// still need status or rate checks cannot be finalized. An ambiguous store
523/// failure can be retried only with the identical result and receipt. A
524/// barrier store's exact [`V2StoreError::RateLimitExceeded`] proves rollback,
525/// changes the token to constraint_denied, and requires a new deny result and
526/// receipt.
527///
528/// Classes (Go returns its own refusals unclassified): a helper refusal is
529/// `configuration_invalid`, a cancelled context is `evaluation_cancelled`, an
530/// unclassified store failure is `claim_store_unavailable`; classified store
531/// errors are returned as the store reported them. `RateLimitExceeded` is
532/// returned as that variant, so callers can still match it, and its
533/// [`V2StoreError::class`] is `claim_store_unavailable`, as in Go.
534pub fn finalize_claim_proof_bundle_v2(
535    ctx: &V2Context,
536    store: &dyn ClaimStoreV2,
537    token: &V2EvaluationToken,
538    terminal_result: &[u8],
539    receipt_body: &[u8],
540) -> Result<bool, V2StoreError> {
541    if ctx.is_done() {
542        return Err(V2StoreError::Classified(V2Error::new(
543            V2ErrorClass::EvaluationCancelled,
544            "v2 finalization context is done",
545        )));
546    }
547    match finalize_claim_proof_bundle_v2_inner(ctx, store, token, terminal_result, receipt_body) {
548        Ok(finalized) => Ok(finalized),
549        Err(FinalizeFailure::Own(e)) => Err(V2StoreError::Classified(e.classify(V2ErrorClass::ConfigurationInvalid))),
550        Err(FinalizeFailure::Store(V2StoreError::Unavailable(m))) => Err(V2StoreError::Classified(V2Error::new(
551            V2ErrorClass::ClaimStoreUnavailable,
552            m,
553        ))),
554        Err(FinalizeFailure::Store(e)) => Err(e),
555    }
556}
557
558pub(crate) fn finalize_claim_proof_bundle_v2_inner(
559    ctx: &V2Context,
560    store: &dyn ClaimStoreV2,
561    token: &V2EvaluationToken,
562    terminal_result: &[u8],
563    receipt_body: &[u8],
564) -> Result<bool, FinalizeFailure> {
565    let own = |m: &str| Err(FinalizeFailure::Own(V2Error::plain(m)));
566    let state = &token.state;
567    if state.owner_token.len() != 32 || state.claim_id.is_empty() {
568        return own("v2 claim store and valid evaluator capability are required");
569    }
570    if ctx.is_done() {
571        return own("v2 finalization context is done");
572    }
573    let mut m = state.lock();
574    if !state.evaluation_complete.load(Ordering::SeqCst) {
575        return own("v2 proof evaluation has not completed");
576    }
577    let Some(decision) = terminal_decision_for_v2_evaluation(&m.evaluation_status, &m.evaluation_reason) else {
578        return own("v2 proof evaluation has not reached a terminal local result");
579    };
580    validate_v2_finalization_payload(&state.claim, terminal_result, receipt_body).map_err(FinalizeFailure::Own)?;
581    if !terminal_payload_matches_v2(terminal_result, receipt_body, decision, &m.evaluation_reason) {
582        return own("v2 terminal result does not match the completed local evaluation");
583    }
584    if (decision == "allow" && m.allow_valid_until <= 0) || (decision != "allow" && m.allow_valid_until != 0) {
585        return own("v2 terminal result lacks a valid allow freshness horizon");
586    }
587    if m.rate_at_finalization && store.rate_at_finalization_view().is_none() {
588        return own("v2 rate-at-finalization requires an atomic rate store");
589    }
590    let payload_digest = v2_finalization_payload_digest(terminal_result, receipt_body);
591    if m.finalization_started && m.finalization_digest != payload_digest {
592        return own("v2 evaluator capability cannot change its terminal result or receipt body");
593    }
594    m.finalization_started = true;
595    m.finalization_digest = payload_digest;
596    let result = store.finalize_v2_claim(
597        ctx,
598        &state.claim_id,
599        &state.owner_token,
600        terminal_result,
601        receipt_body,
602        m.allow_valid_until,
603    );
604    if let Err(V2StoreError::RateLimitExceeded) = &result {
605        if m.rate_at_finalization && decision == "allow" && store.rate_at_finalization_view().is_some() {
606            m.evaluation_status = "constraint_denied".into();
607            m.evaluation_reason = "constraint_denied".into();
608            m.allow_valid_until = 0;
609            m.rate_at_finalization = false;
610            m.finalization_started = false;
611            m.finalization_digest = [0; 32];
612        }
613    }
614    result.map_err(FinalizeFailure::Store)
615}
616
617/// Whether the claim ID is the stable claim ID of the claim's (namespace,
618/// replay_epoch, ChallengeClaimDigest) key (SPEC-v2 §2.4, §7.3). A store keyed
619/// by claim ID refuses a supplied ID not derived from that key, which could
620/// create a second claim for one challenge, and resumption refuses a stored
621/// record whose ID is not derived from it.
622pub(crate) fn claim_id_matches_key(claim: &V2ChallengeClaim) -> bool {
623    let Some(encoded) = claim.challenge_digest.strip_prefix("sha384:") else {
624        return false;
625    };
626    if encoded.len() != 96 || !encoded.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) {
627        return false;
628    }
629    let Ok(digest) = hex::decode(encoded) else {
630        return false;
631    };
632    protocol_claim_id_from_digest_v2(&claim.namespace, claim.replay_epoch, &digest).is_ok_and(|id| id == claim.claim_id)
633}
634
635/// Go `ValidateV2FinalizationPayload`: checks that a terminal result and its
636/// unsigned receipt outbox body belong to the sealed claim (SPEC-v2 §7.5).
637/// The body must decode strictly as a canonical receipt body (`malformed`
638/// otherwise). Its `verifier_id`, `agent_id`, `bundle_hash`, `issuer_ids`
639/// (the sorted, distinct sealed issuer IDs), `required_scope`, and
640/// `constraint_evaluators` must equal the sealed claim's values; its
641/// `context_policy_digest` must equal the sealed claim's (null for a
642/// policy-less claim) unless `context_assessment` is `not_evaluated`, when it
643/// must be null. The terminal result must be exactly the RatifyCanonicalJSON
644/// of the body's `decision`, `decision_reason` and `identity_status`
645/// (SPEC-v2 §7.13); any difference is
646/// `configuration_invalid`. [`finalize_claim_proof_bundle_v2`] applies it
647/// before the store is called, and a claim store applies it inside its
648/// finalization compare-and-set so that no caller can commit a body for
649/// another proof.
650pub fn validate_v2_finalization_payload(
651    claim: &V2ChallengeClaim,
652    terminal_result: &[u8],
653    receipt_body: &[u8],
654) -> V2Result<()> {
655    (|| {
656        let body = decode_verification_receipt_body_v2(receipt_body)?;
657        let mut issuers = claim.issuer_ids.clone();
658        issuers.sort();
659        issuers.dedup();
660        if body.verifier_id != claim.verifier_id {
661            return plain("v2 receipt body verifier_id differs from the sealed claim");
662        }
663        if body.agent_id != claim.agent_id {
664            return plain("v2 receipt body agent_id differs from the sealed claim");
665        }
666        if body.bundle_hash != claim.bundle_hash {
667            return plain("v2 receipt body bundle_hash differs from the sealed claim");
668        }
669        if body.issuer_ids != issuers {
670            return plain("v2 receipt body issuer_ids differ from the sealed claim");
671        }
672        if body.required_scope != claim.required_scope {
673            return plain("v2 receipt body required_scope differs from the sealed claim");
674        }
675        let want_policy_digest = (body.context_assessment != "not_evaluated" && !claim.context_policy_digest.is_empty())
676            .then_some(&claim.context_policy_digest);
677        if body.context_policy_digest.as_ref() != want_policy_digest {
678            return plain("v2 receipt body context_policy_digest differs from the sealed claim");
679        }
680        if body.constraint_evaluators != claim.constraint_evaluators {
681            return plain("v2 receipt body constraint_evaluators differ from the sealed evaluator snapshot");
682        }
683        if !terminal_payload_matches_v2(terminal_result, receipt_body, &body.decision, &body.decision_reason) {
684            return plain("v2 terminal result is not the canonical decision, reason and identity status of the receipt body");
685        }
686        Ok(())
687    })()
688    .map_err(|e| e.classify(V2ErrorClass::ConfigurationInvalid))
689}
690
691/// Go `terminalDecisionForV2Evaluation`.
692pub(crate) fn terminal_decision_for_v2_evaluation(status: &str, reason: &str) -> Option<&'static str> {
693    if reason == "evaluation_interrupted" {
694        return (status == "authorization_unverified").then_some("indeterminate");
695    }
696    let (decision, ok) = match status {
697        "authorization_unverified" => (
698            "indeterminate",
699            matches!(reason, "trust_unavailable" | "action_context_unverified" | "status_unavailable" | "status_stale"),
700        ),
701        "authorized_agent" => ("allow", reason == "authorized"),
702        "constraint_denied" | "constraint_unverifiable" | "constraint_unknown" | "unauthorized" | "invalid_scope"
703        | "scope_denied" => ("deny", reason == status),
704        "revoked" => ("deny", reason == "delegation_revoked"),
705        "invalid" => ("deny", reason == "proof_invalid"),
706        "delegation_not_authorized" => ("deny", reason == "not_delegated" || reason == "delegation_not_authorized"),
707        "expired" => ("deny", reason == "delegation_expired"),
708        _ => return None,
709    };
710    ok.then_some(decision)
711}
712
713/// Go `terminalPayloadMatchesV2`: the body is a JSON object without
714/// duplicate keys at any level whose `decision` and `decision_reason` are
715/// strings equal to the expected values, and the terminal result is exactly
716/// the RatifyCanonicalJSON of its decision, decision_reason and
717/// identity_status (SPEC-v2 §7.13).
718pub(crate) fn terminal_payload_matches_v2(
719    terminal_result: &[u8],
720    receipt_body: &[u8],
721    want_decision: &str,
722    want_reason: &str,
723) -> bool {
724    fn read(value: &[u8]) -> Option<(String, String, String)> {
725        let root = parse_json(value).ok()?;
726        let JV::Obj(fields) = &root.v else {
727            return None;
728        };
729        let field = |name: &str| -> Option<String> {
730            match fields.iter().find(|(k, _)| k == name).map(|(_, v)| &v.v) {
731                Some(JV::Str(s)) => Some(s.clone()),
732                // Go json.Unmarshal of null into a string leaves "".
733                Some(JV::Null) => Some(String::new()),
734                _ => None,
735            }
736        };
737        Some((field("decision")?, field("decision_reason")?, field("identity_status")?))
738    }
739    match read(receipt_body) {
740        Some((decision, reason, identity)) if decision == want_decision && reason == want_reason => {
741            terminal_result_json(&decision, &reason, &identity).is_ok_and(|want| want == terminal_result)
742        }
743        _ => false,
744    }
745}
746
747/// Go `v2FinalizationPayloadDigest`.
748pub(crate) fn v2_finalization_payload_digest(terminal_result: &[u8], receipt_body: &[u8]) -> [u8; 32] {
749    let mut h = Sha256::new();
750    h.update((terminal_result.len() as u64).to_be_bytes());
751    h.update(terminal_result);
752    h.update((receipt_body.len() as u64).to_be_bytes());
753    h.update(receipt_body);
754    h.finalize().into()
755}