Skip to main content

ratify_protocol/v2/
release.rs

1//! Committed versus released (SPEC-v2 §6.9, §7.9). Mirrors Go
2//! `release_v2.go`.
3//!
4//! [`super::verify_proof_bundle_v2`] commits a terminal Protocol result and
5//! returns an opaque [`CommittedV2Outcome`] holding the handoff tuple
6//! {claim_id, receipt_body_digest, challenge_expires_at, allow_horizon} and
7//! the sealed receipt outbox body. It exposes no decision.
8//! [`release_v2_decision`] is the only path to an actionable decision; it
9//! returns released, pending (retryable), withheld (permanent for the claim
10//! once recorded), or rejected (a result of that call's inputs that changes
11//! no claim state).
12//!
13//! There is no production local-log substitute for an independent
14//! checkpoint. The in-memory store in [`super::reference`] exists only for
15//! tests and conformance scenarios.
16
17use std::fmt;
18use std::panic::{catch_unwind, AssertUnwindSafe};
19
20use super::checkpoint_ack::V2CheckpointAcknowledgement;
21use super::claim_store::{V2AuthoritativeClock, V2ChallengeClaim, V2StoreError};
22use super::context::V2Context;
23use super::crypto::{key_id_v2, lower_hex, sha384, verify_v2_statement, V2ObjectType};
24use super::errors::{err, V2Error, V2ErrorClass, V2Result};
25use super::limits::{valid_v2_timestamp, V2_MAX_TIMESTAMP_SECONDS};
26use super::receipt::{
27    decode_verification_receipt_v2, verification_receipt_v2_body, verification_receipt_v2_digest,
28    verification_receipt_v2_signable_bytes, VerificationReceiptV2,
29};
30use crate::types::HybridPublicKey;
31
32/// The immutable, non-actionable handoff from a committed verification to
33/// publication and [`release_v2_decision`]. It carries no decision.
34pub struct CommittedV2Outcome {
35    claim_id: String,
36    verifier_id: String,
37    receipt_body: Vec<u8>,
38    challenge_expires_at: i64,
39    allow_horizon: i64,
40}
41
42impl fmt::Debug for CommittedV2Outcome {
43    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
44        f.debug_struct("CommittedV2Outcome")
45            .field("claim_id", &self.claim_id)
46            .field("receipt_body_digest", &self.receipt_body_digest())
47            .finish_non_exhaustive()
48    }
49}
50
51impl CommittedV2Outcome {
52    pub(crate) fn new(claim: &V2ChallengeClaim, body: &[u8], allow_horizon: i64) -> Self {
53        CommittedV2Outcome {
54            claim_id: claim.claim_id.clone(),
55            verifier_id: claim.verifier_id.clone(),
56            receipt_body: body.to_vec(),
57            challenge_expires_at: claim.expires_at,
58            allow_horizon,
59        }
60    }
61
62    /// The Protocol claim ID of the committed evaluation.
63    pub fn claim_id(&self) -> String {
64        self.claim_id.clone()
65    }
66
67    /// A copy of the sealed receipt outbox body, for the receipt publisher
68    /// only. Applications must not parse it to authorize.
69    pub fn receipt_body(&self) -> Vec<u8> {
70        self.receipt_body.clone()
71    }
72
73    /// [`receipt_outbox_digest_v2`] of the sealed body (SPEC-v2 §4).
74    pub fn receipt_body_digest(&self) -> String {
75        receipt_outbox_digest_v2(&self.receipt_body)
76    }
77
78    /// The sealed exclusive challenge deadline.
79    pub fn challenge_expires_at(&self) -> i64 {
80        self.challenge_expires_at
81    }
82
83    /// The exclusive allow deadline; `None` (null) unless the committed
84    /// result can become an allow.
85    pub fn allow_horizon(&self) -> Option<i64> {
86        (self.allow_horizon > 0).then_some(self.allow_horizon)
87    }
88}
89
90/// A deliberately invalid handoff for SDK conformance tests. Ordinary builds
91/// do not expose a constructor for committed outcomes.
92#[doc(hidden)]
93#[cfg(feature = "test-hooks")]
94pub fn forged_committed_outcome_test_only() -> CommittedV2Outcome {
95    CommittedV2Outcome {
96        claim_id: String::new(),
97        verifier_id: String::new(),
98        receipt_body: Vec::new(),
99        challenge_expires_at: 0,
100        allow_horizon: 0,
101    }
102}
103
104/// `"sha384:" + hex(SHA-384("ratify-protocol-receipt-outbox-v2" || 0x00 || body))`.
105pub fn receipt_outbox_digest_v2(body: &[u8]) -> String {
106    format!(
107        "sha384:{}",
108        hex::encode(sha384(&[b"ratify-protocol-receipt-outbox-v2", &[0], body]))
109    )
110}
111
112/// The Part B receipt outbox drain (§7.7). It signs and appends the exact
113/// committed body for `claim_id` at the next ordered log position, or
114/// returns the receipt already appended for that claim, and returns the
115/// signed receipt wire. It refuses a body that differs from the committed
116/// outbox body.
117pub trait V2ReceiptPublisher: Send + Sync {
118    fn publish_v2_receipt(&self, ctx: &V2Context, claim_id: &str, receipt_body: &[u8]) -> Result<Vec<u8>, V2StoreError>;
119}
120
121/// The caller-configured independent checkpoint (§7.8).
122/// `acknowledge_v2_receipt` accepts only the next sequence of the log,
123/// linked by `previous_entry_hash`, and returns the original acknowledgement
124/// on an identical retry. `get_v2_acknowledgement` returns an
125/// acknowledgement, [`V2StoreError::AcknowledgementNotFound`], or another
126/// error for unavailability.
127pub trait V2ReceiptCheckpoint: Send + Sync {
128    fn acknowledge_v2_receipt(
129        &self,
130        ctx: &V2Context,
131        log_id: &str,
132        sequence: i64,
133        previous_entry_hash: &[u8],
134        entry_hash: &[u8],
135    ) -> Result<V2CheckpointAcknowledgement, V2StoreError>;
136    fn get_v2_acknowledgement(
137        &self,
138        ctx: &V2Context,
139        log_id: &str,
140        sequence: i64,
141    ) -> Result<V2CheckpointAcknowledgement, V2StoreError>;
142}
143
144/// The durable release record of SPEC-v2 §6.9: the release of step 9
145/// (`outcome` released, `reason` empty) or a withheld result of steps 7 and
146/// 8 (`outcome` withheld, `reason` `clock_regressed`, `challenge_expired`, or
147/// `allow_horizon_passed`). `entry_hash` and `ack_timestamp` name the
148/// verified receipt entry and its acknowledgement. The first record for a
149/// claim wins; a claim store returns [`V2StoreError::ReleaseStateMismatch`]
150/// for any different later record and must persist and return every field
151/// unchanged.
152#[derive(Debug, Clone, PartialEq, Eq)]
153pub struct V2ReleaseRecord {
154    pub claim_id: String,
155    pub entry_hash: Vec<u8>,
156    pub ack_timestamp: i64,
157    pub outcome: V2ReleaseStatus,
158    pub reason: String,
159}
160
161/// Go `ValidV2ReleaseRecordOutcome`: whether `outcome` and `reason` form a
162/// release record: released with no reason, or withheld with one of the
163/// reasons release steps 7 and 8 record.
164pub fn valid_v2_release_record_outcome(outcome: V2ReleaseStatus, reason: &str) -> bool {
165    match outcome {
166        V2ReleaseStatus::Released => reason.is_empty(),
167        V2ReleaseStatus::Withheld => {
168            matches!(reason, "clock_regressed" | "challenge_expired" | "allow_horizon_passed")
169        }
170        _ => false,
171    }
172}
173
174/// What the claim store returns to release (§7.3): the sealed handoff
175/// values, the recorded finalization time T_final, any receipt_abandoned
176/// marking, and any prior release record.
177#[derive(Debug, Clone, PartialEq, Eq, Default)]
178pub struct V2TerminalClaimRecord {
179    pub terminal: bool,
180    pub receipt_outbox_digest: String,
181    pub challenge_expires_at: i64,
182    pub allow_horizon: i64,
183    pub finalized_at: i64,
184    pub receipt_abandoned: bool,
185    pub release: Option<V2ReleaseRecord>,
186}
187
188/// The claim-store view release needs. `load_v2_terminal_claim` reports a
189/// claim the store does not hold with a `claim_not_found` error, which
190/// release answers with `rejected / release_state_mismatch`; any other error
191/// is store unavailability (`pending / claim_store_unavailable`).
192/// `record_v2_release` returns [`V2StoreError::ReleaseStateMismatch`] when a
193/// different release or withheld record already exists for the claim.
194pub trait V2ReleaseClaimStore: V2AuthoritativeClock {
195    fn load_v2_terminal_claim(&self, ctx: &V2Context, claim_id: &str) -> Result<V2TerminalClaimRecord, V2StoreError>;
196    fn record_v2_release(&self, ctx: &V2Context, record: V2ReleaseRecord) -> Result<(), V2StoreError>;
197}
198
199/// Caller-authenticated release configuration.
200#[derive(Clone, Copy)]
201pub struct V2ReleaseConfig<'a> {
202    pub verifier_public_key: &'a HybridPublicKey,
203    pub log_id: &'a str,
204    pub claim_store: &'a dyn V2ReleaseClaimStore,
205    pub checkpoint: &'a dyn V2ReceiptCheckpoint,
206}
207
208/// The release outcome class of §6.9.
209#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
210pub enum V2ReleaseStatus {
211    Released,
212    Pending,
213    Withheld,
214    Rejected,
215}
216
217impl V2ReleaseStatus {
218    /// `released`, `pending`, `withheld`, or `rejected`.
219    pub fn as_str(self) -> &'static str {
220        match self {
221            V2ReleaseStatus::Released => "released",
222            V2ReleaseStatus::Pending => "pending",
223            V2ReleaseStatus::Withheld => "withheld",
224            V2ReleaseStatus::Rejected => "rejected",
225        }
226    }
227}
228
229/// The only actionable value in this crate (SPEC-v2 §6.9). It is sealed:
230/// every field is private, [`release_v2_decision`] is its only constructor,
231/// it implements neither `Default`, `Clone` nor any deserializer, and every
232/// accessor returns a copy, so a caller can neither forge a released
233/// decision nor change one it was given.
234pub struct V2ReleasedDecision {
235    claim_id: String,
236    decision: String,
237    reason: String,
238    identity_status: String,
239    granted_scope: Vec<String>,
240    receipt_wire: Vec<u8>,
241    release_time: i64,
242    challenge_expires_at: i64,
243    allow_horizon: i64,
244}
245
246impl fmt::Debug for V2ReleasedDecision {
247    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
248        f.debug_struct("V2ReleasedDecision")
249            .field("claim_id", &self.claim_id)
250            .field("decision", &self.decision)
251            .field("reason", &self.reason)
252            .finish_non_exhaustive()
253    }
254}
255
256impl V2ReleasedDecision {
257    /// The Protocol claim ID of the released evaluation.
258    pub fn claim_id(&self) -> String {
259        self.claim_id.clone()
260    }
261
262    /// The released decision: "allow", "deny", or "indeterminate". Use
263    /// [`V2ReleasedDecision::allowed`], not this value, to gate a side effect.
264    pub fn decision(&self) -> String {
265        self.decision.clone()
266    }
267
268    /// The released decision reason.
269    pub fn reason(&self) -> String {
270        self.reason.clone()
271    }
272
273    /// The released identity status.
274    pub fn identity_status(&self) -> String {
275        self.identity_status.clone()
276    }
277
278    /// A copy of the released granted scope.
279    pub fn granted_scope(&self) -> Vec<String> {
280        self.granted_scope.clone()
281    }
282
283    /// A copy of the signed receipt wire verified during release.
284    pub fn receipt_wire(&self) -> Vec<u8> {
285        self.receipt_wire.clone()
286    }
287
288    /// A freshly decoded copy of the signed receipt verified during release.
289    pub fn receipt(&self) -> V2Result<VerificationReceiptV2> {
290        if self.receipt_wire.is_empty() {
291            return err(V2ErrorClass::Malformed, "v2 released decision carries no receipt");
292        }
293        decode_verification_receipt_v2(&self.receipt_wire)
294    }
295
296    /// The checkpoint acknowledgement time of the release.
297    pub fn release_time(&self) -> i64 {
298        self.release_time
299    }
300
301    /// The sealed exclusive challenge deadline.
302    pub fn challenge_expires_at(&self) -> i64 {
303        self.challenge_expires_at
304    }
305
306    /// The sealed exclusive allow deadline; `None` unless the released
307    /// decision is an allow.
308    pub fn allow_horizon(&self) -> Option<i64> {
309        (self.allow_horizon > 0).then_some(self.allow_horizon)
310    }
311
312    /// Whether this released allow may be acted on now. It reads the
313    /// receiver's authoritative clock and compares that time only with the
314    /// sealed exclusive deadlines: true only when the released decision is an
315    /// allow and now < challenge_expires_at and now < allow_horizon. A clock
316    /// error, panic, regression, or reading outside the timestamp domain is
317    /// false. Call it immediately before the side effect.
318    pub fn allowed(&self, ctx: &V2Context, clock: &dyn V2AuthoritativeClock) -> bool {
319        if self.decision != "allow" || self.receipt_wire.is_empty() || self.allow_horizon <= 0 {
320            return false;
321        }
322        match read_v2_authoritative_time(ctx, clock) {
323            Ok(now) => now < self.challenge_expires_at && now < self.allow_horizon,
324            Err(_) => false,
325        }
326    }
327}
328
329/// The result of [`release_v2_decision`]. `decision` is present only when
330/// `status` is released; `reason` is empty only when released. Only
331/// [`V2ReleasedDecision::allowed`] may gate a side effect.
332#[derive(Debug)]
333pub struct V2ReleaseResult {
334    pub status: V2ReleaseStatus,
335    pub reason: String,
336    decision: Option<V2ReleasedDecision>,
337}
338
339impl V2ReleaseResult {
340    /// The released decision (present only when released).
341    pub fn decision(&self) -> Option<&V2ReleasedDecision> {
342        self.decision.as_ref()
343    }
344
345    /// Take the released decision out of the result.
346    pub fn into_decision(self) -> Option<V2ReleasedDecision> {
347        self.decision
348    }
349}
350
351fn release_result_v2(status: V2ReleaseStatus, reason: &str) -> V2ReleaseResult {
352    V2ReleaseResult {
353        status,
354        reason: reason.into(),
355        decision: None,
356    }
357}
358
359/// Go `ReleaseV2Decision`: the release steps of SPEC-v2 §6.9 in order,
360/// stopping at the first that does not pass. `signed_receipt` is the
361/// publisher's signed receipt wire, or `None` when it has not been appended
362/// yet.
363pub fn release_v2_decision(
364    ctx: &V2Context,
365    committed: &CommittedV2Outcome,
366    signed_receipt: Option<&[u8]>,
367    config: V2ReleaseConfig<'_>,
368) -> V2ReleaseResult {
369    use V2ReleaseStatus::*;
370    if committed.claim_id.is_empty() || committed.receipt_body.is_empty() {
371        return release_result_v2(Rejected, "release_state_mismatch");
372    }
373    if config.log_id.len() != 32 || !lower_hex(config.log_id) {
374        return release_result_v2(Rejected, "release_state_mismatch");
375    }
376    // 1. Committed state.
377    let record = match catch_unwind(AssertUnwindSafe(|| {
378        config.claim_store.load_v2_terminal_claim(ctx, &committed.claim_id)
379    })) {
380        Ok(Ok(r)) => r,
381        // Only an unavailable store is retryable. A store that answers that
382        // it holds no such claim (claim_not_found) did not produce this
383        // handoff: a state mismatch, never pending.
384        Ok(Err(e)) if e.class() == Some(V2ErrorClass::ClaimNotFound) => {
385            return release_result_v2(Rejected, "release_state_mismatch")
386        }
387        _ => return release_result_v2(Pending, "claim_store_unavailable"),
388    };
389    if record.receipt_abandoned {
390        return release_result_v2(Withheld, "receipt_abandoned");
391    }
392    let verifier_id = key_id_v2(config.verifier_public_key);
393    if !record.terminal
394        || record.receipt_outbox_digest != committed.receipt_body_digest()
395        || record.challenge_expires_at != committed.challenge_expires_at
396        || record.allow_horizon != committed.allow_horizon
397        || verifier_id.as_deref().ok() != Some(committed.verifier_id.as_str())
398    {
399        return release_result_v2(Rejected, "release_state_mismatch");
400    }
401    // A recorded withheld result is permanent for the claim and is returned
402    // before any other step. A record that is neither a valid withheld nor a
403    // valid released record for this claim is a state mismatch.
404    if let Some(release) = &record.release {
405        if release.claim_id != committed.claim_id || !valid_v2_release_record_outcome(release.outcome, &release.reason) {
406            return release_result_v2(Rejected, "release_state_mismatch");
407        }
408        if release.outcome == Withheld {
409            return release_result_v2(Withheld, &release.reason);
410        }
411    }
412    // 2. Receipt.
413    let Some(signed_receipt) = signed_receipt.filter(|r| !r.is_empty()) else {
414        return release_result_v2(Pending, "receipt_not_appended");
415    };
416    let receipt = match verify_published_v2_receipt(signed_receipt, config) {
417        Ok(r) if r.verifier_id == committed.verifier_id => r,
418        _ => return release_result_v2(Rejected, "receipt_invalid"),
419    };
420    // 3. Body binding.
421    match verification_receipt_v2_body(&receipt) {
422        Ok(body) if body == committed.receipt_body => {}
423        _ => return release_result_v2(Rejected, "receipt_body_mismatch"),
424    }
425    let Ok(entry_hash) = verification_receipt_v2_digest(&receipt) else {
426        return release_result_v2(Rejected, "receipt_invalid");
427    };
428    // 4. Prior release: the same receipt entry. A recorded release only
429    // enforces sameness; it never substitutes for the acknowledgement.
430    if record.release.as_ref().is_some_and(|r| r.entry_hash != entry_hash) {
431        return release_result_v2(Rejected, "release_state_mismatch");
432    }
433    // 5. Predecessor.
434    if receipt.sequence > 1 {
435        let previous = match get_v2_acknowledgement_safely(ctx, config.checkpoint, &receipt.log_id, receipt.sequence - 1) {
436            Ok(a) => a,
437            Err(_) => return release_result_v2(Pending, "acknowledgement_unavailable"),
438        };
439        if previous.log_id != receipt.log_id
440            || previous.sequence != receipt.sequence - 1
441            || previous.entry_hash != receipt.previous_receipt_hash
442        {
443            return release_result_v2(Rejected, "log_predecessor_mismatch");
444        }
445    }
446    // 6. Acknowledgement.
447    let ack = match get_v2_acknowledgement_safely(ctx, config.checkpoint, &receipt.log_id, receipt.sequence) {
448        Ok(a) => a,
449        Err(_) => return release_result_v2(Pending, "acknowledgement_unavailable"),
450    };
451    if ack.log_id != receipt.log_id || ack.sequence != receipt.sequence || ack.entry_hash != entry_hash {
452        return release_result_v2(Rejected, "acknowledgement_mismatch");
453    }
454    if record.release.as_ref().is_some_and(|r| r.ack_timestamp != ack.timestamp) {
455        return release_result_v2(Rejected, "release_state_mismatch");
456    }
457    // withhold ends release at step 7 or 8. With no release recorded it
458    // durably records the withheld result first, so it is permanent for the
459    // claim; if the store is unavailable this call is still withheld. With a
460    // release already recorded, that first record stands and this call alone
461    // is withheld.
462    let withhold = |reason: &str| -> V2ReleaseResult {
463        if record.release.is_none() {
464            let withheld = V2ReleaseRecord {
465                claim_id: committed.claim_id.clone(),
466                entry_hash: entry_hash.clone(),
467                ack_timestamp: ack.timestamp,
468                outcome: Withheld,
469                reason: reason.into(),
470            };
471            if let Err(V2StoreError::ReleaseStateMismatch) = record_v2_release_safely(ctx, config.claim_store, withheld) {
472                return release_result_v2(Rejected, "release_state_mismatch");
473            }
474        }
475        release_result_v2(Withheld, reason)
476    };
477    // 7. Clock.
478    let now = match read_v2_authoritative_time(ctx, config.claim_store) {
479        Ok(now) => now,
480        Err(e) if e.class == V2ErrorClass::ClockRegressed && e.is_classified() => return withhold("clock_regressed"),
481        Err(_) => return release_result_v2(Pending, "clock_unavailable"),
482    };
483    if !valid_v2_timestamp(record.finalized_at)
484        || !valid_v2_timestamp(ack.timestamp)
485        || record.finalized_at > ack.timestamp
486        || ack.timestamp > now
487    {
488        return withhold("clock_regressed");
489    }
490    // 8. Deadlines.
491    if ack.timestamp >= committed.challenge_expires_at || now >= committed.challenge_expires_at {
492        return withhold("challenge_expired");
493    }
494    if receipt.decision == "allow"
495        && (committed.allow_horizon <= 0 || ack.timestamp >= committed.allow_horizon || now >= committed.allow_horizon)
496    {
497        return withhold("allow_horizon_passed");
498    }
499    // 9. Record.
500    if record.release.is_none() {
501        let new_record = V2ReleaseRecord {
502            claim_id: committed.claim_id.clone(),
503            entry_hash: entry_hash.clone(),
504            ack_timestamp: ack.timestamp,
505            outcome: Released,
506            reason: String::new(),
507        };
508        match record_v2_release_safely(ctx, config.claim_store, new_record) {
509            Ok(()) => {}
510            Err(V2StoreError::ReleaseStateMismatch) => return release_result_v2(Rejected, "release_state_mismatch"),
511            Err(_) => return release_result_v2(Pending, "claim_store_unavailable"),
512        }
513    }
514    // 10. Return.
515    let allow = receipt.decision == "allow";
516    V2ReleaseResult {
517        status: Released,
518        reason: String::new(),
519        decision: Some(V2ReleasedDecision {
520            claim_id: committed.claim_id.clone(),
521            decision: receipt.decision.clone(),
522            reason: receipt.decision_reason.clone(),
523            identity_status: receipt.identity_status.clone(),
524            granted_scope: receipt.granted_scope.clone(),
525            receipt_wire: signed_receipt.to_vec(),
526            release_time: ack.timestamp,
527            challenge_expires_at: committed.challenge_expires_at,
528            allow_horizon: if allow { committed.allow_horizon } else { 0 },
529        }),
530    }
531}
532
533fn verify_published_v2_receipt(wire: &[u8], config: V2ReleaseConfig<'_>) -> V2Result<VerificationReceiptV2> {
534    let receipt = decode_verification_receipt_v2(wire)?;
535    if receipt.log_id != config.log_id {
536        return err(V2ErrorClass::LogStateMismatch, "v2 published receipt belongs to an unconfigured log");
537    }
538    let body = verification_receipt_v2_signable_bytes(&receipt)?;
539    verify_v2_statement(
540        V2ObjectType::VerificationReceipt,
541        &body,
542        &receipt.signature,
543        config.verifier_public_key,
544    )?;
545    Ok(receipt)
546}
547
548fn record_v2_release_safely(
549    ctx: &V2Context,
550    store: &dyn V2ReleaseClaimStore,
551    record: V2ReleaseRecord,
552) -> Result<(), V2StoreError> {
553    catch_unwind(AssertUnwindSafe(|| store.record_v2_release(ctx, record)))
554        .unwrap_or_else(|_| Err(V2StoreError::Unavailable("claim store panicked".into())))
555}
556
557fn get_v2_acknowledgement_safely(
558    ctx: &V2Context,
559    checkpoint: &dyn V2ReceiptCheckpoint,
560    log_id: &str,
561    sequence: i64,
562) -> Result<V2CheckpointAcknowledgement, V2StoreError> {
563    catch_unwind(AssertUnwindSafe(|| checkpoint.get_v2_acknowledgement(ctx, log_id, sequence)))
564        .unwrap_or_else(|_| Err(V2StoreError::Unavailable("checkpoint panicked".into())))
565}
566
567/// Go `readV2AuthoritativeTime`: a store-reported `clock_regressed` keeps its
568/// class; any other failure, a panic, or a reading outside the timestamp
569/// domain is an unavailable clock (an unclassified error).
570pub(crate) fn read_v2_authoritative_time(ctx: &V2Context, clock: &dyn V2AuthoritativeClock) -> V2Result<i64> {
571    let now = match catch_unwind(AssertUnwindSafe(|| clock.authoritative_time_v2(ctx))) {
572        Ok(Ok(now)) => now,
573        Ok(Err(e)) => return Err(e.into_v2()),
574        Err(_) => return Err(V2Error::plain("v2 authoritative clock panicked")),
575    };
576    if !valid_v2_timestamp(now) {
577        return Err(V2Error::plain(format!(
578            "v2 authoritative clock returned {now} outside 0..{V2_MAX_TIMESTAMP_SECONDS}"
579        )));
580    }
581    Ok(now)
582}
583
584#[cfg(test)]
585mod tests {
586    use super::*;
587    use crate::crypto::generate_hybrid_keypair;
588    use crate::v2::reference::Store;
589
590    // lifecycle-scenarios.json `release_forged`: an outcome the verifier never
591    // produced (the Go zero value) is always rejected. Ordinary callers cannot build
592    // one, so this crate-internal test is where the vector's expectation runs.
593    #[test]
594    fn forged_zero_value_outcome_is_rejected() {
595        let (public, private) = generate_hybrid_keypair();
596        let log_id = "dddddddddddddddddddddddddddddd01";
597        let store = Store::new(1_800_000_000, 30, log_id, &private).unwrap();
598        let forged = CommittedV2Outcome {
599            claim_id: String::new(),
600            verifier_id: String::new(),
601            receipt_body: Vec::new(),
602            challenge_expires_at: 0,
603            allow_horizon: 0,
604        };
605        let result = release_v2_decision(
606            &V2Context::background(),
607            &forged,
608            None,
609            V2ReleaseConfig {
610                verifier_public_key: &public,
611                log_id,
612                claim_store: &store,
613                checkpoint: &store,
614            },
615        );
616        assert_eq!(
617            (result.status, result.reason.as_str()),
618            (V2ReleaseStatus::Rejected, "release_state_mismatch")
619        );
620        assert!(result.decision().is_none());
621    }
622}