Skip to main content

ratify_protocol/v2/
journal.rs

1//! `SecurityJournalV2` (SPEC-v2 §6.6): the deployment's status, role, and
2//! status-key state, its validated transitions, and the anchored
3//! compare-and-swap store contract. Mirrors Go `security_journal_v2.go`.
4//!
5//! The logical snapshot, digest, export/import, and version 1 migration live
6//! in [`super::journal_snapshot`].
7//!
8//! Error classes: Go returns most journal errors unclassified. At this
9//! module's public boundary they are classified as SPEC-v2 §6.6 implies:
10//! journal operations (`record_security_key_role_v2`,
11//! `configure_status_key_epoch_v2`, `apply_revocation_*_to_journal_v2`,
12//! `register_*`) use `status_object_rejected`; the query
13//! `revocation_status_from_journal_v2` uses `configuration_invalid`;
14//! record validation (`validate_security_journal_v2`) uses `malformed`;
15//! `validate_security_journal_transition_v2` reports an invalid record as
16//! `malformed` and an invalid transition between valid records as
17//! `status_object_rejected`. A class Go
18//! already fixed (a reducer rejection, an epoch transition's
19//! `configuration_invalid`, a store's own class) is kept.
20
21use std::collections::{BTreeMap, BTreeSet};
22use std::fmt;
23
24use super::context::V2Context;
25use super::crypto::sha384;
26use super::errors::{plain, Classify, V2Error, V2ErrorClass, V2Result};
27use super::journal_snapshot::{same_security_journal_content_v2, security_journal_digest_v2};
28use super::status::{
29    apply_revocation_list_v2, apply_revocation_push_v2, canonicalize_state, compact, contains_all,
30    equal_sets, key_id_plain, must_retain, revocation_status_for_cert_inner, semantic_key,
31    transition_revocation_status_epoch_v2, validate_accepted_state, validate_binding,
32    RevocationStatusPolicyV2, RevocationStatusResultV2, RevocationStatusStateV2, LIST, PUSH,
33};
34use super::wire::{RevocationListV2, RevocationPushV2, MAX_SAFE};
35use crate::types::HybridPublicKey;
36
37/// The current record version (canonical snapshot digest). Version 1
38/// records use the legacy Go `encoding/json` digest and must be migrated.
39pub(crate) const SECURITY_JOURNAL_VERSION_V2: u16 = 2;
40/// The version 1 (alpha) record version, accepted only for migration.
41pub(crate) const SECURITY_JOURNAL_LEGACY_VERSION: u16 = 1;
42
43/// The independently anchored head of a deployment's security journal. A
44/// backend must not derive its rollback protection solely from the journal
45/// records it stores.
46#[derive(Debug, Clone, PartialEq, Eq, Default, Hash)]
47pub struct SecurityJournalHeadV2 {
48    pub generation: u64,
49    pub digest: String,
50}
51
52/// Permanently assigns a key ID and both hybrid key components to one role
53/// for a verifier deployment.
54#[derive(Debug, Clone, PartialEq, Eq, Default, Hash)]
55pub struct KeyRoleBindingV2 {
56    pub key_id: String,
57    pub ed25519_digest: String,
58    pub ml_dsa_65_digest: String,
59    pub role: String,
60}
61
62/// Preserves every authenticated status-key epoch, including retired
63/// epochs, for one issuer.
64#[derive(Debug, Clone, PartialEq, Eq, Default, Hash)]
65pub struct StatusKeyBindingV2 {
66    pub issuer_id: String,
67    pub epoch: u64,
68    pub status_key_id: String,
69    pub ed25519_digest: String,
70    pub ml_dsa_65_digest: String,
71}
72
73/// The state whose loss or rollback can make verification unsafe. It is a
74/// logical record; durability and anti-rollback guarantees come from
75/// [`SecurityJournalStoreV2`].
76///
77/// Construct one with [`empty_security_journal_v2`],
78/// `import_security_journal_snapshot_v2`, or
79/// `decode_security_journal_json_v2` (or `Default` and field assignment).
80#[derive(Debug, Clone, Default)]
81pub struct SecurityJournalV2 {
82    pub version: u16,
83    pub generation: u64,
84    pub previous_digest: String,
85    pub digest: String,
86    pub status_by_issuer: BTreeMap<String, RevocationStatusStateV2>,
87    pub key_role_history: Vec<KeyRoleBindingV2>,
88    pub status_key_history: Vec<StatusKeyBindingV2>,
89    /// Members that were JSON `null` (Go nil slices and maps) when a
90    /// version 1 record was decoded. Go's legacy digest re-encodes a nil
91    /// slice as `null` and an empty one as `[]`; Rust cannot tell them apart
92    /// without this record. It affects only the version 1 digest and the
93    /// "incomplete shape" check, and is empty for every other journal.
94    pub(crate) legacy_null_members: BTreeSet<String>,
95}
96
97/// Why a [`SecurityJournalStoreV2::compare_and_swap`] did not commit.
98#[derive(Debug, Clone, PartialEq, Eq)]
99pub enum SecurityJournalStoreErrorV2 {
100    /// Another writer advanced the anchored journal (Go
101    /// `ErrSecurityJournalConflictV2`). The operation must be reloaded and
102    /// re-evaluated, not blindly retried with a stale state transition.
103    Conflict,
104    /// Any other store failure.
105    Failed(V2Error),
106}
107
108impl fmt::Display for SecurityJournalStoreErrorV2 {
109    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
110        match self {
111            SecurityJournalStoreErrorV2::Conflict => {
112                f.write_str(SECURITY_JOURNAL_CONFLICT_MESSAGE_V2)
113            }
114            SecurityJournalStoreErrorV2::Failed(e) => write!(f, "{e}"),
115        }
116    }
117}
118
119impl std::error::Error for SecurityJournalStoreErrorV2 {}
120
121impl From<V2Error> for SecurityJournalStoreErrorV2 {
122    fn from(e: V2Error) -> Self {
123        SecurityJournalStoreErrorV2::Failed(e)
124    }
125}
126
127/// The diagnostic message of a compare-and-swap conflict reported through a
128/// public journal operation (Go `ErrSecurityJournalConflictV2`).
129pub const SECURITY_JOURNAL_CONFLICT_MESSAGE_V2: &str = "security journal compare-and-swap conflict";
130
131/// Whether a public journal operation failed because another writer
132/// advanced the anchored journal (Go `errors.Is(err,
133/// ErrSecurityJournalConflictV2)`).
134pub fn is_security_journal_conflict_v2(e: &V2Error) -> bool {
135    e.message == SECURITY_JOURNAL_CONFLICT_MESSAGE_V2
136}
137
138impl SecurityJournalStoreErrorV2 {
139    fn into_v2(self) -> V2Error {
140        match self {
141            SecurityJournalStoreErrorV2::Conflict => {
142                V2Error::plain(SECURITY_JOURNAL_CONFLICT_MESSAGE_V2)
143            }
144            SecurityJournalStoreErrorV2::Failed(e) => e,
145        }
146    }
147}
148
149/// An atomic compare-and-swap store backed by an independent,
150/// rollback-resistant head. `load` returns the record together with the
151/// independently anchored head it was read against, or fails closed.
152/// `compare_and_swap` must atomically advance both the durable record and its
153/// independent head, reject stale writers with
154/// [`SecurityJournalStoreErrorV2::Conflict`], and preserve enough history to
155/// recover the anchored head after a crash. A normal file, database
156/// transaction, or checksum chain does not by itself satisfy this contract.
157/// No production backend is provided by this protocol library.
158pub trait SecurityJournalStoreV2: Send + Sync {
159    fn load(&self, ctx: &V2Context) -> V2Result<(SecurityJournalV2, SecurityJournalHeadV2)>;
160    fn compare_and_swap(
161        &self,
162        ctx: &V2Context,
163        expected: &SecurityJournalHeadV2,
164        next: &SecurityJournalV2,
165    ) -> Result<(), SecurityJournalStoreErrorV2>;
166}
167
168/// The only valid genesis record.
169pub fn empty_security_journal_v2() -> SecurityJournalV2 {
170    let mut journal = SecurityJournalV2 {
171        version: SECURITY_JOURNAL_VERSION_V2,
172        ..Default::default()
173    };
174    // Go ignores this error; the genesis snapshot always encodes.
175    journal.digest = security_journal_digest_v2(&journal).unwrap_or_default();
176    journal
177}
178
179/// Go `updateSecurityJournalV2`: one validated journal transition. The
180/// backend's anchored CAS is the serialization point for concurrent callers.
181pub(crate) fn update_security_journal_v2<F>(
182    ctx: &V2Context,
183    store: &dyn SecurityJournalStoreV2,
184    update: F,
185) -> Result<SecurityJournalV2, SecurityJournalStoreErrorV2>
186where
187    F: FnOnce(&mut SecurityJournalV2) -> V2Result<()>,
188{
189    let current = load_anchored_security_journal_v2(ctx, store)?;
190    let mut next = current.clone();
191    update(&mut next)?;
192    commit_security_journal_transition_v2(ctx, store, &current, next)
193}
194
195/// Go `commitSecurityJournalTransitionV2`: compacts and canonicalizes `next`,
196/// returns `current` unchanged when the canonical content is identical
197/// (no-op), and otherwise chains, validates, and commits it by
198/// compare-and-swap against `current`'s head. A conflict is returned, never
199/// retried.
200pub(crate) fn commit_security_journal_transition_v2(
201    ctx: &V2Context,
202    store: &dyn SecurityJournalStoreV2,
203    current: &SecurityJournalV2,
204    mut next: SecurityJournalV2,
205) -> Result<SecurityJournalV2, SecurityJournalStoreErrorV2> {
206    prune_security_journal_observations_v2(&mut next);
207    canonicalize_security_journal_v2(&mut next);
208    if same_security_journal_content_v2(&next, current) {
209        return Ok(current.clone());
210    }
211    next.generation = match current.generation.checked_add(1) {
212        Some(g) if g <= MAX_SAFE as u64 => g,
213        _ => return Err(V2Error::plain("security journal generation exhausted").into()),
214    };
215    next.version = SECURITY_JOURNAL_VERSION_V2;
216    next.previous_digest = current.digest.clone();
217    next.digest = String::new();
218    next.digest = security_journal_digest_v2(&next)?;
219    validate_security_journal_transition_inner(current, &next)
220        .map_err(|e| e.context("invalid security journal transition"))?;
221    let head = SecurityJournalHeadV2 {
222        generation: current.generation,
223        digest: current.digest.clone(),
224    };
225    match store.compare_and_swap(ctx, &head, &next) {
226        Ok(()) => Ok(next),
227        Err(SecurityJournalStoreErrorV2::Conflict) => Err(SecurityJournalStoreErrorV2::Conflict),
228        Err(SecurityJournalStoreErrorV2::Failed(e)) => Err(SecurityJournalStoreErrorV2::Failed(
229            e.context("commit rollback-protected security journal"),
230        )),
231    }
232}
233
234/// Go `loadAnchoredSecurityJournalV2`: loads a version 2 record and requires
235/// it to match the anchored head returned with it.
236pub(crate) fn load_anchored_security_journal_v2(
237    ctx: &V2Context,
238    store: &dyn SecurityJournalStoreV2,
239) -> V2Result<SecurityJournalV2> {
240    let (current, head) = store
241        .load(ctx)
242        .map_err(|e| e.context("load rollback-protected security journal"))?;
243    if head.generation != current.generation
244        || head.digest.is_empty()
245        || head.digest != current.digest
246    {
247        return plain("loaded security journal is not anchored by the store head");
248    }
249    if current.version != SECURITY_JOURNAL_VERSION_V2 {
250        return plain(format!(
251            "security journal version {} requires migration",
252            current.version
253        ));
254    }
255    validate_security_journal_inner(&current)
256        .map_err(|e| e.context("validate loaded security journal"))?;
257    Ok(current)
258}
259
260fn journal_op<T>(r: Result<T, SecurityJournalStoreErrorV2>) -> V2Result<T> {
261    r.map_err(SecurityJournalStoreErrorV2::into_v2)
262        .classify(V2ErrorClass::StatusObjectRejected)
263}
264
265/// Durably add a non-status key role after the caller has authenticated the
266/// trust-configuration event that admits that key.
267pub fn record_security_key_role_v2(
268    ctx: &V2Context,
269    store: &dyn SecurityJournalStoreV2,
270    role: &str,
271    public_key: &HybridPublicKey,
272) -> V2Result<SecurityJournalV2> {
273    if role == "status" {
274        return plain("status keys must be recorded with their issuer and epoch")
275            .classify(V2ErrorClass::StatusObjectRejected);
276    }
277    journal_op(update_security_journal_v2(ctx, store, |journal| {
278        register_key_role_inner(journal, role, public_key)
279    }))
280}
281
282/// Persist an authenticated status-key binding. A first binding starts at
283/// epoch 1; later bindings must advance exactly one epoch and preserve
284/// prior-epoch denials and authenticated evidence.
285pub fn configure_status_key_epoch_v2(
286    ctx: &V2Context,
287    store: &dyn SecurityJournalStoreV2,
288    issuer_id: &str,
289    epoch: u64,
290    public_key: &HybridPublicKey,
291) -> V2Result<SecurityJournalV2> {
292    journal_op(update_security_journal_v2(ctx, store, |journal| {
293        register_status_key_epoch_inner(journal, issuer_id, epoch, public_key)?;
294        if let Some(prior) = journal.status_by_issuer.get(issuer_id) {
295            if epoch == prior.status_key_epoch {
296                return require_journal_status_key_v2(journal, issuer_id, epoch, public_key);
297            }
298            let updated =
299                transition_revocation_status_epoch_v2(prior, issuer_id, epoch, public_key)?;
300            journal
301                .status_by_issuer
302                .insert(issuer_id.to_string(), updated);
303            return Ok(());
304        }
305        if epoch != 1 {
306            return plain("first status-key epoch must be 1");
307        }
308        let key_id = key_id_plain(public_key)?;
309        journal.status_by_issuer.insert(
310            issuer_id.to_string(),
311            RevocationStatusStateV2 {
312                issuer_id: issuer_id.to_string(),
313                status_key_epoch: epoch,
314                status_key_id: key_id,
315                ..Default::default()
316            },
317        );
318        Ok(())
319    }))
320}
321
322/// Authenticate, reduce, and atomically persist a full status snapshot under
323/// the configured issuer key epoch.
324#[allow(clippy::too_many_arguments)]
325pub fn apply_revocation_list_to_journal_v2(
326    ctx: &V2Context,
327    store: &dyn SecurityJournalStoreV2,
328    list: &RevocationListV2,
329    issuer_id: &str,
330    epoch: u64,
331    public_key: &HybridPublicKey,
332    policy: &RevocationStatusPolicyV2,
333    now: i64,
334) -> V2Result<SecurityJournalV2> {
335    journal_op(update_security_journal_v2(ctx, store, |journal| {
336        require_journal_status_key_v2(journal, issuer_id, epoch, public_key)?;
337        let current = journal
338            .status_by_issuer
339            .get(issuer_id)
340            .cloned()
341            .unwrap_or_default();
342        let state =
343            apply_revocation_list_v2(&current, list, issuer_id, epoch, public_key, policy, now)?;
344        journal
345            .status_by_issuer
346            .insert(issuer_id.to_string(), state);
347        Ok(())
348    }))
349}
350
351/// Authenticate, reduce, and atomically persist one push under the
352/// configured issuer key epoch.
353#[allow(clippy::too_many_arguments)]
354pub fn apply_revocation_push_to_journal_v2(
355    ctx: &V2Context,
356    store: &dyn SecurityJournalStoreV2,
357    push: &RevocationPushV2,
358    issuer_id: &str,
359    epoch: u64,
360    public_key: &HybridPublicKey,
361    policy: &RevocationStatusPolicyV2,
362    now: i64,
363) -> V2Result<SecurityJournalV2> {
364    journal_op(update_security_journal_v2(ctx, store, |journal| {
365        require_journal_status_key_v2(journal, issuer_id, epoch, public_key)?;
366        let current = journal
367            .status_by_issuer
368            .get(issuer_id)
369            .cloned()
370            .unwrap_or_default();
371        let state =
372            apply_revocation_push_v2(&current, push, issuer_id, epoch, public_key, policy, now)?;
373        journal
374            .status_by_issuer
375            .insert(issuer_id.to_string(), state);
376        Ok(())
377    }))
378}
379
380/// Read an anchored state and return a fail-closed status decision for one
381/// issuer-scoped certificate reference. Go also returns an
382/// indeterminate/unavailable result alongside an error; this port returns
383/// only the error.
384#[allow(clippy::too_many_arguments)]
385pub fn revocation_status_from_journal_v2(
386    ctx: &V2Context,
387    store: &dyn SecurityJournalStoreV2,
388    issuer_id: &str,
389    cert_id: &str,
390    epoch: u64,
391    public_key: &HybridPublicKey,
392    policy: &RevocationStatusPolicyV2,
393    now: i64,
394) -> V2Result<RevocationStatusResultV2> {
395    (|| {
396        let journal = load_anchored_security_journal_v2(ctx, store)?;
397        require_journal_status_key_v2(&journal, issuer_id, epoch, public_key)?;
398        let state = journal
399            .status_by_issuer
400            .get(issuer_id)
401            .cloned()
402            .unwrap_or_default();
403        revocation_status_for_cert_inner(&state, issuer_id, cert_id, epoch, public_key, policy, now)
404    })()
405    .classify(V2ErrorClass::ConfigurationInvalid)
406}
407
408pub(crate) fn require_journal_status_key_v2(
409    journal: &SecurityJournalV2,
410    issuer_id: &str,
411    epoch: u64,
412    public_key: &HybridPublicKey,
413) -> V2Result<()> {
414    if issuer_id.is_empty() || epoch == 0 {
415        return plain("issuer and status-key epoch are required");
416    }
417    let Some(binding) = status_binding_at_epoch(&journal.status_key_history, issuer_id, epoch)
418    else {
419        return plain("issuer status key is not present in the retained trust history");
420    };
421    let actual = status_key_binding_v2(issuer_id, epoch, public_key)?;
422    if *binding != actual {
423        return plain("status key does not match the retained issuer and epoch binding");
424    }
425    match journal.status_by_issuer.get(issuer_id) {
426        Some(state)
427            if state.status_key_epoch == epoch && state.status_key_id == binding.status_key_id =>
428        {
429            Ok(())
430        }
431        _ => plain("status key is not the current issuer epoch"),
432    }
433}
434
435/// Validate record integrity and internal indexes (class `malformed`).
436pub fn validate_security_journal_v2(journal: &SecurityJournalV2) -> V2Result<()> {
437    validate_security_journal_inner(journal).classify(V2ErrorClass::Malformed)
438}
439
440/// Go `ValidateSecurityJournalV2` with Go's (unclassified) error classes.
441pub(crate) fn validate_security_journal_inner(journal: &SecurityJournalV2) -> V2Result<()> {
442    let nil = |member: &str| journal.legacy_null_members.contains(member);
443    if (journal.version != SECURITY_JOURNAL_VERSION_V2
444        && journal.version != SECURITY_JOURNAL_LEGACY_VERSION)
445        || nil("status_by_issuer")
446        || nil("key_role_history")
447        || nil("status_key_history")
448    {
449        return plain("security journal has unsupported or incomplete shape");
450    }
451    if journal.generation == 0 && !journal.previous_digest.is_empty() {
452        return plain("security journal genesis has a predecessor");
453    }
454    if journal.generation == 0
455        && (!journal.status_by_issuer.is_empty()
456            || !journal.key_role_history.is_empty()
457            || !journal.status_key_history.is_empty())
458    {
459        return plain("security journal genesis must be empty");
460    }
461    if journal.generation > 0
462        && (journal.previous_digest.is_empty() || journal.previous_digest.len() != 96)
463    {
464        return plain("security journal record is missing its predecessor digest");
465    }
466    let digest = security_journal_digest_v2(journal)?;
467    if journal.digest != digest {
468        return plain("security journal digest mismatch");
469    }
470    for (issuer_id, state) in &journal.status_by_issuer {
471        if issuer_id.is_empty() || state.issuer_id != *issuer_id || state.status_key_epoch == 0 {
472            return plain("security journal contains a misbound issuer status state");
473        }
474        validate_binding(state, issuer_id, state.status_key_epoch)
475            .map_err(|e| e.context(format!("invalid status state for issuer {issuer_id:?}")))?;
476        validate_accepted_state(state).map_err(|e| {
477            e.context(format!(
478                "invalid accepted status state for issuer {issuer_id:?}"
479            ))
480        })?;
481        match status_binding_at_epoch(
482            &journal.status_key_history,
483            issuer_id,
484            state.status_key_epoch,
485        ) {
486            Some(binding) if binding.status_key_id == state.status_key_id => {}
487            _ => return plain("current status state has no matching retained key binding"),
488        }
489        let mut max_observed = 0i64;
490        let retired: Vec<String> = journal
491            .status_key_history
492            .iter()
493            .filter(|b| b.issuer_id == *issuer_id && b.epoch < state.status_key_epoch)
494            .map(|b| b.status_key_id.clone())
495            .collect();
496        for o in &state.observations {
497            let bound =
498                status_binding_at_epoch(&journal.status_key_history, issuer_id, o.status_key_epoch);
499            if bound.is_none_or(|b| o.status_key_id != b.status_key_id)
500                || o.sequence <= 0
501                || o.sequence > MAX_SAFE
502                || o.evidence_digest.len() != 48
503                || o.body_digest.len() != 48
504                || (o.object_type != LIST && o.object_type != PUSH)
505            {
506                return plain("security journal contains malformed or misbound status evidence");
507            }
508            if o.status_key_epoch == state.status_key_epoch && o.sequence > max_observed {
509                max_observed = o.sequence;
510            }
511        }
512        if state.max_observed_sequence != max_observed
513            || !equal_sets(&state.retired_status_key_ids, &retired)
514        {
515            return plain("status state does not match retained sequence and key history");
516        }
517    }
518    validate_key_role_history(&journal.key_role_history)?;
519    validate_status_key_history(&journal.status_key_history, &journal.key_role_history)?;
520    let mut latest: BTreeMap<&str, u64> = BTreeMap::new();
521    for b in &journal.status_key_history {
522        let entry = latest.entry(b.issuer_id.as_str()).or_insert(0);
523        if b.epoch > *entry {
524            *entry = b.epoch;
525        }
526    }
527    for (issuer_id, epoch) in latest {
528        match journal.status_by_issuer.get(issuer_id) {
529            Some(state) if state.status_key_epoch == epoch => {}
530            _ => {
531                return plain(
532                    "security journal status state is not at the latest retained issuer epoch",
533                )
534            }
535        }
536    }
537    Ok(())
538}
539
540/// Enforce generation continuity and append-only key histories. An invalid
541/// record is `malformed`; an invalid transition between valid records is
542/// `status_object_rejected`. Status-state evolution itself is performed by
543/// the reducer and the epoch transition before this validation.
544pub fn validate_security_journal_transition_v2(
545    current: &SecurityJournalV2,
546    next: &SecurityJournalV2,
547) -> V2Result<()> {
548    validate_security_journal_v2(current).map_err(|e| e.context("invalid current journal"))?;
549    validate_security_journal_v2(next).map_err(|e| e.context("invalid next journal"))?;
550    validate_security_journal_transition_inner(current, next)
551        .classify(V2ErrorClass::StatusObjectRejected)
552}
553
554/// Go `ValidateSecurityJournalTransitionV2` with Go's (unclassified) classes.
555pub(crate) fn validate_security_journal_transition_inner(
556    current: &SecurityJournalV2,
557    next: &SecurityJournalV2,
558) -> V2Result<()> {
559    validate_security_journal_inner(current).map_err(|e| e.context("invalid current journal"))?;
560    validate_security_journal_inner(next).map_err(|e| e.context("invalid next journal"))?;
561    if current.generation.checked_add(1) != Some(next.generation)
562        || next.previous_digest != current.digest
563    {
564        return plain("journal generation or predecessor is not contiguous");
565    }
566    if next.version != SECURITY_JOURNAL_VERSION_V2 {
567        return plain(format!(
568            "journal transitions must produce a version {SECURITY_JOURNAL_VERSION_V2} record"
569        ));
570    }
571    if current.version == SECURITY_JOURNAL_LEGACY_VERSION
572        && !same_security_journal_content_v2(current, next)
573    {
574        return plain("journal migration must not change logical content");
575    }
576    if !current
577        .key_role_history
578        .iter()
579        .all(|b| next.key_role_history.contains(b))
580        || !current
581            .status_key_history
582            .iter()
583            .all(|b| next.status_key_history.contains(b))
584    {
585        return plain("journal key binding history was removed or rewritten");
586    }
587    for (issuer_id, state) in &current.status_by_issuer {
588        let Some(next_state) = next.status_by_issuer.get(issuer_id) else {
589            return plain("journal transition removed issuer status or a retained revocation");
590        };
591        if !contains_all(&next_state.deny_union_cert_ids, &state.deny_union_cert_ids) {
592            return plain("journal transition removed issuer status or a retained revocation");
593        }
594        for old in &state.observations {
595            // Go keys observations by their complete JSON encoding.
596            if next_state.observations.contains(old) {
597                continue;
598            }
599            if !must_retain(next_state, old) {
600                continue;
601            }
602            // Go keeps the last observation per semantic key.
603            let key = semantic_key(old);
604            let compacted = next_state
605                .observations
606                .iter()
607                .rev()
608                .find(|o| semantic_key(o) == key);
609            let lost = match compacted {
610                None => true,
611                Some(c) => {
612                    !contains_all(&c.revoked_cert_ids, &old.revoked_cert_ids)
613                        || (old.fork && !c.fork)
614                        || (old.gap && next_state.reconciliation_required && !c.gap)
615                        || (old.future_dated
616                            && next_state.future_dated_object_observed
617                            && !c.future_dated)
618                }
619            };
620            if lost {
621                return plain("journal transition removed authenticated status evidence");
622            }
623        }
624        if next_state.status_key_epoch < state.status_key_epoch {
625            return plain("journal transition rolled back a status-key epoch");
626        }
627        if next_state.status_key_epoch > state.status_key_epoch {
628            let mut retired = state.retired_status_key_ids.clone();
629            retired.push(state.status_key_id.clone());
630            if next_state.status_key_id == state.status_key_id
631                || state
632                    .retired_status_key_ids
633                    .contains(&next_state.status_key_id)
634                || !equal_sets(&next_state.retired_status_key_ids, &retired)
635                || next_state.has_floor
636                || next_state.floor != 0
637                || next_state.accepted_snapshot.is_some()
638                || !next_state.accepted_cert_ids.is_empty()
639                || next_state.has_preceding_checkpoint
640                || next_state.preceding_floor != 0
641                || !next_state.preceding_accepted_cert_ids.is_empty()
642                || next_state.max_observed_sequence != 0
643                || next_state.fork_sequence != 0
644                || next_state.reconciliation_required
645                || next_state.future_dated_object_observed
646            {
647                return plain(
648                    "status-key epoch transition did not perform the required fail-closed reset",
649                );
650            }
651            if next_state
652                .observations
653                .iter()
654                .any(|o| o.status_key_epoch >= next_state.status_key_epoch)
655            {
656                return plain(
657                    "status-key epoch transition contains evidence from the new epoch before bootstrap",
658                );
659            }
660        }
661        if next_state.status_key_epoch == state.status_key_epoch
662            && state.has_floor
663            && (!next_state.has_floor || next_state.floor < state.floor)
664        {
665            return plain("journal transition rolled back the accepted status floor");
666        }
667        if next_state.status_key_epoch == state.status_key_epoch
668            && next_state.max_observed_sequence < state.max_observed_sequence
669        {
670            return plain("journal transition rolled back the observed status sequence");
671        }
672        if next_state.status_key_epoch == state.status_key_epoch
673            && state.reconciliation_required
674            && !next_state.reconciliation_required
675            && (!has_accepted_snapshot_after(
676                next_state,
677                state.status_key_epoch,
678                state.max_observed_sequence,
679                state.fork_sequence,
680                &state.deny_union_cert_ids,
681            ) || !contains_all(&next_state.accepted_cert_ids, &state.deny_union_cert_ids))
682        {
683            return plain(
684                "journal transition cleared reconciliation without a caught-up full snapshot",
685            );
686        }
687    }
688    for (issuer_id, state) in &next.status_by_issuer {
689        if !current.status_by_issuer.contains_key(issuer_id)
690            && status_binding_at_epoch(&next.status_key_history, issuer_id, state.status_key_epoch)
691                .is_none()
692        {
693            return plain("new issuer status state lacks authenticated key history");
694        }
695    }
696    Ok(())
697}
698
699fn has_accepted_snapshot_after(
700    state: &RevocationStatusStateV2,
701    epoch: u64,
702    min_sequence: i64,
703    fork_sequence: i64,
704    deny_union: &[String],
705) -> bool {
706    state.observations.iter().any(|o| {
707        o.status_key_epoch == epoch
708            && o.object_type == LIST
709            && o.accepted
710            && o.sequence >= min_sequence
711            && (fork_sequence == 0 || o.sequence > fork_sequence)
712            && contains_all(&o.revoked_cert_ids, deny_union)
713    })
714}
715
716/// Go `pruneSecurityJournalObservationsV2` over every issuer state.
717pub(crate) fn prune_security_journal_observations_v2(journal: &mut SecurityJournalV2) {
718    for state in journal.status_by_issuer.values_mut() {
719        *state = compact(std::mem::take(state));
720    }
721}
722
723/// Go `canonicalizeSecurityJournalV2`: every set and history in snapshot
724/// order. Observation order is compaction order and is not changed here.
725pub(crate) fn canonicalize_security_journal_v2(journal: &mut SecurityJournalV2) {
726    sort_key_role_history(&mut journal.key_role_history);
727    sort_status_key_history(&mut journal.status_key_history);
728    for state in journal.status_by_issuer.values_mut() {
729        *state = canonicalize_state(std::mem::take(state));
730    }
731}
732
733/// Record a permanent global role assignment. Repeating the identical
734/// assignment is idempotent; any key-ID or component reuse is denied (class
735/// `status_object_rejected`).
736pub fn register_key_role_v2(
737    journal: &mut SecurityJournalV2,
738    role: &str,
739    public_key: &HybridPublicKey,
740) -> V2Result<()> {
741    register_key_role_inner(journal, role, public_key).classify(V2ErrorClass::StatusObjectRejected)
742}
743
744fn register_key_role_inner(
745    journal: &mut SecurityJournalV2,
746    role: &str,
747    public_key: &HybridPublicKey,
748) -> V2Result<()> {
749    if !valid_security_key_role(role) || role == "status" {
750        return plain("security key role is invalid");
751    }
752    register_any_key_role(journal, role, public_key)
753}
754
755fn register_any_key_role(
756    journal: &mut SecurityJournalV2,
757    role: &str,
758    public_key: &HybridPublicKey,
759) -> V2Result<()> {
760    let binding = key_role_binding_v2(role, public_key)?;
761    for existing in &journal.key_role_history {
762        if *existing == binding {
763            return Ok(());
764        }
765        if existing.key_id == binding.key_id
766            || existing.ed25519_digest == binding.ed25519_digest
767            || existing.ml_dsa_65_digest == binding.ml_dsa_65_digest
768            || existing.ed25519_digest == binding.ml_dsa_65_digest
769            || existing.ml_dsa_65_digest == binding.ed25519_digest
770        {
771            return plain(format!(
772                "hybrid key ID or component is already permanently assigned to role {:?}",
773                existing.role
774            ));
775        }
776    }
777    journal.key_role_history.push(binding);
778    sort_key_role_history(&mut journal.key_role_history);
779    Ok(())
780}
781
782/// Record caller-authenticated status-key history and the corresponding
783/// permanent global status role before status objects apply (class
784/// `status_object_rejected`).
785pub fn register_status_key_epoch_v2(
786    journal: &mut SecurityJournalV2,
787    issuer_id: &str,
788    epoch: u64,
789    public_key: &HybridPublicKey,
790) -> V2Result<()> {
791    register_status_key_epoch_inner(journal, issuer_id, epoch, public_key)
792        .classify(V2ErrorClass::StatusObjectRejected)
793}
794
795fn register_status_key_epoch_inner(
796    journal: &mut SecurityJournalV2,
797    issuer_id: &str,
798    epoch: u64,
799    public_key: &HybridPublicKey,
800) -> V2Result<()> {
801    if issuer_id.is_empty() || epoch == 0 || epoch > MAX_SAFE as u64 {
802        return plain("status-key binding has invalid issuer or epoch");
803    }
804    let binding = status_key_binding_v2(issuer_id, epoch, public_key)?;
805    for existing in &journal.status_key_history {
806        if existing.issuer_id == issuer_id && existing.epoch == epoch {
807            if *existing == binding {
808                return Ok(());
809            }
810            return plain("status-key epoch is permanently bound to a different key");
811        }
812        if existing.status_key_id == binding.status_key_id
813            || existing.ed25519_digest == binding.ed25519_digest
814            || existing.ml_dsa_65_digest == binding.ml_dsa_65_digest
815        {
816            return plain("status key was previously bound in this deployment");
817        }
818    }
819    let highest = journal
820        .status_key_history
821        .iter()
822        .filter(|b| b.issuer_id == issuer_id)
823        .map(|b| b.epoch)
824        .max()
825        .unwrap_or(0);
826    if Some(epoch) != highest.checked_add(1) {
827        return plain("status-key epoch must advance by one from retained issuer history");
828    }
829    register_any_key_role(journal, "status", public_key)?;
830    journal.status_key_history.push(binding);
831    sort_status_key_history(&mut journal.status_key_history);
832    Ok(())
833}
834
835/// Go `keyRoleBindingV2`: the key ID and SHA-384 component digests.
836pub(crate) fn key_role_binding_v2(
837    role: &str,
838    public_key: &HybridPublicKey,
839) -> V2Result<KeyRoleBindingV2> {
840    let key_id = key_id_plain(public_key)?;
841    Ok(KeyRoleBindingV2 {
842        key_id,
843        ed25519_digest: hex::encode(sha384(&[&public_key.ed25519])),
844        ml_dsa_65_digest: hex::encode(sha384(&[&public_key.ml_dsa_65])),
845        role: role.to_string(),
846    })
847}
848
849fn status_key_binding_v2(
850    issuer_id: &str,
851    epoch: u64,
852    public_key: &HybridPublicKey,
853) -> V2Result<StatusKeyBindingV2> {
854    let role = key_role_binding_v2("status", public_key)?;
855    Ok(StatusKeyBindingV2 {
856        issuer_id: issuer_id.to_string(),
857        epoch,
858        status_key_id: role.key_id,
859        ed25519_digest: role.ed25519_digest,
860        ml_dsa_65_digest: role.ml_dsa_65_digest,
861    })
862}
863
864fn validate_key_role_history(history: &[KeyRoleBindingV2]) -> V2Result<()> {
865    let mut ids: BTreeMap<&str, &KeyRoleBindingV2> = BTreeMap::new();
866    let mut components: BTreeMap<&str, &KeyRoleBindingV2> = BTreeMap::new();
867    for b in history {
868        if b.key_id.is_empty()
869            || !valid_security_key_role(&b.role)
870            || !valid_digest_hex(&b.ed25519_digest)
871            || !valid_digest_hex(&b.ml_dsa_65_digest)
872        {
873            return plain("security journal contains malformed key-role history");
874        }
875        if ids.get(b.key_id.as_str()).is_some_and(|prior| *prior != b) {
876            return plain("security journal reuses a key ID across roles");
877        }
878        ids.insert(&b.key_id, b);
879        for component in [b.ed25519_digest.as_str(), b.ml_dsa_65_digest.as_str()] {
880            if components.get(component).is_some_and(|prior| *prior != b) {
881                return plain("security journal reuses key material across roles");
882            }
883            components.insert(component, b);
884        }
885    }
886    Ok(())
887}
888
889fn validate_status_key_history(
890    history: &[StatusKeyBindingV2],
891    roles: &[KeyRoleBindingV2],
892) -> V2Result<()> {
893    let mut last_epoch: BTreeMap<&str, u64> = BTreeMap::new();
894    let mut ids: BTreeSet<&str> = BTreeSet::new();
895    let mut components: BTreeSet<&str> = BTreeSet::new();
896    for b in history {
897        if b.issuer_id.is_empty()
898            || b.epoch == 0
899            || b.status_key_id.is_empty()
900            || !valid_digest_hex(&b.ed25519_digest)
901            || !valid_digest_hex(&b.ml_dsa_65_digest)
902        {
903            return plain("security journal contains malformed status-key history");
904        }
905        let last = last_epoch.get(b.issuer_id.as_str()).copied().unwrap_or(0);
906        if last.checked_add(1) != Some(b.epoch) {
907            return plain("security journal status-key epochs are missing or out of order");
908        }
909        last_epoch.insert(&b.issuer_id, b.epoch);
910        let role = roles.iter().find(|r| {
911            r.key_id == b.status_key_id
912                && r.ed25519_digest == b.ed25519_digest
913                && r.ml_dsa_65_digest == b.ml_dsa_65_digest
914        });
915        if role.is_none_or(|r| r.role != "status") {
916            return plain("status-key history lacks its global status role assignment");
917        }
918        if !ids.insert(&b.status_key_id) {
919            return plain("security journal reuses a status key ID");
920        }
921        for component in [b.ed25519_digest.as_str(), b.ml_dsa_65_digest.as_str()] {
922            if !components.insert(component) {
923                return plain("security journal reuses a status-key component");
924            }
925        }
926    }
927    Ok(())
928}
929
930pub(crate) fn status_binding_at_epoch<'a>(
931    history: &'a [StatusKeyBindingV2],
932    issuer_id: &str,
933    epoch: u64,
934) -> Option<&'a StatusKeyBindingV2> {
935    history
936        .iter()
937        .find(|b| b.issuer_id == issuer_id && b.epoch == epoch)
938}
939
940fn valid_security_key_role(role: &str) -> bool {
941    matches!(
942        role,
943        "status"
944            | "delegation"
945            | "rotation"
946            | "verifier"
947            | "witness"
948            | "receiver"
949            | "issuer"
950            | "other"
951    )
952}
953
954fn valid_digest_hex(value: &str) -> bool {
955    hex::decode(value).is_ok_and(|d| d.len() == 48 && hex::encode(&d) == value)
956}
957
958pub(crate) fn sort_key_role_history(history: &mut [KeyRoleBindingV2]) {
959    history.sort_by(|a, b| (&a.key_id, &a.role).cmp(&(&b.key_id, &b.role)));
960}
961
962pub(crate) fn sort_status_key_history(history: &mut [StatusKeyBindingV2]) {
963    history.sort_by(|a, b| (&a.issuer_id, a.epoch).cmp(&(&b.issuer_id, b.epoch)));
964}