Skip to main content

ratify_protocol/v2/
status.rs

1//! Issuer status reducer (rollback-protected state), status queries, and
2//! CertificateRef status aggregation. Mirrors Go `status_state_v2.go`,
3//! `status_evaluation_v2.go`, and the observation compaction and accepted-state
4//! validation from `security_journal_v2.go`.
5
6use std::collections::{BTreeMap, BTreeSet};
7
8use super::crypto::{key_id_v2, sha384, valid_prefixed_digest, valid_v2_id};
9use super::errors::{plain, Classify, V2Error, V2ErrorClass, V2Result};
10use super::json::{canonical, CJ};
11use super::limits::{
12    valid_v2_timestamp, V2_MAX_FUTURE_SKEW_SECONDS, V2_MAX_STATUS_LIFETIME_SECONDS,
13};
14use super::receipt::{
15    compare_evidence, has_accepted_status_history_per_issuer, StatusEvidenceEntryV2,
16};
17use super::wire::{
18    decode_revocation_list_v2, encode_revocation_list_v2, revocation_list_v2_signable_bytes,
19    revocation_push_v2_signable_bytes, status_evidence_digest_list_v2,
20    status_evidence_digest_push_v2, verify_revocation_list_v2_signature,
21    verify_revocation_push_v2_signature, RevocationListV2, RevocationPushV2, RevokedCertV2,
22    MAX_SAFE,
23};
24use crate::types::HybridPublicKey;
25
26pub(crate) const LIST: u16 = 0x0003;
27pub(crate) const PUSH: u16 = 0x0005;
28
29/// Go `keyIDV2`, whose length errors are unclassified (the caller's
30/// `v2Classify` fixes their class). The public `key_id_v2` reports
31/// `malformed` explicitly, so internal ports that mirror Go use this.
32pub(crate) fn key_id_plain(key: &HybridPublicKey) -> V2Result<String> {
33    key_id_v2(key).map_err(|e| V2Error::plain(e.message))
34}
35
36/// Finite freshness bounds. A zero maximum means "not configured": status
37/// can then never be current.
38#[derive(Debug, Clone, Copy, Default)]
39pub struct RevocationStatusPolicyV2 {
40    pub max_list_lifetime_seconds: i64,
41    pub max_status_age_seconds: i64,
42    pub clock_skew_seconds: i64,
43}
44
45/// Authenticated status evidence observation.
46#[derive(Debug, Clone, PartialEq, Eq, Default)]
47pub struct RevocationObservationV2 {
48    pub object_type: u16,
49    pub status_key_epoch: u64,
50    pub status_key_id: String,
51    pub sequence: i64,
52    pub evidence_digest: Vec<u8>,
53    pub body_digest: Vec<u8>,
54    pub revoked_set_digest: Vec<u8>,
55    pub revoked_cert_ids: Vec<String>,
56    pub future_dated: bool,
57    pub fork: bool,
58    pub gap: bool,
59    pub accepted: bool,
60}
61
62/// A fail-closed answer for one CertificateRef with its evidence.
63#[derive(Debug, Clone, PartialEq, Eq, Default)]
64pub struct RevocationStatusResultV2 {
65    /// "not_revoked", "revoked", or "indeterminate".
66    pub status: String,
67    /// "" or, for indeterminate, "unavailable" / "stale".
68    pub reason: String,
69    pub evidence: Vec<StatusEvidenceEntryV2>,
70    pub fresh_until: i64,
71}
72
73impl RevocationStatusResultV2 {
74    pub fn unavailable() -> Self {
75        RevocationStatusResultV2 {
76            status: "indeterminate".into(),
77            reason: "unavailable".into(),
78            evidence: Vec::new(),
79            fresh_until: 0,
80        }
81    }
82}
83
84/// One issuer's rollback-protected reducer state. Callers serialize applies
85/// and persist the returned value atomically.
86#[derive(Debug, Clone, Default)]
87pub struct RevocationStatusStateV2 {
88    pub issuer_id: String,
89    pub status_key_epoch: u64,
90    pub status_key_id: String,
91    pub retired_status_key_ids: Vec<String>,
92    pub has_floor: bool,
93    pub floor: i64,
94    pub accepted_snapshot: Option<RevocationListV2>,
95    pub accepted_cert_ids: Vec<String>,
96    pub has_preceding_checkpoint: bool,
97    pub preceding_floor: i64,
98    pub preceding_accepted_cert_ids: Vec<String>,
99    pub deny_union_cert_ids: Vec<String>,
100    pub observations: Vec<RevocationObservationV2>,
101    pub max_observed_sequence: i64,
102    pub fork_sequence: i64,
103    pub reconciliation_required: bool,
104    pub future_dated_object_observed: bool,
105}
106
107pub(crate) fn sorted_unique(values: &[String]) -> Vec<String> {
108    values
109        .iter()
110        .cloned()
111        .collect::<BTreeSet<_>>()
112        .into_iter()
113        .collect()
114}
115
116pub(crate) fn contains_all(have: &[String], want: &[String]) -> bool {
117    want.iter().all(|w| have.contains(w))
118}
119
120pub(crate) fn equal_sets(a: &[String], b: &[String]) -> bool {
121    sorted_unique(a).len() == sorted_unique(b).len() && contains_all(a, b)
122}
123
124fn concat(a: &[String], b: &[String]) -> Vec<String> {
125    a.iter().chain(b.iter()).cloned().collect()
126}
127
128pub(crate) fn revoked_ids(refs: &[RevokedCertV2]) -> Vec<String> {
129    refs.iter().map(|r| r.cert_id.clone()).collect()
130}
131
132/// RevokedSetDigest (SPEC-v2 §4): SHA-384("ratify-protocol-revoked-set-v2" ||
133/// 0x00 || RatifyCanonicalJSON(sorted, deduplicated cert_ids)).
134fn revoked_set_digest(refs: &[RevokedCertV2]) -> V2Result<Vec<u8>> {
135    let encoded = canonical(&CJ::strs(&sorted_unique(&revoked_ids(refs))))
136        .map_err(|e| e.context("encode revoked certificate set"))?;
137    Ok(sha384(&[b"ratify-protocol-revoked-set-v2", &[0], &encoded]))
138}
139
140fn beyond_skew(timestamp: i64, now: i64, skew: i64) -> bool {
141    timestamp > now && timestamp - now > skew
142}
143
144fn list_fresh(l: &RevocationListV2, p: &RevocationStatusPolicyV2, now: i64) -> bool {
145    if p.max_list_lifetime_seconds == 0
146        || p.max_status_age_seconds == 0
147        || l.next_update - l.updated_at > p.max_list_lifetime_seconds
148        || beyond_skew(l.updated_at, now, p.clock_skew_seconds)
149        || now >= l.next_update
150    {
151        // Exclusive deadline: a list is fresh only while now < next_update.
152        return false;
153    }
154    // Exclusive age deadline: fresh only while now < updated_at + max_status_age.
155    now < l.updated_at || now - l.updated_at < p.max_status_age_seconds
156}
157
158fn validate_policy(p: &RevocationStatusPolicyV2) -> V2Result<()> {
159    // Zero lifetime or age means "not configured" (status is then never
160    // current); configured values are bounded by SPEC-v2 §2.5.
161    if p.max_list_lifetime_seconds < 0
162        || p.max_status_age_seconds < 0
163        || p.clock_skew_seconds < 0
164        || p.max_list_lifetime_seconds > V2_MAX_STATUS_LIFETIME_SECONDS
165        || p.max_status_age_seconds > V2_MAX_STATUS_LIFETIME_SECONDS
166        || p.clock_skew_seconds > V2_MAX_FUTURE_SKEW_SECONDS
167    {
168        return plain("revocation status policy contains invalid time bounds");
169    }
170    Ok(())
171}
172
173pub(crate) fn validate_binding(
174    s: &RevocationStatusStateV2,
175    issuer_id: &str,
176    epoch: u64,
177) -> V2Result<()> {
178    if !s.issuer_id.is_empty() && s.issuer_id != issuer_id {
179        return plain("revocation status state belongs to a different issuer");
180    }
181    if !s.issuer_id.is_empty() && s.status_key_epoch != epoch {
182        return plain("revocation status state belongs to a different status-key epoch");
183    }
184    if s.floor < 0 || s.max_observed_sequence < 0 || s.fork_sequence < 0 {
185        return plain("revocation status state has negative sequence state");
186    }
187    if s.preceding_floor < 0
188        || s.preceding_floor > MAX_SAFE
189        || (s.preceding_floor == 0 && !s.preceding_accepted_cert_ids.is_empty())
190        || sorted_unique(&s.preceding_accepted_cert_ids).len()
191            != s.preceding_accepted_cert_ids.len()
192    {
193        return plain("revocation status state has invalid preceding checkpoint");
194    }
195    if s.has_floor
196        && (s.floor == 0
197            || s.floor > MAX_SAFE
198            || s.accepted_snapshot
199                .as_ref()
200                .is_none_or(|l| l.sequence <= 0 || l.sequence > s.floor))
201    {
202        return plain("revocation status state has inconsistent accepted floor");
203    }
204    if !s.has_floor
205        && (s.floor != 0 || s.accepted_snapshot.is_some() || !s.accepted_cert_ids.is_empty())
206    {
207        return plain("revocation status state has accepted data without a floor");
208    }
209    if s.max_observed_sequence > MAX_SAFE
210        || s.fork_sequence > MAX_SAFE
211        || epoch == 0
212        || epoch > MAX_SAFE as u64
213    {
214        return plain("revocation status state has invalid sequence or epoch");
215    }
216    if !s.issuer_id.is_empty() && !valid_v2_id(&s.status_key_id) {
217        return plain("revocation status state has an invalid status-key ID");
218    }
219    if sorted_unique(&s.retired_status_key_ids).len() != s.retired_status_key_ids.len()
220        || s.retired_status_key_ids.contains(&s.status_key_id)
221    {
222        return plain("revocation status state has invalid retired status-key history");
223    }
224    if s.retired_status_key_ids.iter().any(|k| !valid_v2_id(k)) {
225        return plain("revocation status state has an invalid retired status-key ID");
226    }
227    Ok(())
228}
229
230pub(crate) fn has_accepted_observation(
231    obs: &[RevocationObservationV2],
232    epoch: u64,
233    ty: u16,
234    seq: i64,
235    digest: &[u8],
236) -> bool {
237    obs.iter().any(|o| {
238        o.status_key_epoch == epoch
239            && o.object_type == ty
240            && o.sequence == seq
241            && o.evidence_digest == digest
242            && o.accepted
243            && !o.fork
244            && !o.future_dated
245    })
246}
247
248pub(crate) fn validate_accepted_state(s: &RevocationStatusStateV2) -> V2Result<()> {
249    if sorted_unique(&s.deny_union_cert_ids).len() != s.deny_union_cert_ids.len()
250        || sorted_unique(&s.accepted_cert_ids).len() != s.accepted_cert_ids.len()
251    {
252        return plain("revocation status sets are not canonical");
253    }
254    let mut observed = Vec::new();
255    let mut fork_recorded = false;
256    for o in &s.observations {
257        if o.sequence <= 0
258            || o.sequence > MAX_SAFE
259            || !valid_v2_id(&o.status_key_id)
260            || (o.object_type != LIST && o.object_type != PUSH)
261            || o.evidence_digest.len() != 48
262            || o.body_digest.len() != 48
263            || o.revoked_set_digest.len() != 48
264            || sorted_unique(&o.revoked_cert_ids).len() != o.revoked_cert_ids.len()
265        {
266            return plain("security journal contains a malformed status observation");
267        }
268        if o.revoked_cert_ids.iter().any(String::is_empty) {
269            return plain("status observation contains an invalid certificate ID");
270        }
271        fork_recorded = fork_recorded || (o.status_key_epoch == s.status_key_epoch && o.fork);
272        observed.extend(o.revoked_cert_ids.iter().cloned());
273        if o.status_key_epoch == s.status_key_epoch && o.sequence > s.max_observed_sequence {
274            return plain("observed sequence exceeds its high-water mark");
275        }
276        if !contains_all(&s.deny_union_cert_ids, &o.revoked_cert_ids) {
277            return plain("deny union omits a revocation from authenticated evidence");
278        }
279    }
280    if !contains_all(&observed, &s.deny_union_cert_ids) {
281        return plain("deny union contains a revocation without a retained authenticated witness");
282    }
283    if s.fork_sequence > 0 && (!s.reconciliation_required || !fork_recorded) {
284        return plain("unresolved fork state lacks its retained fork marker");
285    }
286    if s.has_floor && s.floor > s.max_observed_sequence {
287        return plain("accepted floor exceeds the observed sequence high-water mark");
288    }
289    if !s.has_floor {
290        return Ok(());
291    }
292    let Some(snap) = s.accepted_snapshot.as_ref() else {
293        // Go dereferences the snapshot here; every caller validates the
294        // binding (has_floor implies a snapshot) first.
295        return plain("accepted snapshot does not match issuer or floor");
296    };
297    if snap.issuer_id != s.issuer_id || snap.sequence > s.floor {
298        return plain("accepted snapshot does not match issuer or floor");
299    }
300    let digest = status_evidence_digest_list_v2(snap)?;
301    if !has_accepted_observation(
302        &s.observations,
303        s.status_key_epoch,
304        LIST,
305        snap.sequence,
306        &digest,
307    ) {
308        return plain("accepted snapshot has no matching authenticated observation");
309    }
310    let mut accepted = revoked_ids(&snap.revoked);
311    let mut pushes: Vec<&RevocationObservationV2> = s
312        .observations
313        .iter()
314        .filter(|o| {
315            o.status_key_epoch == s.status_key_epoch
316                && o.object_type == PUSH
317                && o.accepted
318                && o.sequence > snap.sequence
319                && o.sequence <= s.floor
320        })
321        .collect();
322    for p in &pushes {
323        accepted.extend(p.revoked_cert_ids.iter().cloned());
324    }
325    pushes.sort_by_key(|p| p.sequence);
326    let mut expected = snap.sequence;
327    for p in pushes {
328        if expected >= MAX_SAFE || p.sequence != expected + 1 {
329            return plain(
330                "accepted push observations are not contiguous after the accepted snapshot",
331            );
332        }
333        expected = p.sequence;
334    }
335    if expected != s.floor {
336        return plain("accepted push history does not reach the recorded floor");
337    }
338    if !equal_sets(&accepted, &s.accepted_cert_ids) {
339        return plain("accepted certificate set does not follow the accepted snapshot and pushes");
340    }
341    Ok(())
342}
343
344pub(crate) fn semantic_key(o: &RevocationObservationV2) -> String {
345    let digest = if o.object_type == LIST {
346        &o.revoked_set_digest
347    } else {
348        &o.body_digest
349    };
350    format!(
351        "{}:{}:{}:{}:future={}:fork={}",
352        o.status_key_epoch,
353        o.object_type,
354        o.sequence,
355        hex::encode(digest),
356        o.future_dated,
357        o.fork
358    )
359}
360
361pub(crate) fn must_retain(s: &RevocationStatusStateV2, o: &RevocationObservationV2) -> bool {
362    if o.status_key_epoch != s.status_key_epoch {
363        return false;
364    }
365    if let Some(snap) = &s.accepted_snapshot {
366        if o.object_type == PUSH
367            && o.accepted
368            && o.sequence > snap.sequence
369            && o.sequence <= s.floor
370        {
371            return true;
372        }
373    }
374    s.reconciliation_required && (o.sequence > s.floor || o.fork || o.gap || o.future_dated)
375}
376
377/// Go `canonicalizeRevocationStatusStateV2`: every string set in snapshot
378/// order. Observation order (compaction order) is not changed.
379pub(crate) fn canonicalize_state(mut s: RevocationStatusStateV2) -> RevocationStatusStateV2 {
380    s.retired_status_key_ids = sorted_unique(&s.retired_status_key_ids);
381    s.accepted_cert_ids = sorted_unique(&s.accepted_cert_ids);
382    s.preceding_accepted_cert_ids = sorted_unique(&s.preceding_accepted_cert_ids);
383    s.deny_union_cert_ids = sorted_unique(&s.deny_union_cert_ids);
384    for o in &mut s.observations {
385        o.revoked_cert_ids = sorted_unique(&o.revoked_cert_ids);
386    }
387    s
388}
389
390/// Go `pruneSecurityJournalObservationsV2` for one issuer state (also Go
391/// `compactRevocationStatusObservationsV2`), followed by canonicalization.
392pub(crate) fn compact(mut s: RevocationStatusStateV2) -> RevocationStatusStateV2 {
393    let base_digest = s
394        .accepted_snapshot
395        .as_ref()
396        .and_then(|l| status_evidence_digest_list_v2(l).ok())
397        .unwrap_or_default();
398    let mut obs = s.observations.clone();
399    obs.sort_by(|a, b| {
400        (
401            a.status_key_epoch,
402            a.sequence,
403            a.object_type,
404            &a.revoked_set_digest,
405            &a.body_digest,
406        )
407            .cmp(&(
408                b.status_key_epoch,
409                b.sequence,
410                b.object_type,
411                &b.revoked_set_digest,
412                &b.body_digest,
413            ))
414    });
415    let mut retained: Vec<RevocationObservationV2> = Vec::new();
416    let mut witnessed = BTreeSet::new();
417    let mut semantic: BTreeMap<String, usize> = BTreeMap::new();
418    for mut o in obs {
419        let accepted_base = !base_digest.is_empty()
420            && o.status_key_epoch == s.status_key_epoch
421            && o.object_type == LIST
422            && Some(o.sequence) == s.accepted_snapshot.as_ref().map(|l| l.sequence)
423            && o.evidence_digest == base_digest;
424        let full = accepted_base || must_retain(&s, &o);
425        let mut new_witnesses = Vec::new();
426        for id in &o.revoked_cert_ids {
427            if witnessed.insert(id.clone()) {
428                new_witnesses.push(id.clone());
429            }
430        }
431        if !full {
432            o.revoked_cert_ids = new_witnesses;
433        }
434        let key = semantic_key(&o);
435        if let Some(&idx) = semantic.get(&key) {
436            let prior = &mut retained[idx];
437            prior.accepted = prior.accepted || o.accepted;
438            prior.fork = prior.fork || o.fork;
439            prior.gap = prior.gap || o.gap;
440            prior.future_dated = (prior.future_dated || o.future_dated) && !prior.accepted;
441            prior.revoked_cert_ids =
442                sorted_unique(&concat(&prior.revoked_cert_ids, &o.revoked_cert_ids));
443            if accepted_base {
444                prior.evidence_digest = o.evidence_digest.clone();
445                prior.accepted = true;
446                if !s.reconciliation_required {
447                    prior.gap = false;
448                }
449                prior.future_dated = false;
450            }
451            continue;
452        }
453        semantic.insert(key, retained.len());
454        retained.push(o);
455    }
456    if !s.reconciliation_required {
457        if let Some(snap) = &s.accepted_snapshot {
458            if let Some(o) = retained.iter_mut().find(|o| {
459                o.status_key_epoch == s.status_key_epoch
460                    && o.object_type == LIST
461                    && o.sequence == snap.sequence
462                    && o.accepted
463                    && !o.future_dated
464                    && o.evidence_digest == base_digest
465            }) {
466                o.gap = false;
467            }
468        }
469    }
470    s.observations = retained;
471    canonicalize_state(s)
472}
473
474fn initialize(s: &mut RevocationStatusStateV2, issuer_id: &str, epoch: u64) {
475    if s.issuer_id.is_empty() {
476        s.issuer_id = issuer_id.to_string();
477        s.status_key_epoch = epoch;
478    }
479    s.accepted_cert_ids = sorted_unique(&s.accepted_cert_ids);
480    s.deny_union_cert_ids = sorted_unique(&s.deny_union_cert_ids);
481}
482
483fn add_revocations(s: &mut RevocationStatusStateV2, values: &[String]) {
484    s.deny_union_cert_ids = sorted_unique(&concat(&s.deny_union_cert_ids, values));
485}
486
487fn mark_fork(s: &mut RevocationStatusStateV2, o: &mut RevocationObservationV2, sequence: i64) {
488    o.fork = true;
489    s.reconciliation_required = true;
490    s.fork_sequence = [s.fork_sequence, s.floor, sequence, 0]
491        .into_iter()
492        .max()
493        .unwrap_or(0);
494}
495
496fn find_observation(
497    obs: &[RevocationObservationV2],
498    epoch: u64,
499    ty: u16,
500    seq: i64,
501    digest: &[u8],
502) -> Option<usize> {
503    obs.iter().rposition(|o| {
504        o.status_key_epoch == epoch
505            && o.object_type == ty
506            && o.sequence == seq
507            && o.evidence_digest == digest
508    })
509}
510
511fn find_set_observation(
512    obs: &[RevocationObservationV2],
513    inc: &RevocationObservationV2,
514) -> Option<RevocationObservationV2> {
515    obs.iter()
516        .rev()
517        .find(|o| {
518            o.status_key_epoch == inc.status_key_epoch
519                && o.object_type == inc.object_type
520                && o.sequence == inc.sequence
521                && o.revoked_set_digest == inc.revoked_set_digest
522        })
523        .cloned()
524}
525
526fn has_forked_sequence(obs: &[RevocationObservationV2], epoch: u64, ty: u16, seq: i64) -> bool {
527    obs.iter().any(|o| {
528        o.status_key_epoch == epoch
529            && (ty == 0 || o.object_type == ty)
530            && o.sequence == seq
531            && o.fork
532    })
533}
534
535fn sequence_conflict(obs: &[RevocationObservationV2], inc: &RevocationObservationV2) -> bool {
536    obs.iter().any(|o| {
537        o.status_key_epoch == inc.status_key_epoch
538            && o.sequence == inc.sequence
539            && o.object_type == inc.object_type
540            && ((inc.object_type == LIST && o.revoked_set_digest != inc.revoked_set_digest)
541                || (inc.object_type == PUSH && o.body_digest != inc.body_digest))
542    })
543}
544
545fn required_for_snapshot(obs: &[RevocationObservationV2], epoch: u64, seq: i64) -> Vec<String> {
546    let mut v = Vec::new();
547    for o in obs
548        .iter()
549        .filter(|o| o.status_key_epoch == epoch && o.sequence <= seq)
550    {
551        v.extend(o.revoked_cert_ids.iter().cloned());
552    }
553    sorted_unique(&v)
554}
555
556fn snapshot_conflicts_with_push(
557    s: &RevocationStatusStateV2,
558    epoch: u64,
559    seq: i64,
560    ids: &[String],
561) -> bool {
562    s.observations
563        .iter()
564        .filter(|o| o.status_key_epoch == epoch && o.object_type == PUSH && o.sequence == seq)
565        .any(|o| {
566            if s.has_floor && s.floor == seq - 1 {
567                !equal_sets(ids, &concat(&s.accepted_cert_ids, &o.revoked_cert_ids))
568            } else {
569                !contains_all(ids, &o.revoked_cert_ids)
570            }
571        })
572}
573
574fn snapshot_omission_for_push(
575    s: &RevocationStatusStateV2,
576    epoch: u64,
577    push: &RevocationObservationV2,
578) -> Option<i64> {
579    let mut conflicting = 0i64;
580    let mut check = |seq: i64, revoked: &[String]| {
581        if seq >= push.sequence
582            && !contains_all(revoked, &push.revoked_cert_ids)
583            && seq > conflicting
584        {
585            conflicting = seq;
586        }
587    };
588    if let Some(snap) = &s.accepted_snapshot {
589        if s.status_key_epoch == epoch {
590            check(snap.sequence, &revoked_ids(&snap.revoked));
591        }
592    }
593    if s.reconciliation_required {
594        for o in &s.observations {
595            if o.status_key_epoch == epoch
596                && o.object_type == LIST
597                && o.sequence > s.floor
598                && o.sequence >= push.sequence
599                && (o.fork || o.gap || o.future_dated)
600            {
601                check(o.sequence, &o.revoked_cert_ids);
602            }
603        }
604    }
605    (conflicting != 0).then_some(conflicting)
606}
607
608fn heartbeat_preferred(
609    incoming: &RevocationListV2,
610    incoming_digest: &[u8],
611    accepted: &RevocationListV2,
612) -> bool {
613    if incoming.updated_at != accepted.updated_at {
614        return incoming.updated_at > accepted.updated_at;
615    }
616    status_evidence_digest_list_v2(accepted).is_ok_and(|d| incoming_digest < d.as_slice())
617}
618
619pub(crate) fn clone_list(l: &RevocationListV2) -> V2Result<RevocationListV2> {
620    decode_revocation_list_v2(&encode_revocation_list_v2(l)?)
621}
622
623/// Go `cloneRevocationStatusStateV2`: the accepted snapshot is copied through
624/// its wire form, so a snapshot that does not encode is an error.
625fn clone_state(s: &RevocationStatusStateV2) -> V2Result<RevocationStatusStateV2> {
626    let mut copy = s.clone();
627    if let Some(list) = &s.accepted_snapshot {
628        copy.accepted_snapshot = Some(clone_list(list)?);
629    }
630    Ok(copy)
631}
632
633/// Verify a list against the caller-authenticated status-key binding and
634/// apply it. Errors (class `status_object_rejected` unless already
635/// classified) leave the state untouched.
636pub fn apply_revocation_list_v2(
637    state: &RevocationStatusStateV2,
638    list: &RevocationListV2,
639    bound_issuer_id: &str,
640    status_key_epoch: u64,
641    status_key: &HybridPublicKey,
642    policy: &RevocationStatusPolicyV2,
643    now: i64,
644) -> V2Result<RevocationStatusStateV2> {
645    apply_list_inner(
646        state,
647        list,
648        bound_issuer_id,
649        status_key_epoch,
650        status_key,
651        policy,
652        now,
653    )
654    .map(|r| {
655        if r.issuer_id.is_empty() {
656            r
657        } else {
658            compact(r)
659        }
660    })
661    .classify(V2ErrorClass::StatusObjectRejected)
662}
663
664fn apply_list_inner(
665    state: &RevocationStatusStateV2,
666    list: &RevocationListV2,
667    bound_issuer_id: &str,
668    epoch: u64,
669    status_key: &HybridPublicKey,
670    policy: &RevocationStatusPolicyV2,
671    now: i64,
672) -> V2Result<RevocationStatusStateV2> {
673    validate_policy(policy)?;
674    if !valid_v2_timestamp(now) || epoch == 0 || epoch > MAX_SAFE as u64 {
675        return plain("revocation list application has invalid time or status-key epoch");
676    }
677    verify_revocation_list_v2_signature(list, bound_issuer_id, status_key)?;
678    validate_binding(state, bound_issuer_id, epoch)?;
679    let digest = status_evidence_digest_list_v2(list)?;
680    let body_digest = sha384(&[&revocation_list_v2_signable_bytes(list)?]);
681    let set_digest = revoked_set_digest(&list.revoked)?;
682    let mut next = clone_state(state)?;
683    initialize(&mut next, bound_issuer_id, epoch);
684    let key_id = key_id_plain(status_key)?;
685    if !next.status_key_id.is_empty() && next.status_key_id != key_id {
686        return plain("revocation list status key does not match configured epoch binding");
687    }
688    next.status_key_id = key_id.clone();
689    let dup_index = find_observation(&next.observations, epoch, LIST, list.sequence, &digest);
690    let duplicate = dup_index.is_some();
691    let future = beyond_skew(list.updated_at, now, policy.clock_skew_seconds);
692    let mut obs = RevocationObservationV2 {
693        object_type: LIST,
694        status_key_epoch: epoch,
695        status_key_id: key_id,
696        sequence: list.sequence,
697        evidence_digest: digest.clone(),
698        body_digest,
699        revoked_set_digest: set_digest,
700        revoked_cert_ids: revoked_ids(&list.revoked),
701        future_dated: future,
702        ..Default::default()
703    };
704    let fresh = list_fresh(list, policy, now);
705    if !duplicate {
706        if let Some(prior) = find_set_observation(&next.observations, &obs) {
707            if prior.fork {
708                return Ok(next);
709            }
710            if (prior.future_dated || prior.gap) && !future && fresh {
711                if (next.has_floor && list.sequence < next.floor)
712                    || has_forked_sequence(&next.observations, epoch, 0, list.sequence)
713                {
714                    return Ok(next);
715                }
716            } else if !prior.accepted
717                && !prior.fork
718                && next.has_floor
719                && list.sequence == next.floor
720                && next
721                    .accepted_snapshot
722                    .as_ref()
723                    .is_some_and(|a| a.sequence < next.floor)
724                && !future
725                && fresh
726            {
727                // A fresh same-set snapshot at a push-advanced floor becomes the new base.
728            } else if prior.accepted
729                && next.has_floor
730                && list.sequence == next.floor
731                && next
732                    .accepted_snapshot
733                    .as_ref()
734                    .is_some_and(|a| heartbeat_preferred(list, &digest, a))
735            {
736                // A newer same-set current-floor heartbeat may refresh freshness.
737            } else {
738                return Ok(next);
739            }
740        }
741    }
742    if let Some(idx) = dup_index {
743        let prior = &next.observations[idx];
744        if prior.accepted || (!prior.future_dated && !prior.gap) || future || !fresh {
745            return Ok(next);
746        }
747        if next.has_floor && list.sequence < next.floor {
748            return Ok(next);
749        }
750        if has_forked_sequence(&next.observations, epoch, 0, list.sequence) {
751            return Ok(next);
752        }
753    } else {
754        add_revocations(&mut next, &obs.revoked_cert_ids);
755        if list.sequence > next.max_observed_sequence {
756            next.max_observed_sequence = list.sequence;
757        }
758    }
759    if future {
760        next.future_dated_object_observed = true;
761        next.reconciliation_required = true;
762    }
763    if sequence_conflict(&next.observations, &obs)
764        || (next.has_floor
765            && list.sequence == next.floor
766            && !equal_sets(&obs.revoked_cert_ids, &next.accepted_cert_ids))
767        || (next.has_floor
768            && list.sequence < next.floor
769            && !contains_all(&next.accepted_cert_ids, &obs.revoked_cert_ids))
770    {
771        mark_fork(&mut next, &mut obs, list.sequence);
772    }
773    let applicable = required_for_snapshot(&next.observations, epoch, list.sequence);
774    if !contains_all(&obs.revoked_cert_ids, &applicable) {
775        mark_fork(&mut next, &mut obs, list.sequence);
776    }
777    if snapshot_conflicts_with_push(&next, epoch, list.sequence, &obs.revoked_cert_ids.clone()) {
778        mark_fork(&mut next, &mut obs, list.sequence);
779    }
780    let push_obs = |next: &mut RevocationStatusStateV2, obs: RevocationObservationV2| {
781        if !duplicate {
782            next.observations.push(obs);
783        }
784    };
785    if !fresh {
786        if next.has_floor && list.sequence <= next.floor {
787            push_obs(&mut next, obs);
788            return Ok(next);
789        }
790        next.reconciliation_required = true;
791        obs.gap = true;
792        push_obs(&mut next, obs);
793        return Ok(next);
794    }
795    if obs.fork {
796        push_obs(&mut next, obs);
797        return Ok(next);
798    }
799    if !next.has_floor
800        && (!contains_all(&obs.revoked_cert_ids, &next.deny_union_cert_ids)
801            || list.sequence < next.max_observed_sequence)
802    {
803        next.reconciliation_required = true;
804        obs.gap = true;
805        push_obs(&mut next, obs);
806        return Ok(next);
807    }
808    if next.has_floor && list.sequence < next.floor {
809        push_obs(&mut next, obs);
810        return Ok(next);
811    }
812    if next.has_floor && list.sequence == next.floor {
813        if !equal_sets(&obs.revoked_cert_ids, &next.accepted_cert_ids) {
814            mark_fork(&mut next, &mut obs, list.sequence);
815            push_obs(&mut next, obs);
816            return Ok(next);
817        }
818        let replace = match &next.accepted_snapshot {
819            None => true,
820            Some(a) => a.sequence < list.sequence || heartbeat_preferred(list, &digest, a),
821        };
822        if replace {
823            next.accepted_snapshot = Some(clone_list(list)?);
824        }
825        obs.accepted = true;
826    } else {
827        let copy = clone_list(list)?;
828        if next.has_floor && list.sequence == next.floor + 1 {
829            next.has_preceding_checkpoint = true;
830            next.preceding_floor = next.floor;
831            next.preceding_accepted_cert_ids = sorted_unique(&next.accepted_cert_ids);
832        } else {
833            next.has_preceding_checkpoint = false;
834            next.preceding_floor = 0;
835            next.preceding_accepted_cert_ids = Vec::new();
836        }
837        next.accepted_snapshot = Some(copy);
838        next.accepted_cert_ids = sorted_unique(&obs.revoked_cert_ids);
839        next.has_floor = true;
840        next.floor = list.sequence;
841        obs.accepted = true;
842    }
843    if next.reconciliation_required {
844        let recoverable = next.fork_sequence == 0
845            || (list.sequence > next.fork_sequence && list.sequence >= next.max_observed_sequence);
846        let fully = contains_all(&obs.revoked_cert_ids, &next.deny_union_cert_ids);
847        if recoverable && fully && list.sequence >= next.max_observed_sequence {
848            next.reconciliation_required = false;
849            next.future_dated_object_observed = false;
850            next.fork_sequence = 0;
851        }
852    } else if list.sequence >= next.max_observed_sequence
853        && contains_all(&obs.revoked_cert_ids, &next.deny_union_cert_ids)
854    {
855        next.reconciliation_required = false;
856    }
857    let prior_accepted = dup_index.map(|i| next.observations[i].accepted);
858    if !duplicate || (obs.accepted && prior_accepted == Some(false)) {
859        next.observations.push(obs);
860    }
861    Ok(next)
862}
863
864/// Verify and apply one signed push. Noncontiguous or future pushes join
865/// the deny union but make current status unavailable until repaired.
866pub fn apply_revocation_push_v2(
867    state: &RevocationStatusStateV2,
868    push: &RevocationPushV2,
869    bound_issuer_id: &str,
870    status_key_epoch: u64,
871    status_key: &HybridPublicKey,
872    policy: &RevocationStatusPolicyV2,
873    now: i64,
874) -> V2Result<RevocationStatusStateV2> {
875    apply_push_inner(
876        state,
877        push,
878        bound_issuer_id,
879        status_key_epoch,
880        status_key,
881        policy,
882        now,
883    )
884    .map(|r| {
885        if r.issuer_id.is_empty() {
886            r
887        } else {
888            compact(r)
889        }
890    })
891    .classify(V2ErrorClass::StatusObjectRejected)
892}
893
894fn apply_push_inner(
895    state: &RevocationStatusStateV2,
896    push: &RevocationPushV2,
897    bound_issuer_id: &str,
898    epoch: u64,
899    status_key: &HybridPublicKey,
900    policy: &RevocationStatusPolicyV2,
901    now: i64,
902) -> V2Result<RevocationStatusStateV2> {
903    validate_policy(policy)?;
904    if !valid_v2_timestamp(now) || epoch == 0 || epoch > MAX_SAFE as u64 {
905        return plain("revocation push application has invalid time or status-key epoch");
906    }
907    verify_revocation_push_v2_signature(push, bound_issuer_id, status_key)?;
908    validate_binding(state, bound_issuer_id, epoch)?;
909    let digest = status_evidence_digest_push_v2(push)?;
910    let body_digest = sha384(&[&revocation_push_v2_signable_bytes(push)?]);
911    let set_digest = revoked_set_digest(&push.revoked)?;
912    let mut next = clone_state(state)?;
913    initialize(&mut next, bound_issuer_id, epoch);
914    let key_id = key_id_plain(status_key)?;
915    if !next.status_key_id.is_empty() && next.status_key_id != key_id {
916        return plain("revocation push status key does not match configured epoch binding");
917    }
918    next.status_key_id = key_id.clone();
919    if find_observation(&next.observations, epoch, PUSH, push.sequence, &digest).is_some()
920        || next.observations.iter().any(|o| {
921            o.status_key_epoch == epoch
922                && o.object_type == PUSH
923                && o.sequence == push.sequence
924                && o.body_digest == body_digest
925        })
926    {
927        return Ok(next);
928    }
929    let future = beyond_skew(push.pushed_at, now, policy.clock_skew_seconds);
930    let mut obs = RevocationObservationV2 {
931        object_type: PUSH,
932        status_key_epoch: epoch,
933        status_key_id: key_id,
934        sequence: push.sequence,
935        evidence_digest: digest,
936        body_digest,
937        revoked_set_digest: set_digest,
938        revoked_cert_ids: revoked_ids(&push.revoked),
939        future_dated: future,
940        ..Default::default()
941    };
942    add_revocations(&mut next, &obs.revoked_cert_ids);
943    if push.sequence > next.max_observed_sequence {
944        next.max_observed_sequence = push.sequence;
945    }
946    if future {
947        next.future_dated_object_observed = true;
948        next.reconciliation_required = true;
949    }
950    if sequence_conflict(&next.observations, &obs) {
951        mark_fork(&mut next, &mut obs, push.sequence);
952    }
953    if let Some(conflicting) = snapshot_omission_for_push(&next, epoch, &obs) {
954        mark_fork(&mut next, &mut obs, conflicting);
955    }
956    let expected = if next.has_floor { next.floor + 1 } else { 1 };
957    if next.has_floor && push.sequence <= next.floor {
958        if push.sequence == next.floor {
959            let checkpoint_mismatch = next.has_preceding_checkpoint
960                && next.preceding_floor == push.sequence - 1
961                && !equal_sets(
962                    &next.accepted_cert_ids,
963                    &concat(&next.preceding_accepted_cert_ids, &obs.revoked_cert_ids),
964                );
965            if checkpoint_mismatch || !contains_all(&next.accepted_cert_ids, &obs.revoked_cert_ids)
966            {
967                mark_fork(&mut next, &mut obs, push.sequence);
968            } else if !obs.fork && contains_all(&next.accepted_cert_ids, &obs.revoked_cert_ids) {
969                // The accepted full set already proves these entries.
970            } else {
971                obs.gap = true;
972                next.reconciliation_required = true;
973            }
974            next.observations.push(obs);
975            return Ok(next);
976        }
977        if !contains_all(&next.accepted_cert_ids, &obs.revoked_cert_ids) {
978            mark_fork(&mut next, &mut obs, push.sequence);
979        }
980        next.observations.push(obs);
981        return Ok(next);
982    }
983    if !next.has_floor || push.sequence != expected || next.reconciliation_required || future {
984        obs.gap = !obs.fork;
985        next.reconciliation_required = true;
986        next.observations.push(obs);
987        return Ok(next);
988    }
989    next.accepted_cert_ids = sorted_unique(&concat(&next.accepted_cert_ids, &obs.revoked_cert_ids));
990    next.has_preceding_checkpoint = false;
991    next.preceding_floor = 0;
992    next.preceding_accepted_cert_ids = Vec::new();
993    next.has_floor = true;
994    next.floor = push.sequence;
995    obs.accepted = true;
996    next.observations.push(obs);
997    Ok(next)
998}
999
1000/// Apply an already-authenticated status-key epoch transition, preserving
1001/// issuer-wide denials and making old accepted state unusable.
1002pub fn transition_revocation_status_epoch_v2(
1003    state: &RevocationStatusStateV2,
1004    issuer_id: &str,
1005    next_epoch: u64,
1006    next_status_key: &HybridPublicKey,
1007) -> V2Result<RevocationStatusStateV2> {
1008    (|| {
1009        if issuer_id.is_empty() || next_epoch == 0 || next_epoch > MAX_SAFE as u64 {
1010            return plain("status-key epoch transition has invalid issuer or epoch");
1011        }
1012        if state.issuer_id != issuer_id
1013            || state.status_key_epoch == 0
1014            || state.status_key_epoch >= MAX_SAFE as u64
1015            || next_epoch != state.status_key_epoch + 1
1016        {
1017            return plain(
1018                "status-key epoch transition must advance exactly one configured issuer epoch",
1019            );
1020        }
1021        validate_binding(state, issuer_id, state.status_key_epoch)
1022            .map_err(|e| e.context("cannot transition malformed status state"))?;
1023        validate_accepted_state(state)
1024            .map_err(|e| e.context("cannot transition invalid accepted status state"))?;
1025        let key_id = key_id_plain(next_status_key)?;
1026        if key_id == state.status_key_id || state.retired_status_key_ids.contains(&key_id) {
1027            return plain(
1028                "status-key epoch transition cannot reuse a current or retired status key",
1029            );
1030        }
1031        let mut next = clone_state(state)?;
1032        let mut retired = next.retired_status_key_ids.clone();
1033        retired.push(state.status_key_id.clone());
1034        next.retired_status_key_ids = sorted_unique(&retired);
1035        next.status_key_epoch = next_epoch;
1036        next.status_key_id = key_id;
1037        next.has_floor = false;
1038        next.floor = 0;
1039        next.accepted_snapshot = None;
1040        next.accepted_cert_ids = Vec::new();
1041        next.has_preceding_checkpoint = false;
1042        next.preceding_floor = 0;
1043        next.preceding_accepted_cert_ids = Vec::new();
1044        next.max_observed_sequence = 0;
1045        next.fork_sequence = 0;
1046        next.reconciliation_required = false;
1047        next.future_dated_object_observed = false;
1048        Ok(next)
1049    })()
1050    // SPEC-v2 §2.7: a rejected status-key epoch transition, including reuse
1051    // of a current or retired key, is status_object_rejected.
1052    .classify(V2ErrorClass::StatusObjectRejected)
1053}
1054
1055fn evidence_entry(
1056    issuer_id: &str,
1057    status_key_id: &str,
1058    o: &RevocationObservationV2,
1059) -> StatusEvidenceEntryV2 {
1060    let key = if o.status_key_id.is_empty() {
1061        status_key_id
1062    } else {
1063        &o.status_key_id
1064    };
1065    StatusEvidenceEntryV2 {
1066        issuer_id: issuer_id.to_string(),
1067        status_key_id: key.to_string(),
1068        sequence: o.sequence,
1069        object_type: o.object_type,
1070        digest: format!("sha384:{}", hex::encode(&o.evidence_digest)),
1071    }
1072}
1073
1074fn push_unique(evidence: &mut Vec<StatusEvidenceEntryV2>, e: StatusEvidenceEntryV2) {
1075    if !evidence.contains(&e) {
1076        evidence.push(e);
1077    }
1078}
1079
1080pub(crate) fn sort_evidence(
1081    mut evidence: Vec<StatusEvidenceEntryV2>,
1082) -> Vec<StatusEvidenceEntryV2> {
1083    evidence.sort_by(compare_evidence);
1084    evidence
1085}
1086
1087fn accepted_evidence(
1088    s: &RevocationStatusStateV2,
1089    issuer_id: &str,
1090    key_id: &str,
1091) -> Vec<StatusEvidenceEntryV2> {
1092    let mut evidence = Vec::new();
1093    let Some(snap) = &s.accepted_snapshot else {
1094        return evidence;
1095    };
1096    if let Ok(d) = status_evidence_digest_list_v2(snap) {
1097        evidence.push(StatusEvidenceEntryV2 {
1098            issuer_id: issuer_id.to_string(),
1099            status_key_id: key_id.to_string(),
1100            sequence: snap.sequence,
1101            object_type: LIST,
1102            digest: format!("sha384:{}", hex::encode(d)),
1103        });
1104    }
1105    for o in &s.observations {
1106        if o.status_key_epoch == s.status_key_epoch
1107            && o.object_type == PUSH
1108            && o.accepted
1109            && o.sequence > snap.sequence
1110            && o.sequence <= s.floor
1111        {
1112            push_unique(&mut evidence, evidence_entry(issuer_id, key_id, o));
1113        }
1114    }
1115    sort_evidence(evidence)
1116}
1117
1118fn unavailable_evidence(
1119    s: &RevocationStatusStateV2,
1120    issuer_id: &str,
1121    key_id: &str,
1122) -> Vec<StatusEvidenceEntryV2> {
1123    let mut evidence = accepted_evidence(s, issuer_id, key_id);
1124    for o in &s.observations {
1125        if o.status_key_epoch != s.status_key_epoch {
1126            continue;
1127        }
1128        if o.sequence > s.floor
1129            || o.fork
1130            || o.gap
1131            || o.future_dated
1132            || (s.reconciliation_required && !o.accepted)
1133        {
1134            push_unique(&mut evidence, evidence_entry(issuer_id, key_id, o));
1135        }
1136    }
1137    sort_evidence(evidence)
1138}
1139
1140/// Derive a fail-closed answer and deterministic evidence for one
1141/// CertificateRef from the issuer's reducer state.
1142///
1143/// Go `RevocationStatusForCertV2` returns these errors unclassified; this
1144/// port classifies them `configuration_invalid` (an invalid query, policy,
1145/// or state binding), keeping any class already fixed (for example the
1146/// accepted snapshot's signature verification class).
1147pub fn revocation_status_for_cert_v2(
1148    state: &RevocationStatusStateV2,
1149    issuer_id: &str,
1150    cert_id: &str,
1151    status_key_epoch: u64,
1152    status_key: &HybridPublicKey,
1153    policy: &RevocationStatusPolicyV2,
1154    now: i64,
1155) -> V2Result<RevocationStatusResultV2> {
1156    revocation_status_for_cert_inner(
1157        state,
1158        issuer_id,
1159        cert_id,
1160        status_key_epoch,
1161        status_key,
1162        policy,
1163        now,
1164    )
1165    .classify(V2ErrorClass::ConfigurationInvalid)
1166}
1167
1168/// Go `RevocationStatusForCertV2` with Go's (unclassified) error classes.
1169pub(crate) fn revocation_status_for_cert_inner(
1170    state: &RevocationStatusStateV2,
1171    issuer_id: &str,
1172    cert_id: &str,
1173    status_key_epoch: u64,
1174    status_key: &HybridPublicKey,
1175    policy: &RevocationStatusPolicyV2,
1176    now: i64,
1177) -> V2Result<RevocationStatusResultV2> {
1178    validate_policy(policy)?;
1179    validate_binding(state, issuer_id, status_key_epoch)?;
1180    validate_accepted_state(state)?;
1181    if cert_id.is_empty() || !valid_v2_timestamp(now) {
1182        return plain("status query has invalid certificate ID or time");
1183    }
1184    let key_id = key_id_plain(status_key)?;
1185    if state.issuer_id != issuer_id
1186        || state.status_key_epoch != status_key_epoch
1187        || state.status_key_id != key_id
1188    {
1189        return plain("status query does not match the configured issuer status-key binding");
1190    }
1191    if let Some(snap) = &state.accepted_snapshot {
1192        verify_revocation_list_v2_signature(snap, issuer_id, status_key)
1193            .map_err(|e| e.context("accepted status snapshot signature is invalid"))?;
1194    }
1195    let cert = [cert_id.to_string()];
1196    if contains_all(&state.deny_union_cert_ids, &cert) {
1197        let mut evidence = accepted_evidence(state, issuer_id, &key_id);
1198        for o in &state.observations {
1199            if o.revoked_cert_ids.contains(&cert[0]) {
1200                push_unique(&mut evidence, evidence_entry(issuer_id, &key_id, o));
1201            }
1202        }
1203        return Ok(RevocationStatusResultV2 {
1204            status: "revoked".into(),
1205            reason: String::new(),
1206            evidence: sort_evidence(evidence),
1207            fresh_until: 0,
1208        });
1209    }
1210    if !state.has_floor
1211        || state.accepted_snapshot.is_none()
1212        || policy.max_list_lifetime_seconds == 0
1213        || policy.max_status_age_seconds == 0
1214        || state.future_dated_object_observed
1215        || state.reconciliation_required
1216        || state.floor < state.max_observed_sequence
1217        || !contains_all(&state.accepted_cert_ids, &state.deny_union_cert_ids)
1218    {
1219        return Ok(RevocationStatusResultV2 {
1220            status: "indeterminate".into(),
1221            reason: "unavailable".into(),
1222            evidence: unavailable_evidence(state, issuer_id, &key_id),
1223            fresh_until: 0,
1224        });
1225    }
1226    let Some(snap) = state.accepted_snapshot.as_ref() else {
1227        return Ok(RevocationStatusResultV2::unavailable());
1228    };
1229    if !list_fresh(snap, policy, now) {
1230        return Ok(RevocationStatusResultV2 {
1231            status: "indeterminate".into(),
1232            reason: "stale".into(),
1233            evidence: accepted_evidence(state, issuer_id, &key_id),
1234            fresh_until: 0,
1235        });
1236    }
1237    Ok(RevocationStatusResultV2 {
1238        status: "not_revoked".into(),
1239        reason: String::new(),
1240        evidence: accepted_evidence(state, issuer_id, &key_id),
1241        fresh_until: snap
1242            .next_update
1243            .min(snap.updated_at + policy.max_status_age_seconds),
1244    })
1245}
1246
1247// ---------------------------------------------------------------------------
1248// Aggregation over every CertificateRef
1249
1250/// Every issuer-scoped certificate whose status must be resolved.
1251#[derive(Debug, Clone, PartialEq, Eq)]
1252pub struct V2CertificateStatusCheck {
1253    pub delegation_index: usize,
1254    pub issuer_id: String,
1255    pub subject_id: String,
1256    pub cert_id: String,
1257}
1258
1259/// Caller-authenticated status-key role bindings.
1260#[derive(Debug, Clone, Default)]
1261pub struct V2StatusRoleBindings {
1262    /// status key ID -> issuer ID.
1263    pub status_key_issuers: BTreeMap<String, String>,
1264    /// issuer ID -> current status key ID.
1265    pub current_status_key_ids: BTreeMap<String, String>,
1266    /// Non-status key roles that must never authenticate status.
1267    pub reserved_key_ids: BTreeSet<String>,
1268}
1269
1270/// Deterministic aggregate of one result per CertificateRef.
1271#[derive(Debug, Clone, PartialEq, Eq)]
1272pub struct V2StatusAssessment {
1273    pub assessment: String,
1274    pub reason: String,
1275    pub evidence: Vec<StatusEvidenceEntryV2>,
1276    pub fresh_until: i64,
1277}
1278
1279fn validate_roles(
1280    roles: &V2StatusRoleBindings,
1281    checks: &[V2CertificateStatusCheck],
1282    allow_unbound_issuers: bool,
1283) -> V2Result<()> {
1284    for (key, issuer) in &roles.status_key_issuers {
1285        if !valid_v2_id(key) || !valid_v2_id(issuer) {
1286            return plain("authenticated status-key binding is malformed");
1287        }
1288        if roles.reserved_key_ids.contains(key) {
1289            return plain("status key collides with a reserved non-status key role");
1290        }
1291    }
1292    for check in checks {
1293        let bound = roles.current_status_key_ids.get(&check.issuer_id);
1294        if bound.is_none() && allow_unbound_issuers {
1295            continue;
1296        }
1297        let key = bound.cloned().unwrap_or_default();
1298        if roles.status_key_issuers.get(&key) != Some(&check.issuer_id) {
1299            return plain("issuer lacks an authenticated current status-key binding");
1300        }
1301    }
1302    if roles.reserved_key_ids.iter().any(|k| !valid_v2_id(k)) {
1303        return plain("reserved non-status key ID is malformed");
1304    }
1305    Ok(())
1306}
1307
1308fn valid_current_evidence(evidence: &[StatusEvidenceEntryV2], issuer_id: &str) -> bool {
1309    if evidence.is_empty() {
1310        return false;
1311    }
1312    let mut base: Option<&StatusEvidenceEntryV2> = None;
1313    let mut bases = 0;
1314    let mut pushes = Vec::new();
1315    for e in evidence {
1316        if e.issuer_id != issuer_id {
1317            return false;
1318        }
1319        match e.object_type {
1320            LIST => {
1321                bases += 1;
1322                base = Some(e);
1323            }
1324            PUSH => pushes.push(e),
1325            _ => return false,
1326        }
1327    }
1328    let (1, Some(base)) = (bases, base) else {
1329        return false;
1330    };
1331    pushes.sort_by_key(|p| p.sequence);
1332    pushes.iter().enumerate().all(|(i, p)| {
1333        p.status_key_id == base.status_key_id && p.sequence == base.sequence + i as i64 + 1
1334    })
1335}
1336
1337fn add_history(
1338    h: &mut BTreeMap<String, Vec<StatusEvidenceEntryV2>>,
1339    issuer: &str,
1340    evidence: &[StatusEvidenceEntryV2],
1341) -> bool {
1342    let canonical = sort_evidence(evidence.to_vec());
1343    match h.get(issuer) {
1344        None => {
1345            h.insert(issuer.to_string(), canonical);
1346            true
1347        }
1348        Some(prior) => *prior == canonical,
1349    }
1350}
1351
1352/// Go `aggregateCertificateStatusResultsV2` (internal; SPEC-v2 §6.5):
1353/// exactly one reducer result per check, in order. Revoked outranks
1354/// unavailable, which outranks stale, independent of chain order.
1355// Go uses it only in resolveClaimProofBundleV2AfterStatusResults, which only
1356// Go unit tests call; the live verifier aggregates inside runV2StatusStage.
1357// Kept for parity.
1358#[allow(dead_code)]
1359pub(crate) fn aggregate_certificate_status_results_v2(
1360    checks: &[V2CertificateStatusCheck],
1361    results: &[RevocationStatusResultV2],
1362    roles: &V2StatusRoleBindings,
1363) -> V2Result<V2StatusAssessment> {
1364    aggregate_certificate_status_v2(checks, results, roles, false)
1365}
1366
1367/// Go `aggregateCertificateStatusV2`, the shared aggregator.
1368/// `allow_unbound_issuers` is used only by the live verifier, which derives
1369/// results from its own journal and reports an issuer without authenticated
1370/// status configuration as unavailable instead of aborting the evaluation.
1371pub(crate) fn aggregate_certificate_status_v2(
1372    checks: &[V2CertificateStatusCheck],
1373    results: &[RevocationStatusResultV2],
1374    roles: &V2StatusRoleBindings,
1375    allow_unbound_issuers: bool,
1376) -> V2Result<V2StatusAssessment> {
1377    if checks.is_empty() || checks.len() != results.len() {
1378        return plain(
1379            "v2 status aggregation requires one result for every non-empty certificate list",
1380        );
1381    }
1382    validate_roles(roles, checks, allow_unbound_issuers)?;
1383    let mut issuers = Vec::new();
1384    let mut seen_refs = BTreeSet::new();
1385    let mut issuer_set = BTreeSet::new();
1386    let mut subject_set = BTreeSet::new();
1387    for (i, c) in checks.iter().enumerate() {
1388        if c.delegation_index != i
1389            || !valid_v2_id(&c.issuer_id)
1390            || !valid_v2_id(&c.subject_id)
1391            || c.cert_id.is_empty()
1392        {
1393            return plain(format!(
1394                "v2 status check {i} has an invalid delegation index or CertificateRef"
1395            ));
1396        }
1397        if !seen_refs.insert((c.issuer_id.clone(), c.cert_id.clone())) {
1398            return plain("v2 status checks contain a duplicate CertificateRef");
1399        }
1400        subject_set.insert(c.subject_id.clone());
1401        if issuer_set.insert(c.issuer_id.clone()) {
1402            issuers.push(c.issuer_id.clone());
1403        }
1404    }
1405    let mut evidence_out: Vec<StatusEvidenceEntryV2> = Vec::new();
1406    let mut seen = BTreeSet::new();
1407    let mut bindings: BTreeMap<String, StatusEvidenceEntryV2> = BTreeMap::new();
1408    let mut invalid_digests = BTreeSet::new();
1409    let (mut invalid, mut any_revoked, mut any_unavailable, mut any_stale) =
1410        (false, false, false, false);
1411    let mut fresh_until = 0i64;
1412    let mut revoked_candidates = Vec::new();
1413    let mut history = BTreeMap::new();
1414    for (i, c) in checks.iter().enumerate() {
1415        let r = &results[i];
1416        let mut valid = true;
1417        for e in &r.evidence {
1418            if e.issuer_id != c.issuer_id
1419                || !valid_v2_id(&e.status_key_id)
1420                || e.sequence <= 0
1421                || e.sequence > MAX_SAFE
1422                || !valid_prefixed_digest(&e.digest)
1423                || (e.object_type != LIST && e.object_type != PUSH)
1424            {
1425                valid = false;
1426                continue;
1427            }
1428            if issuer_set.contains(&e.status_key_id) || subject_set.contains(&e.status_key_id) {
1429                valid = false;
1430                continue;
1431            }
1432            if roles.reserved_key_ids.contains(&e.status_key_id)
1433                || roles.status_key_issuers.get(&e.status_key_id) != Some(&e.issuer_id)
1434                || (r.status != "revoked"
1435                    && roles.current_status_key_ids.get(&e.issuer_id) != Some(&e.status_key_id))
1436            {
1437                valid = false;
1438                continue;
1439            }
1440            if let Some(prior) = bindings.get(&e.digest) {
1441                if prior != e {
1442                    invalid_digests.insert(e.digest.clone());
1443                }
1444            }
1445            bindings.insert(e.digest.clone(), e.clone());
1446            if seen.insert(e.clone()) {
1447                evidence_out.push(e.clone());
1448            }
1449        }
1450        match r.status.as_str() {
1451            "not_revoked" => {
1452                valid = valid
1453                    && r.reason.is_empty()
1454                    && r.fresh_until > 0
1455                    && r.fresh_until <= MAX_SAFE
1456                    && valid_current_evidence(&r.evidence, &c.issuer_id);
1457                if valid {
1458                    if fresh_until == 0 || r.fresh_until < fresh_until {
1459                        fresh_until = r.fresh_until;
1460                    }
1461                    valid = add_history(&mut history, &c.issuer_id, &r.evidence);
1462                }
1463            }
1464            "revoked" => {
1465                valid = valid && r.reason.is_empty() && !r.evidence.is_empty();
1466                if valid {
1467                    revoked_candidates.push(i);
1468                }
1469            }
1470            "indeterminate" => match r.reason.as_str() {
1471                "unavailable" => any_unavailable = true,
1472                "stale" => {
1473                    valid = valid && valid_current_evidence(&r.evidence, &c.issuer_id);
1474                    if valid {
1475                        valid = add_history(&mut history, &c.issuer_id, &r.evidence);
1476                    }
1477                    any_stale = true;
1478                }
1479                _ => valid = false,
1480            },
1481            _ => valid = false,
1482        }
1483        invalid = invalid || !valid;
1484    }
1485    if !invalid_digests.is_empty() {
1486        evidence_out.retain(|e| !invalid_digests.contains(&e.digest));
1487        invalid = true;
1488    }
1489    for i in revoked_candidates {
1490        let r = &results[i];
1491        let ok = !r.evidence.is_empty()
1492            && !r
1493                .evidence
1494                .iter()
1495                .any(|e| invalid_digests.contains(&e.digest));
1496        any_revoked = any_revoked || ok;
1497    }
1498    let evidence = sort_evidence(evidence_out);
1499    let mut issuers_sorted = issuers.clone();
1500    issuers_sorted.sort();
1501    let (assessment, reason) = if any_revoked {
1502        ("revoked", "delegation_revoked")
1503    } else if invalid || any_unavailable {
1504        ("unavailable", "status_unavailable")
1505    } else if any_stale {
1506        ("stale", "status_stale")
1507    } else if !has_accepted_status_history_per_issuer(&evidence, &issuers_sorted) {
1508        ("unavailable", "status_unavailable")
1509    } else {
1510        ("current", "")
1511    };
1512    Ok(V2StatusAssessment {
1513        assessment: assessment.into(),
1514        reason: reason.into(),
1515        evidence,
1516        fresh_until: if assessment == "current" {
1517            fresh_until
1518        } else {
1519            0
1520        },
1521    })
1522}