Skip to main content

ratify_protocol/v2/
evaluation_progress.rs

1//! Persisted evaluation progress and lease-expiry recovery (SPEC-v2 §6.7,
2//! §7.5). Mirrors Go `evaluation_progress_v2.go`.
3
4use std::panic::{catch_unwind, AssertUnwindSafe};
5
6use super::claim_store::{
7    claim_id_matches_key, validate_v2_finalization_payload, ClaimStoreV2, V2ChallengeClaim, V2EvaluationToken,
8    V2StoreError,
9};
10use super::context::V2Context;
11use super::crypto::valid_prefixed_digest;
12use super::errors::{err, plain, Classify, V2Error, V2ErrorClass, V2Result};
13use super::json::{canonical, CJ};
14use super::limits::{valid_v2_timestamp, V2_MAX_TIMESTAMP_SECONDS};
15use super::receipt::{
16    decode_verification_receipt_body_v2, verification_receipt_v2_body, StatusEvidenceEntryV2, VerificationReceiptV2,
17};
18use super::release::CommittedV2Outcome;
19use crate::types::HybridSignature;
20
21/// The per-dimension progress of one claimed evaluation (SPEC-v2 §6.7,
22/// §7.5). The evaluator persists it in the claim store under its evaluator
23/// capability before every external lookup starts and after it completes.
24///
25/// - `trust_assessment`: not_evaluated, unavailable (started, not
26///   completed), trusted, or untrusted.
27/// - `status_assessment`: not_evaluated, unavailable, current, revoked, or
28///   stale.
29/// - `context_assessment`: not_evaluated, bound, or not_required.
30/// - `context_policy_digest` is present exactly when `context_assessment` is
31///   bound or not_required.
32/// - `status_evidence` is empty while `status_assessment` is not_evaluated.
33#[derive(Debug, Clone, PartialEq, Eq)]
34pub struct V2EvaluationProgress {
35    pub trust_assessment: String,
36    pub status_assessment: String,
37    pub context_assessment: String,
38    pub context_policy_digest: Option<String>,
39    pub status_evidence: Vec<StatusEvidenceEntryV2>,
40}
41
42impl Default for V2EvaluationProgress {
43    fn default() -> Self {
44        initial_v2_evaluation_progress()
45    }
46}
47
48/// What a claim store returns to lease-expiry recovery: the sealed claim,
49/// its authoritative claim time T_claim, and the last persisted progress.
50#[derive(Debug, Clone, PartialEq, Eq, Default)]
51pub struct V2InterruptedClaim {
52    pub claim: V2ChallengeClaim,
53    pub claimed_at: i64,
54    pub progress: V2EvaluationProgress,
55}
56
57/// Go `InitialV2EvaluationProgress`: no post-claim check has started.
58pub fn initial_v2_evaluation_progress() -> V2EvaluationProgress {
59    V2EvaluationProgress {
60        trust_assessment: "not_evaluated".into(),
61        status_assessment: "not_evaluated".into(),
62        context_assessment: "not_evaluated".into(),
63        context_policy_digest: None,
64        status_evidence: Vec::new(),
65    }
66}
67
68/// Go `ValidateV2EvaluationProgress` (class `malformed`; Go returns an
69/// unclassified error). A claim store rejects an invalid record, and
70/// recovery refuses to build a receipt from one. (Go's additional "nil
71/// evidence slice" rejection has no Rust counterpart: a `Vec` is never nil.)
72pub fn validate_v2_evaluation_progress(p: &V2EvaluationProgress) -> V2Result<()> {
73    validate_v2_evaluation_progress_inner(p).classify(V2ErrorClass::Malformed)
74}
75
76pub(crate) fn validate_v2_evaluation_progress_inner(p: &V2EvaluationProgress) -> V2Result<()> {
77    if !matches!(p.trust_assessment.as_str(), "not_evaluated" | "unavailable" | "trusted" | "untrusted") {
78        return plain("v2 evaluation progress trust_assessment is invalid");
79    }
80    if !matches!(
81        p.status_assessment.as_str(),
82        "not_evaluated" | "unavailable" | "current" | "revoked" | "stale"
83    ) {
84        return plain("v2 evaluation progress status_assessment is invalid");
85    }
86    if !matches!(p.context_assessment.as_str(), "not_evaluated" | "bound" | "not_required") {
87        return plain("v2 evaluation progress context_assessment is invalid");
88    }
89    if (p.context_assessment == "not_evaluated") != p.context_policy_digest.is_none()
90        || p.context_policy_digest.as_deref().is_some_and(|d| !valid_prefixed_digest(d))
91    {
92        return plain("v2 evaluation progress context_policy_digest does not match context_assessment");
93    }
94    if p.trust_assessment != "trusted"
95        && (p.status_assessment != "not_evaluated" || p.context_assessment != "not_evaluated")
96    {
97        return plain("v2 evaluation progress records status or context without a trusted root");
98    }
99    if p.status_assessment == "not_evaluated" && !p.status_evidence.is_empty() {
100        return plain("v2 evaluation progress status evidence is inconsistent with status_assessment");
101    }
102    Ok(())
103}
104
105/// The canonical terminal-result object `{"decision","decision_reason",
106/// "identity_status"}`.
107pub(crate) fn terminal_result_json(decision: &str, reason: &str, identity_status: &str) -> V2Result<Vec<u8>> {
108    canonical(&CJ::obj(vec![
109        ("decision", CJ::s(decision)),
110        ("decision_reason", CJ::s(reason)),
111        ("identity_status", CJ::s(identity_status)),
112    ]))
113}
114
115/// An empty receipt with the fields every receipt shares; callers fill the
116/// rest (the log position, previous hash and signature are not part of a
117/// receipt body).
118pub(crate) fn receipt_skeleton() -> VerificationReceiptV2 {
119    VerificationReceiptV2 {
120        version: 2,
121        log_id: String::new(),
122        sequence: 0,
123        verifier_id: String::new(),
124        agent_id: String::new(),
125        human_id: String::new(),
126        bundle_hash: String::new(),
127        issuer_ids: Vec::new(),
128        decision: String::new(),
129        decision_reason: String::new(),
130        identity_status: String::new(),
131        trust_assessment: String::new(),
132        status_assessment: String::new(),
133        challenge_assessment: String::new(),
134        constraint_evaluators: Vec::new(),
135        context_assessment: String::new(),
136        context_policy_digest: None,
137        verified_at: 0,
138        required_scope: String::new(),
139        granted_scope: Vec::new(),
140        status_evidence: Vec::new(),
141        previous_receipt_hash: Vec::new(),
142        signature: HybridSignature {
143            ed25519: Vec::new(),
144            ml_dsa_65: Vec::new(),
145        },
146    }
147}
148
149/// Go `V2EvaluationInterruptedResult`: the canonical terminal result object
150/// and receipt outbox body for indeterminate/evaluation_interrupted from the
151/// claim's sealed values and its evaluation progress. `verified_at` is the
152/// claim's authoritative claim time T_claim. Returns `(terminal_result,
153/// receipt_body)`.
154pub fn v2_evaluation_interrupted_result(
155    claim: &V2ChallengeClaim,
156    verified_at: i64,
157    progress: &V2EvaluationProgress,
158) -> V2Result<(Vec<u8>, Vec<u8>)> {
159    if !valid_v2_timestamp(verified_at) {
160        return err(
161            V2ErrorClass::ConfigurationInvalid,
162            "v2 recovery time is outside the timestamp domain",
163        );
164    }
165    validate_v2_evaluation_progress_inner(progress).classify(V2ErrorClass::Malformed)?;
166    let mut issuers = claim.issuer_ids.clone();
167    issuers.sort();
168    issuers.dedup();
169    let mut receipt = receipt_skeleton();
170    receipt.verifier_id = claim.verifier_id.clone();
171    receipt.agent_id = claim.agent_id.clone();
172    receipt.bundle_hash = claim.bundle_hash.clone();
173    receipt.issuer_ids = issuers;
174    receipt.decision = "indeterminate".into();
175    receipt.decision_reason = "evaluation_interrupted".into();
176    receipt.identity_status = "authorization_unverified".into();
177    receipt.trust_assessment = progress.trust_assessment.clone();
178    receipt.status_assessment = progress.status_assessment.clone();
179    receipt.challenge_assessment = "current".into();
180    receipt.context_assessment = progress.context_assessment.clone();
181    receipt.context_policy_digest = progress.context_policy_digest.clone();
182    receipt.verified_at = verified_at;
183    receipt.required_scope = claim.required_scope.clone();
184    receipt.status_evidence = progress.status_evidence.clone();
185    receipt.constraint_evaluators = claim.constraint_evaluators.clone();
186    let receipt_body = verification_receipt_v2_body(&receipt).classify(V2ErrorClass::Malformed)?;
187    let terminal = terminal_result_json("indeterminate", "evaluation_interrupted", "authorization_unverified")
188        .classify(V2ErrorClass::Malformed)?;
189    Ok((terminal, receipt_body))
190}
191
192/// Go `RecoverInterruptedClaimV2`: lease-expiry recovery. Loads the claim's
193/// sealed values, T_claim and persisted progress from the store (which
194/// refuses while the evaluator lease is live), commits the
195/// evaluation_interrupted result built from them, and returns the committed,
196/// non-actionable outcome for publication and release. An identical repeat
197/// returns the same outcome.
198pub fn recover_interrupted_claim_v2(
199    ctx: &V2Context,
200    store: &dyn ClaimStoreV2,
201    claim_id: &str,
202) -> V2Result<CommittedV2Outcome> {
203    if claim_id.is_empty() {
204        return err(
205            V2ErrorClass::ConfigurationInvalid,
206            "v2 recovery requires a context, claim store and claim ID",
207        );
208    }
209    let classify = |e: V2StoreError| e.classified_or(V2ErrorClass::ClaimStoreUnavailable);
210    let interrupted = match catch_unwind(AssertUnwindSafe(|| store.load_v2_interrupted_claim(ctx, claim_id))) {
211        Ok(r) => r.map_err(classify)?,
212        Err(_) => {
213            return err(
214                V2ErrorClass::ClaimStoreUnavailable,
215                "claim store recovery load panicked",
216            )
217        }
218    };
219    if interrupted.claim.claim_id != claim_id {
220        return err(
221            V2ErrorClass::ClaimStoreUnavailable,
222            "v2 claim store returned a different claim for recovery",
223        );
224    }
225    let (terminal, body) =
226        v2_evaluation_interrupted_result(&interrupted.claim, interrupted.claimed_at, &interrupted.progress)?;
227    match catch_unwind(AssertUnwindSafe(|| {
228        store.recover_interrupted_v2_claim(ctx, claim_id, &terminal, &body)
229    })) {
230        Ok(r) => {
231            r.map_err(classify)?;
232        }
233        Err(_) => return err(V2ErrorClass::ClaimStoreUnavailable, "claim store recovery panicked"),
234    }
235    Ok(CommittedV2Outcome::new(&interrupted.claim, &body, 0))
236}
237
238/// Go `V2CommittedClaim`: a terminal claim as the claim store's terminal
239/// compare-and-set persisted it: the sealed claim values, the terminal
240/// result, the sealed receipt outbox body, and the allow horizon (0 unless
241/// the result is an allow).
242#[derive(Debug, Clone, PartialEq, Eq, Default)]
243pub struct V2CommittedClaim {
244    pub claim: V2ChallengeClaim,
245    pub terminal_result: Vec<u8>,
246    pub receipt_body: Vec<u8>,
247    pub allow_horizon: i64,
248}
249
250/// Go `V2CommittedClaimStore`: loads a terminal claim's persisted record for
251/// resumption (SPEC-v2 §7.11). `load_v2_committed_claim` answers
252/// `claim_not_found` for a claim the store does not hold, `claim_lease_live`
253/// for a claim still evaluating under a live lease, and `claim_lease_lost`
254/// for a claim still evaluating after its lease expired (lease-expiry
255/// recovery runs first).
256pub trait V2CommittedClaimStore {
257    fn load_v2_committed_claim(&self, ctx: &V2Context, claim_id: &str) -> Result<V2CommittedClaim, V2StoreError>;
258}
259
260/// Go `ResumeCommittedClaimV2`: returns the handoff of a claim's committed
261/// result from the claim store's persisted record (SPEC-v2 §7.11), for a
262/// service whose handoff was lost after the terminal commit, for example by
263/// a crash before the verifier returned. It checks the record as the
264/// terminal compare-and-set does and never builds or replaces a result; a
265/// record that fails a check is `claim_store_unavailable`. Publication,
266/// checkpoint submission and release then proceed as for a returned handoff.
267pub fn resume_committed_claim_v2(
268    ctx: &V2Context,
269    store: &dyn V2CommittedClaimStore,
270    claim_id: &str,
271) -> V2Result<CommittedV2Outcome> {
272    if claim_id.is_empty() {
273        return err(
274            V2ErrorClass::ConfigurationInvalid,
275            "v2 resumption requires a context, claim store and claim ID",
276        );
277    }
278    let committed = match catch_unwind(AssertUnwindSafe(|| store.load_v2_committed_claim(ctx, claim_id))) {
279        Ok(r) => r.map_err(|e| e.classified_or(V2ErrorClass::ClaimStoreUnavailable))?,
280        Err(_) => {
281            return err(
282                V2ErrorClass::ClaimStoreUnavailable,
283                "claim store committed-claim load panicked",
284            )
285        }
286    };
287    if let Err(e) = validate_v2_committed_claim(&committed, claim_id) {
288        return err(
289            V2ErrorClass::ClaimStoreUnavailable,
290            format!("v2 claim store returned a committed record that fails its checks: {}", e.message),
291        );
292    }
293    Ok(CommittedV2Outcome::new(&committed.claim, &committed.receipt_body, committed.allow_horizon))
294}
295
296/// Go `validateV2CommittedClaim`: the terminal compare-and-set's checks on a
297/// persisted record: the claim ID (§7.3), the finalization payload (§7.5),
298/// and the allow horizon (§6.8).
299fn validate_v2_committed_claim(committed: &V2CommittedClaim, claim_id: &str) -> V2Result<()> {
300    let claim = &committed.claim;
301    if claim.claim_id != claim_id {
302        return plain("the record is for a different claim");
303    }
304    if !claim_id_matches_key(claim) {
305        return plain("the claim ID does not derive from the claim's replay key");
306    }
307    validate_v2_finalization_payload(claim, &committed.terminal_result, &committed.receipt_body)?;
308    let body = decode_verification_receipt_body_v2(&committed.receipt_body)?;
309    if body.decision == "allow" {
310        if committed.allow_horizon <= 0 || committed.allow_horizon > V2_MAX_TIMESTAMP_SECONDS {
311            return plain("an allow has no allow horizon in the timestamp domain");
312        }
313    } else if committed.allow_horizon != 0 {
314        return plain("a result that is not an allow has an allow horizon");
315    }
316    Ok(())
317}
318
319/// Go `recordV2ProgressSafely`: persist progress under the evaluator
320/// capability. Any failure stops the evaluation before the next provider
321/// call.
322pub(crate) fn record_v2_progress_safely(
323    ctx: &V2Context,
324    store: &dyn ClaimStoreV2,
325    token: &V2EvaluationToken,
326    progress: &V2EvaluationProgress,
327) -> V2Result<()> {
328    validate_v2_evaluation_progress_inner(progress)?;
329    let state = &token.state;
330    match catch_unwind(AssertUnwindSafe(|| {
331        store.record_v2_evaluation_progress(ctx, &state.claim_id, &state.owner_token, progress.clone())
332    })) {
333        Ok(r) => r.map_err(|e| e.classified_or(V2ErrorClass::ClaimStoreUnavailable)),
334        Err(_) => Err(V2Error::new(
335            V2ErrorClass::ClaimStoreUnavailable,
336            "claim store progress write panicked",
337        )),
338    }
339}