Skip to main content

ratify_protocol/v2/
status_provenance.rs

1//! Authenticated status at the verifier boundary (SPEC-v2 §6.5). Mirrors Go
2//! `status_provenance_v2.go`.
3//!
4//! The status provider never supplies a StatusResult. For each distinct
5//! issuer in the verified chain, in ascending byte order of issuer ID, the
6//! verifier:
7//!  1. loads the committed `SecurityJournalV2` at its anchored head and
8//!     requires the caller-authenticated status key to equal the journal's
9//!     current epoch binding for the issuer;
10//!  2. checks role separation by complete key ID and both component digests;
11//!  3. asks the provider for a bounded batch of signed lists and pushes;
12//!  4. decodes every object and verifies it under the selected key (any
13//!     failure rejects the whole batch);
14//!  5. applies the batch, sorted by sequence, then code, then
15//!     StatusEvidenceDigest, as one journal transition committed by
16//!     compare-and-swap against the head loaded in step 1; on a conflict it
17//!     reloads, rechecks steps 1 and 2, and reapplies the same batch exactly
18//!     once more;
19//!  6. derives each CertificateRef result from the committed journal state.
20//!
21//! A missing binding, unanchored or unmigrated journal, role violation,
22//! provider error/panic, malformed/oversized/unauthenticated batch, reducer
23//! rejection, store failure or panic, or compare-and-swap conflict makes every
24//! reference of that issuer indeterminate/unavailable with no evidence. If
25//! the caller's context ends during the stage, nothing is committed and the
26//! stage reports cancellation.
27
28use std::collections::BTreeMap;
29use std::fmt;
30use std::panic::{catch_unwind, AssertUnwindSafe};
31use std::sync::Arc;
32
33use super::context::V2Context;
34use super::errors::{plain, V2Error, V2Result};
35use super::journal::{
36    commit_security_journal_transition_v2, key_role_binding_v2, load_anchored_security_journal_v2,
37    require_journal_status_key_v2, KeyRoleBindingV2, SecurityJournalStoreErrorV2,
38    SecurityJournalStoreV2, SecurityJournalV2,
39};
40use super::limits::{MAX_STATUS_EVIDENCE_BATCH_BYTES_V2, MAX_STATUS_EVIDENCE_BATCH_OBJECTS_V2};
41use super::status::{
42    aggregate_certificate_status_v2, apply_revocation_list_v2, apply_revocation_push_v2,
43    key_id_plain, revocation_status_for_cert_inner, RevocationStatusPolicyV2,
44    RevocationStatusResultV2, V2CertificateStatusCheck, V2StatusAssessment, V2StatusRoleBindings,
45    LIST, PUSH,
46};
47use super::status_batch::v2_status_evidence_batch_encoded_length;
48use super::wire::{
49    decode_revocation_list_v2, decode_revocation_push_v2, status_evidence_digest_list_v2,
50    status_evidence_digest_push_v2, verify_revocation_list_v2_signature,
51    verify_revocation_push_v2_signature, ProofBundleV2, RevocationListV2, RevocationPushV2,
52};
53use crate::types::HybridPublicKey;
54
55/// An issuer-scoped certificate reference (Go `CertificateRefV2`, declared
56/// in `verify_v2.go`).
57#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
58pub struct CertificateRefV2 {
59    pub issuer_id: String,
60    pub cert_id: String,
61}
62
63/// The caller-authenticated status-key binding for one issuer. It must equal
64/// the binding retained in the security journal at that epoch, and the epoch
65/// must be the issuer's current journal epoch.
66#[derive(Debug, Clone, PartialEq, Eq)]
67pub struct V2StatusKeyConfig {
68    pub epoch: u64,
69    pub key: HybridPublicKey,
70}
71
72/// What the verifier asks a status provider for. It is chosen by the
73/// verifier from authenticated configuration, never from the proof. `refs`
74/// are the issuer's CertificateRefs in chain order.
75#[derive(Debug, Clone, PartialEq, Eq)]
76pub struct V2StatusEvidenceRequest {
77    pub issuer_id: String,
78    pub status_key_epoch: u64,
79    pub status_key_id: String,
80    pub refs: Vec<CertificateRefV2>,
81}
82
83/// One signed status object exactly as received. `object_type` is 0x0003
84/// (revocation list) or 0x0005 (revocation push).
85#[derive(Debug, Clone, PartialEq, Eq)]
86pub struct V2StatusEvidenceObject {
87    pub object_type: u16,
88    pub wire: Vec<u8>,
89}
90
91/// A provider's bounded response for one issuer. An empty batch is valid:
92/// the result then comes from retained journal state.
93#[derive(Debug, Clone, PartialEq, Eq, Default)]
94pub struct V2StatusEvidenceBatch {
95    pub objects: Vec<V2StatusEvidenceObject>,
96}
97
98/// A status provider's failure. Any provider failure (including a panic,
99/// which the verifier contains) makes every reference of the issuer
100/// unavailable; the message is diagnostic only.
101#[derive(Debug, Clone, PartialEq, Eq)]
102pub struct V2StatusProviderError {
103    pub message: String,
104}
105
106impl V2StatusProviderError {
107    pub fn new(message: impl Into<String>) -> Self {
108        V2StatusProviderError {
109            message: message.into(),
110        }
111    }
112}
113
114impl fmt::Display for V2StatusProviderError {
115    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
116        write!(f, "v2 status provider: {}", self.message)
117    }
118}
119
120impl std::error::Error for V2StatusProviderError {}
121
122/// The status evidence provider (Go `V2VerifyCallbacks.StatusEvidence`): a
123/// shared, thread-safe closure returning a bounded batch of signed status
124/// objects for one issuer. It never returns a status result.
125pub type V2StatusEvidenceProvider = Arc<
126    dyn Fn(
127            &V2Context,
128            &V2StatusEvidenceRequest,
129        ) -> Result<V2StatusEvidenceBatch, V2StatusProviderError>
130        + Send
131        + Sync,
132>;
133
134/// Exactly the inputs Go `runV2StatusStage` reads from `V2VerifyRequest`
135/// (`StatusKeys`, `StatusPolicy`) and `V2VerifyCallbacks` (`StatusEvidence`,
136/// `StatusJournal`). A `None` provider or journal makes every issuer
137/// unavailable, as a nil Go callback does.
138pub(crate) struct V2StatusStageInputs<'a> {
139    pub status_evidence: Option<&'a V2StatusEvidenceProvider>,
140    pub status_journal: Option<&'a dyn SecurityJournalStoreV2>,
141    pub status_keys: &'a BTreeMap<String, V2StatusKeyConfig>,
142    pub status_policy: &'a RevocationStatusPolicyV2,
143}
144
145/// Go `v2StatusStageResult`. `cancelled` replaces Go's `ctx.Err()`: the
146/// caller's context ended during the stage and nothing further was committed.
147#[derive(Debug, Clone)]
148pub(crate) struct V2StatusStageResult {
149    pub assessment: V2StatusAssessment,
150    pub cancelled: bool,
151    // Go reads it only in tests (provider-call accounting).
152    #[cfg_attr(not(test), allow(dead_code))]
153    pub queries: usize,
154}
155
156pub(crate) enum V2VerifiedStatusPayload {
157    List(RevocationListV2),
158    Push(RevocationPushV2),
159}
160
161pub(crate) struct V2VerifiedStatusObject {
162    pub code: u16,
163    pub sequence: i64,
164    pub digest: Vec<u8>,
165    pub payload: V2VerifiedStatusPayload,
166}
167
168fn unavailable_assessment() -> V2StatusAssessment {
169    V2StatusAssessment {
170        assessment: "unavailable".into(),
171        reason: "status_unavailable".into(),
172        evidence: Vec::new(),
173        fresh_until: 0,
174    }
175}
176
177/// Go `callV2JournalSafely`: a panicking store is a failure, not a crash.
178fn call_journal_safely<T>(
179    f: impl FnOnce() -> Result<T, SecurityJournalStoreErrorV2>,
180) -> Result<T, SecurityJournalStoreErrorV2> {
181    match catch_unwind(AssertUnwindSafe(f)) {
182        Ok(r) => r,
183        Err(_) => Err(SecurityJournalStoreErrorV2::Failed(V2Error::plain(
184            "v2 status journal panicked",
185        ))),
186    }
187}
188
189/// Go `runV2StatusStage`: the status stage for every CertificateRef check.
190pub(crate) fn run_v2_status_stage(
191    ctx: &V2Context,
192    bundle: &ProofBundleV2,
193    checks: &[V2CertificateStatusCheck],
194    inputs: &V2StatusStageInputs<'_>,
195    now: i64,
196) -> V2StatusStageResult {
197    let mut issuer_ids: Vec<String> = Vec::new();
198    let mut refs_by_issuer: BTreeMap<String, Vec<CertificateRefV2>> = BTreeMap::new();
199    for check in checks {
200        if !refs_by_issuer.contains_key(&check.issuer_id) {
201            issuer_ids.push(check.issuer_id.clone());
202        }
203        refs_by_issuer
204            .entry(check.issuer_id.clone())
205            .or_default()
206            .push(CertificateRefV2 {
207                issuer_id: check.issuer_id.clone(),
208                cert_id: check.cert_id.clone(),
209            });
210    }
211    issuer_ids.sort();
212    let mut results: Vec<RevocationStatusResultV2> = checks
213        .iter()
214        .map(|_| RevocationStatusResultV2::unavailable())
215        .collect();
216    let mut roles = V2StatusRoleBindings::default();
217    let mut queries = 0usize;
218    let cancelled = |queries: usize| V2StatusStageResult {
219        assessment: unavailable_assessment(),
220        cancelled: true,
221        queries,
222    };
223    for issuer_id in &issuer_ids {
224        if ctx.is_done() {
225            return cancelled(queries);
226        }
227        let (Some(config), Some(journal_store), Some(provider)) = (
228            inputs.status_keys.get(issuer_id),
229            inputs.status_journal,
230            inputs.status_evidence,
231        ) else {
232            continue;
233        };
234        // 1. Anchored journal and current epoch binding.
235        let loaded =
236            call_journal_safely(|| Ok(load_anchored_security_journal_v2(ctx, journal_store)?));
237        let mut current = match loaded {
238            Ok(j) => j,
239            Err(_) => {
240                if ctx.is_done() {
241                    return cancelled(queries);
242                }
243                continue;
244            }
245        };
246        // 2. Role separation.
247        if check_v2_status_role_separation(&current, issuer_id, config, bundle).is_err() {
248            continue;
249        }
250        let status_key_id = key_id_plain(&config.key).unwrap_or_default();
251        // 3. Provider.
252        queries += 1;
253        let request = V2StatusEvidenceRequest {
254            issuer_id: issuer_id.clone(),
255            status_key_epoch: config.epoch,
256            status_key_id: status_key_id.clone(),
257            refs: refs_by_issuer.get(issuer_id).cloned().unwrap_or_default(),
258        };
259        let batch = match call_v2_status_provider(ctx, provider, &request) {
260            Ok(b) => b,
261            Err(_) => {
262                if ctx.is_done() {
263                    return cancelled(queries);
264                }
265                continue;
266            }
267        };
268        // 4. Authenticate.
269        let Ok(objects) = verify_v2_status_evidence_batch(&batch, issuer_id, &config.key) else {
270            continue;
271        };
272        // 5. Apply as one transition against the loaded head. On a
273        // compare-and-swap conflict, reload the anchored journal, repeat the
274        // binding and role-separation checks, and reapply the same batch
275        // exactly once more (no second provider call); a second conflict or
276        // any other failure makes the issuer unavailable.
277        let mut committed: Option<SecurityJournalV2> = None;
278        for attempt in 0..2 {
279            if attempt > 0 {
280                match call_journal_safely(|| {
281                    Ok(load_anchored_security_journal_v2(ctx, journal_store)?)
282                }) {
283                    Ok(j) => current = j,
284                    Err(_) => break,
285                }
286                if check_v2_status_role_separation(&current, issuer_id, config, bundle).is_err() {
287                    break;
288                }
289            }
290            match call_journal_safely(|| {
291                apply_v2_status_batch_to_journal(
292                    ctx,
293                    journal_store,
294                    &current,
295                    issuer_id,
296                    config,
297                    &objects,
298                    inputs.status_policy,
299                    now,
300                )
301            }) {
302                Ok(j) => {
303                    committed = Some(j);
304                    break;
305                }
306                Err(SecurityJournalStoreErrorV2::Conflict) => {}
307                Err(SecurityJournalStoreErrorV2::Failed(_)) => break,
308            }
309        }
310        if ctx.is_done() {
311            return cancelled(queries);
312        }
313        let Some(committed) = committed else {
314            continue;
315        };
316        // 6. Derive from committed state.
317        for binding in &committed.status_key_history {
318            if binding.issuer_id == *issuer_id {
319                roles
320                    .status_key_issuers
321                    .insert(binding.status_key_id.clone(), issuer_id.clone());
322            }
323        }
324        roles
325            .current_status_key_ids
326            .insert(issuer_id.clone(), status_key_id.clone());
327        let state = committed
328            .status_by_issuer
329            .get(issuer_id)
330            .cloned()
331            .unwrap_or_default();
332        for (i, check) in checks.iter().enumerate() {
333            if check.issuer_id != *issuer_id {
334                continue;
335            }
336            let result = revocation_status_for_cert_inner(
337                &state,
338                issuer_id,
339                &check.cert_id,
340                config.epoch,
341                &config.key,
342                inputs.status_policy,
343                now,
344            )
345            .unwrap_or_else(|_| RevocationStatusResultV2::unavailable());
346            if let Some(slot) = results.get_mut(i) {
347                *slot = result;
348            }
349        }
350    }
351    let assessment = aggregate_certificate_status_v2(checks, &results, &roles, true)
352        .unwrap_or_else(|_| unavailable_assessment());
353    V2StatusStageResult {
354        assessment,
355        cancelled: false,
356        queries,
357    }
358}
359
360/// Go `callV2StatusProvider`: a provider panic is contained and reported as
361/// a provider error.
362pub(crate) fn call_v2_status_provider(
363    ctx: &V2Context,
364    provider: &V2StatusEvidenceProvider,
365    request: &V2StatusEvidenceRequest,
366) -> Result<V2StatusEvidenceBatch, V2StatusProviderError> {
367    match catch_unwind(AssertUnwindSafe(|| provider(ctx, request))) {
368        Ok(r) => r,
369        Err(_) => Err(V2StatusProviderError::new("v2 status provider panicked")),
370    }
371}
372
373/// Go `verifyV2StatusEvidenceBatch`: decodes and authenticates every object
374/// before any is applied, and returns them in the deterministic application
375/// order: ascending sequence, then object type code (list before push), then
376/// evidence digest bytes. Errors keep the decoder's or verifier's class.
377pub(crate) fn verify_v2_status_evidence_batch(
378    batch: &V2StatusEvidenceBatch,
379    issuer_id: &str,
380    key: &HybridPublicKey,
381) -> V2Result<Vec<V2VerifiedStatusObject>> {
382    if batch.objects.len() > MAX_STATUS_EVIDENCE_BATCH_OBJECTS_V2 {
383        return plain(format!(
384            "v2 status batch exceeds {MAX_STATUS_EVIDENCE_BATCH_OBJECTS_V2} objects"
385        ));
386    }
387    if v2_status_evidence_batch_encoded_length(batch) > MAX_STATUS_EVIDENCE_BATCH_BYTES_V2 {
388        return plain(format!(
389            "v2 status batch exceeds {MAX_STATUS_EVIDENCE_BATCH_BYTES_V2} bytes"
390        ));
391    }
392    let mut out = Vec::with_capacity(batch.objects.len());
393    for object in &batch.objects {
394        match object.object_type {
395            LIST => {
396                let list = decode_revocation_list_v2(&object.wire)?;
397                verify_revocation_list_v2_signature(&list, issuer_id, key)?;
398                let digest = status_evidence_digest_list_v2(&list)?;
399                out.push(V2VerifiedStatusObject {
400                    code: LIST,
401                    sequence: list.sequence,
402                    digest,
403                    payload: V2VerifiedStatusPayload::List(list),
404                });
405            }
406            PUSH => {
407                let push = decode_revocation_push_v2(&object.wire)?;
408                verify_revocation_push_v2_signature(&push, issuer_id, key)?;
409                let digest = status_evidence_digest_push_v2(&push)?;
410                out.push(V2VerifiedStatusObject {
411                    code: PUSH,
412                    sequence: push.sequence,
413                    digest,
414                    payload: V2VerifiedStatusPayload::Push(push),
415                });
416            }
417            other => {
418                return plain(format!(
419                    "v2 status batch contains unsupported object type 0x{other:04x}"
420                ))
421            }
422        }
423    }
424    out.sort_by(|a, b| (a.sequence, a.code, &a.digest).cmp(&(b.sequence, b.code, &b.digest)));
425    Ok(out)
426}
427
428/// Go `applyV2StatusBatchToJournal`: applies one issuer's authenticated batch
429/// to the loaded journal and commits it by compare-and-swap against the
430/// loaded head. A no-op batch returns the loaded journal unchanged.
431#[allow(clippy::too_many_arguments)]
432pub(crate) fn apply_v2_status_batch_to_journal(
433    ctx: &V2Context,
434    store: &dyn SecurityJournalStoreV2,
435    current: &SecurityJournalV2,
436    issuer_id: &str,
437    config: &V2StatusKeyConfig,
438    objects: &[V2VerifiedStatusObject],
439    policy: &RevocationStatusPolicyV2,
440    now: i64,
441) -> Result<SecurityJournalV2, SecurityJournalStoreErrorV2> {
442    let mut next = current.clone();
443    let mut state = next
444        .status_by_issuer
445        .get(issuer_id)
446        .cloned()
447        .unwrap_or_default();
448    for object in objects {
449        state = match &object.payload {
450            V2VerifiedStatusPayload::List(list) => apply_revocation_list_v2(
451                &state,
452                list,
453                issuer_id,
454                config.epoch,
455                &config.key,
456                policy,
457                now,
458            )?,
459            V2VerifiedStatusPayload::Push(push) => apply_revocation_push_v2(
460                &state,
461                push,
462                issuer_id,
463                config.epoch,
464                &config.key,
465                policy,
466                now,
467            )?,
468        };
469    }
470    next.status_by_issuer.insert(issuer_id.to_string(), state);
471    commit_security_journal_transition_v2(ctx, store, current, next)
472}
473
474/// Go `checkV2StatusRoleSeparation` (SPEC-v2 §5.4, §6.5): the configured
475/// status key must be the issuer's current journal epoch binding; its global
476/// role history entry must be exactly the status role; and neither its
477/// complete key ID nor either component may equal the key ID or either
478/// component of any other journal role or of any key in the proof (issuers,
479/// subjects, agent), or the proof's verifier ID.
480pub(crate) fn check_v2_status_role_separation(
481    journal: &SecurityJournalV2,
482    issuer_id: &str,
483    config: &V2StatusKeyConfig,
484    bundle: &ProofBundleV2,
485) -> V2Result<()> {
486    require_journal_status_key_v2(journal, issuer_id, config.epoch, &config.key)?;
487    let status = key_role_binding_v2("status", &config.key)?;
488    let overlaps = |other: &KeyRoleBindingV2| {
489        let components = [&status.ed25519_digest, &status.ml_dsa_65_digest];
490        other.key_id == status.key_id
491            || components.contains(&&other.ed25519_digest)
492            || components.contains(&&other.ml_dsa_65_digest)
493    };
494    let mut recorded = false;
495    for binding in &journal.key_role_history {
496        if *binding == status {
497            recorded = true;
498            continue;
499        }
500        if overlaps(binding) {
501            return plain(format!(
502                "status key shares a key ID or component with journal role {:?}",
503                binding.role
504            ));
505        }
506    }
507    if !recorded {
508        return plain("status key lacks its permanent status role in the journal");
509    }
510    let mut keys = vec![&bundle.agent_pub_key];
511    for cert in &bundle.delegations {
512        keys.push(&cert.issuer_pub_key);
513        keys.push(&cert.subject_pub_key);
514    }
515    for key in keys {
516        let chain_key = key_role_binding_v2("other", key)?;
517        // No chain key may share an ID or component with any current or
518        // retired status binding of any issuer (§6.5 step 2).
519        for binding in journal
520            .key_role_history
521            .iter()
522            .filter(|b| b.role == "status")
523        {
524            let components = [&binding.ed25519_digest, &binding.ml_dsa_65_digest];
525            if chain_key.key_id == binding.key_id
526                || components.contains(&&chain_key.ed25519_digest)
527                || components.contains(&&chain_key.ml_dsa_65_digest)
528            {
529                return plain("a proof key shares a key ID or component with a status key");
530            }
531        }
532    }
533    if status.key_id == bundle.verifier_id {
534        return plain("status key equals the verifier identity");
535    }
536    Ok(())
537}
538
539#[cfg(test)]
540mod tests {
541    use std::sync::atomic::{AtomicUsize, Ordering};
542
543    use super::*;
544    use crate::crypto::hybrid_keypair_from_seeds;
545    use crate::types::{HybridPrivateKey, HybridSignature};
546    use crate::v2::crypto::key_id_v2;
547    use crate::v2::journal::{configure_status_key_epoch_v2, SecurityJournalHeadV2};
548    use crate::v2::reference::JournalStore;
549    use crate::v2::wire::{encode_revocation_list_v2, sign_revocation_list_v2, RevokedCertV2};
550
551    const NOW: i64 = 1_800_000_000;
552
553    /// Wraps the reference store: counts loads and compare-and-swaps and
554    /// reports `conflicts` conflicts before delegating.
555    struct ConflictingStore {
556        inner: JournalStore,
557        conflicts: AtomicUsize,
558        loads: AtomicUsize,
559        swaps: AtomicUsize,
560    }
561
562    impl SecurityJournalStoreV2 for ConflictingStore {
563        fn load(
564            &self,
565            ctx: &V2Context,
566        ) -> V2Result<(SecurityJournalV2, crate::v2::journal::SecurityJournalHeadV2)> {
567            self.loads.fetch_add(1, Ordering::SeqCst);
568            self.inner.load(ctx)
569        }
570        // fetch_update is deprecated as try_update from Rust 1.99, which older
571        // supported toolchains do not have.
572        #[allow(deprecated)]
573        fn compare_and_swap(
574            &self,
575            ctx: &V2Context,
576            expected: &SecurityJournalHeadV2,
577            next: &SecurityJournalV2,
578        ) -> Result<(), SecurityJournalStoreErrorV2> {
579            self.swaps.fetch_add(1, Ordering::SeqCst);
580            if self
581                .conflicts
582                .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |c| c.checked_sub(1))
583                .is_ok()
584            {
585                return Err(SecurityJournalStoreErrorV2::Conflict);
586            }
587            self.inner.compare_and_swap(ctx, expected, next)
588        }
589    }
590
591    struct Setup {
592        store: ConflictingStore,
593        issuer_id: String,
594        status_public: HybridPublicKey,
595        status_private: HybridPrivateKey,
596        bundle: ProofBundleV2,
597        checks: Vec<V2CertificateStatusCheck>,
598    }
599
600    fn setup(conflicts: usize) -> Setup {
601        let (issuer_public, _) = hybrid_keypair_from_seeds(&[11; 32], &[12; 32]);
602        let (status_public, status_private) = hybrid_keypair_from_seeds(&[13; 32], &[14; 32]);
603        let (agent_public, _) = hybrid_keypair_from_seeds(&[15; 32], &[16; 32]);
604        let issuer_id = key_id_v2(&issuer_public).expect("issuer id");
605        let inner = JournalStore::new().expect("store");
606        configure_status_key_epoch_v2(
607            &V2Context::background(),
608            &inner,
609            &issuer_id,
610            1,
611            &status_public,
612        )
613        .expect("configure status key");
614        let bundle = ProofBundleV2 {
615            version: 2,
616            verifier_id: "a".repeat(64),
617            agent_id: key_id_v2(&agent_public).expect("agent id"),
618            agent_pub_key: agent_public.clone(),
619            delegations: Vec::new(),
620            delegation_digest: Vec::new(),
621            challenge: Vec::new(),
622            challenge_at: NOW,
623            challenge_sig: HybridSignature {
624                ed25519: vec![],
625                ml_dsa_65: vec![],
626            },
627            session_context: None,
628            stream_id: None,
629            stream_seq: None,
630        };
631        let checks = vec![V2CertificateStatusCheck {
632            delegation_index: 0,
633            issuer_id: issuer_id.clone(),
634            subject_id: key_id_v2(&agent_public).expect("subject id"),
635            cert_id: "c1".into(),
636        }];
637        Setup {
638            store: ConflictingStore {
639                inner,
640                conflicts: AtomicUsize::new(conflicts),
641                loads: AtomicUsize::new(0),
642                swaps: AtomicUsize::new(0),
643            },
644            issuer_id,
645            status_public,
646            status_private,
647            bundle,
648            checks,
649        }
650    }
651
652    fn signed_list(s: &Setup, revoked: &[&str]) -> Vec<u8> {
653        let list = RevocationListV2 {
654            version: 2,
655            issuer_id: s.issuer_id.clone(),
656            updated_at: NOW - 10,
657            next_update: NOW + 600,
658            sequence: 1,
659            revoked: revoked
660                .iter()
661                .map(|c| RevokedCertV2 {
662                    cert_id: c.to_string(),
663                })
664                .collect(),
665            signature: HybridSignature {
666                ed25519: vec![],
667                ml_dsa_65: vec![],
668            },
669        };
670        let signed =
671            sign_revocation_list_v2(&list, &s.issuer_id, &s.status_public, &s.status_private)
672                .expect("sign");
673        encode_revocation_list_v2(&signed).expect("encode")
674    }
675
676    fn run(s: &Setup, provider: V2StatusEvidenceProvider) -> V2StatusStageResult {
677        let keys: BTreeMap<String, V2StatusKeyConfig> = [(
678            s.issuer_id.clone(),
679            V2StatusKeyConfig {
680                epoch: 1,
681                key: s.status_public.clone(),
682            },
683        )]
684        .into_iter()
685        .collect();
686        let policy = RevocationStatusPolicyV2 {
687            max_list_lifetime_seconds: 3600,
688            max_status_age_seconds: 600,
689            clock_skew_seconds: 5,
690        };
691        let inputs = V2StatusStageInputs {
692            status_evidence: Some(&provider),
693            status_journal: Some(&s.store),
694            status_keys: &keys,
695            status_policy: &policy,
696        };
697        run_v2_status_stage(&V2Context::background(), &s.bundle, &s.checks, &inputs, NOW)
698    }
699
700    fn list_provider(wire: Vec<u8>, calls: Arc<AtomicUsize>) -> V2StatusEvidenceProvider {
701        Arc::new(move |_: &V2Context, _: &V2StatusEvidenceRequest| {
702            calls.fetch_add(1, Ordering::SeqCst);
703            Ok(V2StatusEvidenceBatch {
704                objects: vec![V2StatusEvidenceObject {
705                    object_type: LIST,
706                    wire: wire.clone(),
707                }],
708            })
709        })
710    }
711
712    #[test]
713    fn a_conflict_is_retried_exactly_once_without_a_second_provider_call() {
714        let s = setup(1);
715        let calls = Arc::new(AtomicUsize::new(0));
716        let before = s.store.inner.head();
717        let out = run(&s, list_provider(signed_list(&s, &[]), calls.clone()));
718        assert!(!out.cancelled);
719        assert_eq!(out.assessment.assessment, "current", "{:?}", out.assessment);
720        assert_eq!(out.queries, 1);
721        assert_eq!(
722            calls.load(Ordering::SeqCst),
723            1,
724            "the provider is never called again"
725        );
726        assert_eq!(
727            s.store.swaps.load(Ordering::SeqCst),
728            2,
729            "one conflicted swap, one committed retry"
730        );
731        assert_eq!(
732            s.store.loads.load(Ordering::SeqCst),
733            2,
734            "the retry reloads the anchored journal"
735        );
736        assert_eq!(s.store.inner.head().generation, before.generation + 1);
737    }
738
739    #[test]
740    fn a_second_conflict_makes_the_issuer_unavailable() {
741        let s = setup(usize::MAX);
742        let calls = Arc::new(AtomicUsize::new(0));
743        let before = s.store.inner.head();
744        let out = run(&s, list_provider(signed_list(&s, &[]), calls.clone()));
745        assert!(!out.cancelled);
746        assert_eq!(
747            (
748                out.assessment.assessment.as_str(),
749                out.assessment.reason.as_str()
750            ),
751            ("unavailable", "status_unavailable")
752        );
753        assert!(out.assessment.evidence.is_empty());
754        assert_eq!(calls.load(Ordering::SeqCst), 1);
755        assert_eq!(
756            s.store.swaps.load(Ordering::SeqCst),
757            2,
758            "exactly one bounded retry"
759        );
760        assert_eq!(s.store.loads.load(Ordering::SeqCst), 2);
761        assert_eq!(s.store.inner.head(), before, "nothing was committed");
762    }
763
764    #[test]
765    fn without_conflict_one_swap_commits_and_revocation_wins() {
766        let s = setup(0);
767        let calls = Arc::new(AtomicUsize::new(0));
768        let out = run(&s, list_provider(signed_list(&s, &["c1"]), calls.clone()));
769        assert_eq!(out.assessment.assessment, "revoked");
770        assert_eq!(s.store.swaps.load(Ordering::SeqCst), 1);
771        assert_eq!(s.store.loads.load(Ordering::SeqCst), 1);
772    }
773
774    #[test]
775    fn provider_panics_and_errors_are_contained() {
776        let s = setup(0);
777        let before = s.store.inner.head();
778        let panicking: V2StatusEvidenceProvider =
779            Arc::new(|_: &V2Context, _: &V2StatusEvidenceRequest| {
780                panic!("provider exploded");
781            });
782        let out = run(&s, panicking);
783        assert_eq!(out.assessment.assessment, "unavailable");
784        assert_eq!(out.queries, 1);
785        let failing: V2StatusEvidenceProvider =
786            Arc::new(|_: &V2Context, _: &V2StatusEvidenceRequest| {
787                Err(V2StatusProviderError::new("offline"))
788            });
789        assert_eq!(run(&s, failing).assessment.assessment, "unavailable");
790        assert_eq!(s.store.swaps.load(Ordering::SeqCst), 0);
791        assert_eq!(s.store.inner.head(), before);
792    }
793
794    #[test]
795    fn a_tampered_object_rejects_the_whole_batch() {
796        let s = setup(0);
797        let mut wire = signed_list(&s, &[]);
798        let text = String::from_utf8(wire.clone())
799            .expect("utf8")
800            .replace("\"sequence\":1", "\"sequence\":2");
801        wire = text.into_bytes();
802        let calls = Arc::new(AtomicUsize::new(0));
803        let out = run(&s, list_provider(wire, calls));
804        assert_eq!(out.assessment.assessment, "unavailable");
805        assert_eq!(s.store.swaps.load(Ordering::SeqCst), 0);
806    }
807}