1use 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#[derive(Debug, Clone, PartialEq, Eq)]
34pub enum V2StoreError {
35 Classified(V2Error),
38 Unavailable(String),
41 ClaimProofConflict,
44 RateLimitExceeded,
46 ReleaseStateMismatch,
48 AcknowledgementNotFound,
50 ChallengeIssuanceConflict,
53 ChallengeIssuanceNotFound,
55}
56
57impl V2StoreError {
58 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 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 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#[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 pub constraint_evaluators: Vec<ConstraintEvaluatorRefV2>,
156}
157
158#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
160pub enum V2ClaimDisposition {
161 Created,
162 InProgress,
163 TerminalReplay,
164}
165
166impl V2ClaimDisposition {
167 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#[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
195pub trait V2AuthoritativeClock: Send + Sync {
200 fn authoritative_time_v2(&self, ctx: &V2Context) -> Result<i64, V2StoreError>;
201}
202
203pub 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 fn rate_at_finalization_view(&self) -> Option<&dyn V2RateAtFinalizationStore> {
261 None
262 }
263}
264
265pub 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 fn rate_at_finalization_view(&self) -> Option<&dyn V2RateAtFinalizationStore> {
282 None
283 }
284}
285
286pub trait V2RateAtFinalizationStore: ClaimStoreV2 + V2RateReservationStore {
293 fn admits_v2_rate_at_finalization(&self);
294}
295
296pub 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#[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 pub(crate) fn allow_horizon(&self) -> i64 {
363 self.lock().allow_valid_until
364 }
365}
366
367pub 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 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 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#[derive(Debug, Clone)]
515pub(crate) enum FinalizeFailure {
516 Own(V2Error),
517 Store(V2StoreError),
518}
519
520pub 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
617pub(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
635pub 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
691pub(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
713pub(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 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
747pub(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}