Skip to main content

hyprstream_rpc/
session_pq_overlay.rs

1//! Session-scoped PQ binding overlay: trust-on-first-use continuity for
2//! browser and other dynamically-identified clients, with out-of-band
3//! promotion.
4//!
5//! # Why this exists
6//!
7//! [`crate::envelope::KeyedPqTrustStore`] is admin-anchored and immutable after
8//! install: an operator enrolls each peer's ML-DSA-65 key out of band. A
9//! browser's Ed25519 identity is user/device-generated, so no operator can
10//! pre-enroll it, and under the mandatory Hybrid suite an unanchored identity
11//! cannot have its signature checked at all — the request is dropped.
12//!
13//! This overlay is the additive answer. It is consulted by the envelope verify
14//! path *after* the admin-anchored store misses, and it **never mutates that
15//! store**: its entries are established out of band by contract, and the
16//! federation perimeter deliberately leaves it untouched. Consult-then-fall-
17//! back, never write-through.
18//!
19//! # The load-bearing property
20//!
21//! A [`PqProvenance::TofuBound`] entry makes a signature **verifiable** without
22//! making the signer **more trusted**. Those are two different questions and
23//! this module answers them through two different methods that share no return
24//! type:
25//!
26//! - [`SessionPqOverlay::verifying_key_for`] — verifiability. Returns a key and
27//!   nothing else, so the verify path structurally cannot learn provenance from
28//!   it and therefore cannot launder it into an assurance decision.
29//! - [`SessionPqOverlay::provenance_for`] — trust. The MAC assurance seam reads
30//!   this, and [`PqProvenance::key_material`] refuses to map `TofuBound` to
31//!   anything above `Classical`.
32//!
33//! # What a composite has to prove before anything is recorded
34//!
35//! The nested composite binds inner→outer — the outer ML-DSA-65 layer signs
36//! `payload ‖ inner_signature` — and **not** outer→inner. So a composite that
37//! verifies proves possession of the ML-DSA-65 key plus possession of one
38//! Ed25519 *signature*, which is not the same as possession of the Ed25519
39//! *private key*: anyone holding a copy of a valid inner layer can drop the
40//! outer, re-sign with an ML-DSA key of their own, and produce a composite that
41//! verifies under the captured identity.
42//!
43//! That is survivable while the PQ key is always resolved from a trust store,
44//! and fatal the moment it is recorded. So a binding is established only from a
45//! composite whose inner EdDSA layer *commits* to the key above it
46//! ([`crate::crypto::cose_sign::PQ_BINDING_HEADER_LABEL`]) — a commitment that
47//! lives inside the Ed25519 signature. An uncommitted composite still verifies;
48//! it just cannot establish a binding.
49//!
50//! # Rebinding is loud by construction
51//!
52//! TOFU's security value is change detection, not initial trust. A silent
53//! last-write-wins rebind voids every guarantee here, so the API offers no way
54//! to perform one:
55//!
56//! - [`SessionPqOverlay::observe_first_contact`] inserts into a **vacant** slot
57//!   only. An occupied slot naming a different key yields
58//!   [`FirstContactOutcome::RebindRefused`], and the [`RebindEvent`] is
59//!   published to the event sink *before* that value is returned, so a caller
60//!   that discards the return value has still surfaced the event.
61//! - The only way to change an established binding is
62//!   [`SessionPqOverlay::apply_rebind`], which takes a [`RebindApproval`]. A
63//!   `RebindApproval` can only be built by consuming a `RebindEvent`, which
64//!   only the overlay can mint, and only by refusing a rebind. Legitimate key
65//!   rotation therefore travels the same visible path as an attack.
66//!
67//! # Promotion and revocation
68//!
69//! Promotion to [`PqProvenance::OobVerified`] requires presenting the
70//! [`composite_fingerprint`] — a hash over `ed25519 ‖ ml_dsa_65`, covering the
71//! *pair*, because fingerprinting the PQ half alone confirms possession of a
72//! key without binding it to the identity it claims to belong to. The value
73//! must have been obtained through a channel with different compromise
74//! assumptions from the one being bootstrapped; this module verifies the value
75//! matches, and cannot verify where the operator got it.
76//!
77//! `TofuBound` entries expire with the session. An `OobVerified` promotion
78//! outlives one, so it has an explicit revocation path
79//! ([`SessionPqOverlay::revoke_promotion`],
80//! [`SessionPqOverlay::revoke_binding`]) — an irreversible promotion would be
81//! worse than no promotion.
82
83use std::collections::HashMap;
84use std::sync::Arc;
85
86use parking_lot::RwLock;
87
88use crate::auth::mac::{Assurance, VerifiedKeyMaterial};
89use crate::crypto::pq::{ml_dsa_vk_bytes, MlDsaVerifyingKey};
90
91/// Domain separation tag for the composite fingerprint.
92const FINGERPRINT_DOMAIN: &[u8] = b"hyprstream/pq-composite-fingerprint/v1";
93
94/// Default lifetime of a first-contact binding. It is session continuity, not
95/// enrollment: it lapses so that a device that stops appearing stops being
96/// remembered.
97pub const DEFAULT_TOFU_TTL_MS: i64 = 12 * 60 * 60 * 1000;
98
99/// Default ceiling on retained bindings.
100///
101/// Recording costs an attacker only a self-minted Ed25519 + ML-DSA-65 keypair —
102/// no enrollment, no credential, no prior relationship — and the verify path
103/// runs before authorization, so an unbounded map is a memory-exhaustion
104/// surface. At the ceiling the least-recently-seen first-contact entry is
105/// evicted rather than the new one refused; see
106/// [`SessionPqOverlay::observe_first_contact`] for why refusing is the worse
107/// failure. Promoted bindings are never evicted.
108pub const DEFAULT_MAX_ENTRIES: usize = 4096;
109
110/// How a PQ verifying key came to be associated with an Ed25519 identity.
111///
112/// The absence of an entry is the third state of the model — `Classical`, no PQ
113/// key bound — and is deliberately not a variant here: it is not something the
114/// overlay records.
115#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
116pub enum PqProvenance {
117    /// Recorded at first contact, over a channel authenticated only
118    /// classically. Proves the client held both private keys at that moment
119    /// and nothing more. Sufficient to check a signature; insufficient to
120    /// believe the signer any harder than a classical one.
121    TofuBound,
122    /// Confirmed through a channel with different compromise assumptions than
123    /// the one being bootstrapped — an operator-published deployment
124    /// fingerprint, or an already-authenticated session on another device.
125    OobVerified,
126}
127
128impl PqProvenance {
129    /// The verified key material this provenance supports.
130    ///
131    /// This is the single point where a binding is allowed to influence
132    /// assurance, and the only mapping that reaches
133    /// [`VerifiedKeyMaterial::PqHybrid`] is [`PqProvenance::OobVerified`].
134    #[must_use]
135    pub fn key_material(self) -> VerifiedKeyMaterial {
136        match self {
137            // Capped. A first-contact record is continuity, not an anchor.
138            PqProvenance::TofuBound => VerifiedKeyMaterial::Classical,
139            PqProvenance::OobVerified => VerifiedKeyMaterial::PqHybrid,
140        }
141    }
142
143    /// The highest MAC assurance this provenance can support.
144    #[must_use]
145    pub fn assurance_ceiling(self) -> Assurance {
146        self.key_material().assurance()
147    }
148
149    /// Stable label for logs and audit records.
150    #[must_use]
151    pub fn as_str(self) -> &'static str {
152        match self {
153            PqProvenance::TofuBound => "tofu-bound",
154            PqProvenance::OobVerified => "oob-verified",
155        }
156    }
157}
158
159/// A recorded binding.
160#[derive(Debug, Clone)]
161struct OverlayEntry {
162    ml_dsa_vk: Vec<u8>,
163    provenance: PqProvenance,
164    /// Wall-clock ms after which the entry is treated as absent. `None` for a
165    /// promoted binding, which outlives the session that created it and is
166    /// withdrawn by revocation rather than by lapse.
167    expires_at_ms: Option<i64>,
168    /// Monotonically increasing stamp of the last contact that touched this
169    /// entry. Orders eviction when the table is full.
170    last_seen_seq: u64,
171}
172
173impl OverlayEntry {
174    fn is_live(&self, now_ms: i64) -> bool {
175        match self.expires_at_ms {
176            Some(deadline) => now_ms < deadline,
177            None => true,
178        }
179    }
180}
181
182/// A surfaced attempt to bind an already-bound identity to a different PQ key.
183///
184/// Minted only by [`SessionPqOverlay::observe_first_contact`] refusing a
185/// rebind. It is the sole input to [`RebindApproval`], which makes "change an
186/// established binding" unreachable without an event having been raised first.
187#[derive(Debug, Clone)]
188#[must_use = "a refused rebind is a security event; record it or approve it deliberately"]
189pub struct RebindEvent {
190    identity: [u8; 32],
191    established_vk: Vec<u8>,
192    established_provenance: PqProvenance,
193    presented_vk: Vec<u8>,
194}
195
196impl RebindEvent {
197    /// The Ed25519 identity whose binding was challenged.
198    #[must_use]
199    pub fn identity(&self) -> &[u8; 32] {
200        &self.identity
201    }
202
203    /// Provenance of the binding already on file.
204    #[must_use]
205    pub fn established_provenance(&self) -> PqProvenance {
206        self.established_provenance
207    }
208
209    /// Fingerprint of the pairing already on file.
210    #[must_use]
211    pub fn established_fingerprint(&self) -> [u8; 32] {
212        fingerprint_bytes(&self.identity, &self.established_vk)
213    }
214
215    /// Fingerprint of the pairing that was presented and refused.
216    #[must_use]
217    pub fn presented_fingerprint(&self) -> [u8; 32] {
218        fingerprint_bytes(&self.identity, &self.presented_vk)
219    }
220
221    /// Turn this surfaced event into an approval to replace the binding.
222    ///
223    /// Consumes the event: an approval cannot exist unless a rebind was
224    /// refused first. `justification` is carried into the applied-rebind
225    /// notification so the record says who decided and on what basis.
226    #[must_use]
227    pub fn approve(
228        self,
229        provenance: PqProvenance,
230        justification: impl Into<String>,
231    ) -> RebindApproval {
232        RebindApproval {
233            event: self,
234            provenance,
235            justification: justification.into(),
236        }
237    }
238}
239
240/// An operator decision to replace an established binding, carrying the event
241/// it answers.
242#[derive(Debug, Clone)]
243pub struct RebindApproval {
244    event: RebindEvent,
245    provenance: PqProvenance,
246    justification: String,
247}
248
249impl RebindApproval {
250    /// The event this approval answers.
251    pub fn event(&self) -> &RebindEvent {
252        &self.event
253    }
254
255    /// The provenance the replacement binding will carry.
256    #[must_use]
257    pub fn provenance(&self) -> PqProvenance {
258        self.provenance
259    }
260}
261
262/// Outcome of offering a first-contact observation.
263#[derive(Debug, Clone)]
264#[must_use]
265pub enum FirstContactOutcome {
266    /// No live binding existed; the presented key is now recorded `TofuBound`.
267    Recorded,
268    /// A live binding exists and names the same key. Nothing changed.
269    AlreadyBound(PqProvenance),
270    /// A live binding exists and names a *different* key. **Not applied.**
271    RebindRefused(RebindEvent),
272    /// The overlay is at capacity and no expired entry could be reclaimed. The
273    /// binding was not recorded; the request that offered it fails closed.
274    CapacityExhausted,
275}
276
277/// Why a promotion was refused.
278#[derive(Debug, Clone, PartialEq, Eq)]
279pub enum PromotionError {
280    /// No live binding exists for the identity — there is nothing to promote.
281    /// Promotion never creates a binding: the out-of-band channel confirms a
282    /// pairing the node already observed, it does not introduce one.
283    NotBound,
284    /// The out-of-band fingerprint does not match the recorded pairing.
285    FingerprintMismatch,
286}
287
288impl std::fmt::Display for PromotionError {
289    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
290        match self {
291            PromotionError::NotBound => f.write_str("no live PQ binding for this identity"),
292            PromotionError::FingerprintMismatch => {
293                f.write_str("out-of-band fingerprint does not match the recorded pairing")
294            }
295        }
296    }
297}
298
299impl std::error::Error for PromotionError {}
300
301/// Sink for binding lifecycle events.
302///
303/// Every method has a default no-op body except the two that report a change of
304/// trust state; implementors are expected to route those to the audit journal.
305pub trait PqBindingEventSink: Send + Sync {
306    /// An identity presented a PQ key different from its established binding.
307    /// The binding was left alone.
308    fn on_rebind_refused(&self, event: &RebindEvent);
309
310    /// An established binding was replaced under an explicit approval.
311    fn on_rebind_applied(&self, approval: &RebindApproval);
312
313    /// A first-contact binding was recorded.
314    fn on_first_contact(&self, _identity: &[u8; 32], _fingerprint: &[u8; 32]) {}
315
316    /// A binding was promoted to `OobVerified`.
317    fn on_promoted(&self, _identity: &[u8; 32], _fingerprint: &[u8; 32], _channel: &str) {}
318
319    /// A promotion or a whole binding was withdrawn.
320    fn on_revoked(&self, _identity: &[u8; 32], _from: PqProvenance, _to: Option<PqProvenance>) {}
321
322    /// A first-contact binding was evicted to make room. The identity loses
323    /// change detection until it is seen again.
324    fn on_evicted(&self, _identity: &[u8; 32]) {}
325}
326
327/// Sink that records events to `tracing` at warning level.
328pub struct TracingPqBindingEventSink;
329
330impl PqBindingEventSink for TracingPqBindingEventSink {
331    fn on_rebind_refused(&self, event: &RebindEvent) {
332        tracing::warn!(
333            identity = %hex::encode(event.identity()),
334            established_provenance = event.established_provenance().as_str(),
335            established_fingerprint = %hex::encode(event.established_fingerprint()),
336            presented_fingerprint = %hex::encode(event.presented_fingerprint()),
337            "PQ rebinding refused: identity presented a different ML-DSA-65 key than its \
338             established binding; the binding was NOT changed"
339        );
340    }
341
342    fn on_rebind_applied(&self, approval: &RebindApproval) {
343        tracing::warn!(
344            identity = %hex::encode(approval.event().identity()),
345            from_fingerprint = %hex::encode(approval.event().established_fingerprint()),
346            to_fingerprint = %hex::encode(approval.event().presented_fingerprint()),
347            provenance = approval.provenance().as_str(),
348            justification = %approval.justification,
349            "PQ binding replaced under explicit approval"
350        );
351    }
352
353    fn on_first_contact(&self, identity: &[u8; 32], fingerprint: &[u8; 32]) {
354        tracing::info!(
355            identity = %hex::encode(identity),
356            fingerprint = %hex::encode(fingerprint),
357            "PQ binding recorded at first contact (verifiable, assurance capped at Classical)"
358        );
359    }
360
361    fn on_promoted(&self, identity: &[u8; 32], fingerprint: &[u8; 32], channel: &str) {
362        tracing::warn!(
363            identity = %hex::encode(identity),
364            fingerprint = %hex::encode(fingerprint),
365            channel,
366            "PQ binding promoted to out-of-band verified"
367        );
368    }
369
370    fn on_revoked(&self, identity: &[u8; 32], from: PqProvenance, to: Option<PqProvenance>) {
371        tracing::warn!(
372            identity = %hex::encode(identity),
373            from = from.as_str(),
374            to = to.map_or("none", PqProvenance::as_str),
375            "PQ binding withdrawn"
376        );
377    }
378
379    fn on_evicted(&self, identity: &[u8; 32]) {
380        tracing::warn!(
381            identity = %hex::encode(identity),
382            "PQ binding evicted under capacity pressure; change detection for this identity \
383             is reset until it is seen again"
384        );
385    }
386}
387
388/// The fingerprint compared over the out-of-band channel.
389///
390/// Covers the **pair** — `domain ‖ ed25519 ‖ ml_dsa_65` — not the PQ key alone.
391/// A fingerprint over only the PQ half would confirm that someone holds that
392/// key while saying nothing about which identity it belongs to, which is
393/// exactly the substitution the out-of-band comparison exists to catch.
394#[must_use]
395pub fn composite_fingerprint(ed25519_pubkey: &[u8; 32], ml_dsa_vk: &MlDsaVerifyingKey) -> [u8; 32] {
396    fingerprint_bytes(ed25519_pubkey, &ml_dsa_vk_bytes(ml_dsa_vk))
397}
398
399fn fingerprint_bytes(ed25519_pubkey: &[u8; 32], ml_dsa_vk_bytes: &[u8]) -> [u8; 32] {
400    use sha2::Digest as _;
401    let mut hasher = sha2::Sha256::new();
402    hasher.update(FINGERPRINT_DOMAIN);
403    hasher.update(ed25519_pubkey);
404    hasher.update(ml_dsa_vk_bytes);
405    hasher.finalize().into()
406}
407
408/// Render a fingerprint the way it is shown to a human performing the
409/// comparison: uppercase hex in space-separated quads, so a mismatch in any
410/// position is easy to spot when read aloud or compared by eye.
411#[must_use]
412pub fn format_fingerprint(fingerprint: &[u8; 32]) -> String {
413    let hex = hex::encode_upper(fingerprint);
414    hex.as_bytes()
415        .chunks(4)
416        .map(|c| String::from_utf8_lossy(c).into_owned())
417        .collect::<Vec<_>>()
418        .join(" ")
419}
420
421/// Additive, session-scoped PQ binding overlay.
422pub struct SessionPqOverlay {
423    entries: RwLock<HashMap<[u8; 32], OverlayEntry>>,
424    sink: Arc<dyn PqBindingEventSink>,
425    tofu_ttl_ms: i64,
426    max_entries: usize,
427    /// Recency counter for eviction ordering. Wall-clock is unsuitable: many
428    /// first contacts can land inside one millisecond.
429    contact_seq: std::sync::atomic::AtomicU64,
430}
431
432impl Default for SessionPqOverlay {
433    fn default() -> Self {
434        Self::new(Arc::new(TracingPqBindingEventSink))
435    }
436}
437
438impl SessionPqOverlay {
439    /// Build an overlay with the default TTL and capacity.
440    #[must_use]
441    pub fn new(sink: Arc<dyn PqBindingEventSink>) -> Self {
442        Self {
443            entries: RwLock::new(HashMap::new()),
444            sink,
445            tofu_ttl_ms: DEFAULT_TOFU_TTL_MS,
446            max_entries: DEFAULT_MAX_ENTRIES,
447            contact_seq: std::sync::atomic::AtomicU64::new(0),
448        }
449    }
450
451    /// Override the first-contact lifetime.
452    #[must_use]
453    pub fn with_tofu_ttl_ms(mut self, ttl_ms: i64) -> Self {
454        self.tofu_ttl_ms = ttl_ms;
455        self
456    }
457
458    /// Override the retained-binding ceiling.
459    #[must_use]
460    pub fn with_max_entries(mut self, max_entries: usize) -> Self {
461        self.max_entries = max_entries;
462        self
463    }
464
465    /// The ML-DSA-65 key to check this identity's signature against.
466    ///
467    /// Returns the key and nothing else. There is deliberately no provenance in
468    /// the return type: the verify path has no business knowing how much the
469    /// binding is believed, and cannot accidentally propagate it.
470    #[must_use]
471    pub fn verifying_key_for(&self, ed25519_pubkey: &[u8; 32]) -> Option<MlDsaVerifyingKey> {
472        let now = crate::envelope::current_timestamp();
473        let entries = self.entries.read();
474        let entry = entries.get(ed25519_pubkey)?;
475        if !entry.is_live(now) {
476            return None;
477        }
478        crate::crypto::pq::ml_dsa_vk_from_bytes(&entry.ml_dsa_vk).ok()
479    }
480
481    /// How much this identity's binding is believed, if it has a live one.
482    ///
483    /// This is the trust question, answered separately from
484    /// [`Self::verifying_key_for`].
485    #[must_use]
486    pub fn provenance_for(&self, ed25519_pubkey: &[u8; 32]) -> Option<PqProvenance> {
487        let now = crate::envelope::current_timestamp();
488        let entries = self.entries.read();
489        let entry = entries.get(ed25519_pubkey)?;
490        entry.is_live(now).then_some(entry.provenance)
491    }
492
493    /// The fingerprint of this identity's live binding, for display in an
494    /// out-of-band comparison ceremony.
495    #[must_use]
496    pub fn fingerprint_for(&self, ed25519_pubkey: &[u8; 32]) -> Option<[u8; 32]> {
497        let now = crate::envelope::current_timestamp();
498        let entries = self.entries.read();
499        let entry = entries.get(ed25519_pubkey)?;
500        entry
501            .is_live(now)
502            .then(|| fingerprint_bytes(ed25519_pubkey, &entry.ml_dsa_vk))
503    }
504
505    /// Offer a PQ key observed at first contact.
506    ///
507    /// **Call only after the composite has verified against `presented_vk` AND
508    /// reported the inner layer's commitment to it** (`CompositeVerified::
509    /// pq_bound`). Verification alone is not enough: the nesting binds
510    /// inner→outer only, so a composite without that commitment proves
511    /// possession of the ML-DSA-65 key plus possession of one replayable
512    /// Ed25519 signature — not of the Ed25519 private key. Recording on those
513    /// weaker grounds lets anyone holding a captured envelope bind their own PQ
514    /// key to the sender's identity.
515    ///
516    /// This never overwrites a **live** entry. A live entry naming a different
517    /// key produces [`FirstContactOutcome::RebindRefused`], and the event
518    /// reaches the sink before this returns.
519    ///
520    /// # Change detection is bounded by the TTL
521    ///
522    /// A binding that has lapsed is, by the session-scoped model, forgotten:
523    /// the identity is unbound again and the next contact is genuinely a first
524    /// one, recorded without a refusal even if it names a different key. So the
525    /// window in which a key substitution is caught is exactly the TTL, and an
526    /// attacker who can wait out a device's idle period sees an unbound
527    /// identity rather than a challenged one. Raising the TTL widens detection
528    /// at the cost of remembering devices longer; a promotion
529    /// ([`Self::promote_out_of_band`]) removes the deadline entirely, which is
530    /// the durable answer for an identity worth pinning.
531    pub fn observe_first_contact(
532        &self,
533        ed25519_pubkey: [u8; 32],
534        presented_vk: &MlDsaVerifyingKey,
535    ) -> FirstContactOutcome {
536        let now = crate::envelope::current_timestamp();
537        let presented_bytes = ml_dsa_vk_bytes(presented_vk);
538        let seq = self
539            .contact_seq
540            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
541        let mut evicted: Option<[u8; 32]> = None;
542        let mut return_capacity_exhausted = false;
543
544        let outcome = {
545            let mut entries = self.entries.write();
546            match entries.get_mut(&ed25519_pubkey) {
547                Some(entry) if entry.is_live(now) => {
548                    if entry.ml_dsa_vk == presented_bytes {
549                        entry.last_seen_seq = seq;
550                        FirstContactOutcome::AlreadyBound(entry.provenance)
551                    } else {
552                        // Refuse. The established binding stays exactly as it
553                        // is; the only path that replaces it is `apply_rebind`,
554                        // which needs the event this constructs.
555                        FirstContactOutcome::RebindRefused(RebindEvent {
556                            identity: ed25519_pubkey,
557                            established_vk: entry.ml_dsa_vk.clone(),
558                            established_provenance: entry.provenance,
559                            presented_vk: presented_bytes,
560                        })
561                    }
562                }
563                _ => {
564                    // Vacant or lapsed. Reclaim lapsed entries first — a quiet
565                    // period must not be permanently fatal.
566                    if entries.len() >= self.max_entries {
567                        entries.retain(|_, e| e.is_live(now));
568                    }
569                    // Still full: evict the least-recently-seen *first-contact*
570                    // entry rather than refusing the new one.
571                    //
572                    // Refusing was the obvious fail-closed choice and it is the
573                    // wrong one here. Recording costs an attacker only a
574                    // self-minted keypair — no enrollment, no credential — and
575                    // this runs before authorization, so filling the table is
576                    // seconds of work. Under refusal that locks out every NEW
577                    // dynamic client until entries lapse, i.e. an unauthenticated
578                    // party gets to switch the feature off. Under eviction the
579                    // worst an attacker achieves is resetting other identities'
580                    // change detection, which is the same exposure a lapse
581                    // already carries, and legitimate clients keep connecting.
582                    //
583                    // Promoted bindings are never evicted: they are an operator
584                    // statement, not session continuity.
585                    if entries.len() >= self.max_entries && !entries.contains_key(&ed25519_pubkey) {
586                        let victim = entries
587                            .iter()
588                            .filter(|(_, e)| e.provenance == PqProvenance::TofuBound)
589                            .min_by_key(|(_, e)| e.last_seen_seq)
590                            .map(|(id, _)| *id);
591                        match victim {
592                            Some(id) => {
593                                entries.remove(&id);
594                                evicted = Some(id);
595                            }
596                            // Every slot holds a promotion. Refuse rather than
597                            // discard operator-established trust.
598                            None => return_capacity_exhausted = true,
599                        }
600                    }
601                    if return_capacity_exhausted {
602                        FirstContactOutcome::CapacityExhausted
603                    } else {
604                        entries.insert(
605                            ed25519_pubkey,
606                            OverlayEntry {
607                                ml_dsa_vk: presented_bytes,
608                                provenance: PqProvenance::TofuBound,
609                                expires_at_ms: Some(now.saturating_add(self.tofu_ttl_ms)),
610                                last_seen_seq: seq,
611                            },
612                        );
613                        FirstContactOutcome::Recorded
614                    }
615                }
616            }
617        };
618
619        match &outcome {
620            FirstContactOutcome::RebindRefused(event) => self.sink.on_rebind_refused(event),
621            FirstContactOutcome::Recorded => {
622                let fp = fingerprint_bytes(&ed25519_pubkey, &ml_dsa_vk_bytes(presented_vk));
623                self.sink.on_first_contact(&ed25519_pubkey, &fp);
624            }
625            FirstContactOutcome::CapacityExhausted => {
626                tracing::warn!(
627                    identity = %hex::encode(ed25519_pubkey),
628                    "PQ overlay at capacity with every slot promoted; first-contact binding \
629                     refused (request fails closed)"
630                );
631            }
632            FirstContactOutcome::AlreadyBound(_) => {}
633        }
634        if let Some(id) = evicted {
635            // An evicted identity loses change detection: its next contact is a
636            // fresh first contact. Say so, rather than letting the table quietly
637            // forget.
638            tracing::warn!(
639                evicted_identity = %hex::encode(id),
640                admitted_identity = %hex::encode(ed25519_pubkey),
641                "PQ overlay at capacity; evicted the least-recently-seen first-contact binding"
642            );
643            self.sink.on_evicted(&id);
644        }
645
646        outcome
647    }
648
649    /// Publish a rebinding event **without any possibility of recording**.
650    ///
651    /// The verify path reaches a rebinding attempt before the presented key has
652    /// been checked against anything — the whole point is that the request is
653    /// being rejected. [`Self::observe_first_contact`] must not be reused there:
654    /// its contract is "the composite already verified against this key", and a
655    /// binding that lapses between the lookup and the call would send it down
656    /// the recording branch with an unproven key. This entry point cannot
657    /// record under any interleaving.
658    pub fn surface_rebind(&self, ed25519_pubkey: [u8; 32], presented_vk: &MlDsaVerifyingKey) {
659        let now = crate::envelope::current_timestamp();
660        let event = {
661            let entries = self.entries.read();
662            entries
663                .get(&ed25519_pubkey)
664                .filter(|e| e.is_live(now))
665                .map(|entry| RebindEvent {
666                    identity: ed25519_pubkey,
667                    established_vk: entry.ml_dsa_vk.clone(),
668                    established_provenance: entry.provenance,
669                    presented_vk: ml_dsa_vk_bytes(presented_vk),
670                })
671        };
672        if let Some(event) = event {
673            self.sink.on_rebind_refused(&event);
674        }
675    }
676
677    /// Replace an established binding, under an approval that answers a
678    /// surfaced [`RebindEvent`].
679    ///
680    /// This is the only mutation that can change an existing binding, and it is
681    /// unreachable without the overlay having refused a rebind first. Returns
682    /// `false` when the identity's binding no longer matches the one the event
683    /// described — a concurrent change means the approval answered a stale
684    /// observation and must be re-taken.
685    pub fn apply_rebind(&self, approval: RebindApproval) -> bool {
686        let now = crate::envelope::current_timestamp();
687        let applied = {
688            let mut entries = self.entries.write();
689            match entries.get(&approval.event.identity) {
690                Some(entry) if entry.ml_dsa_vk == approval.event.established_vk => {
691                    let expires_at_ms = match approval.provenance {
692                        PqProvenance::TofuBound => Some(now.saturating_add(self.tofu_ttl_ms)),
693                        PqProvenance::OobVerified => None,
694                    };
695                    entries.insert(
696                        approval.event.identity,
697                        OverlayEntry {
698                            ml_dsa_vk: approval.event.presented_vk.clone(),
699                            provenance: approval.provenance,
700                            expires_at_ms,
701                            last_seen_seq: self
702                                .contact_seq
703                                .fetch_add(1, std::sync::atomic::Ordering::Relaxed),
704                        },
705                    );
706                    true
707                }
708                _ => false,
709            }
710        };
711        if applied {
712            self.sink.on_rebind_applied(&approval);
713        }
714        applied
715    }
716
717    /// Promote a live binding to [`PqProvenance::OobVerified`].
718    ///
719    /// `oob_fingerprint` is the value the operator obtained through the
720    /// independent channel; it must equal [`composite_fingerprint`] over the
721    /// recorded pairing. `channel` names where it came from and is carried into
722    /// the notification.
723    ///
724    /// Promotion never creates a binding — an identity the node has never
725    /// observed cannot be promoted, because there would be no observed pairing
726    /// for the fingerprint to confirm.
727    ///
728    /// # Errors
729    ///
730    /// [`PromotionError::NotBound`] when no live binding exists;
731    /// [`PromotionError::FingerprintMismatch`] when the value does not match.
732    pub fn promote_out_of_band(
733        &self,
734        ed25519_pubkey: &[u8; 32],
735        oob_fingerprint: &[u8; 32],
736        channel: &str,
737    ) -> std::result::Result<(), PromotionError> {
738        use subtle::ConstantTimeEq as _;
739        let now = crate::envelope::current_timestamp();
740        {
741            let mut entries = self.entries.write();
742            let entry = entries
743                .get_mut(ed25519_pubkey)
744                .filter(|e| e.is_live(now))
745                .ok_or(PromotionError::NotBound)?;
746            let recorded = fingerprint_bytes(ed25519_pubkey, &entry.ml_dsa_vk);
747            if !bool::from(recorded.ct_eq(oob_fingerprint)) {
748                return Err(PromotionError::FingerprintMismatch);
749            }
750            entry.provenance = PqProvenance::OobVerified;
751            // A promotion is a statement about the pairing, not about the
752            // session that happened to observe it, so it stops lapsing.
753            entry.expires_at_ms = None;
754        }
755        self.sink
756            .on_promoted(ed25519_pubkey, oob_fingerprint, channel);
757        Ok(())
758    }
759
760    /// Withdraw a promotion, returning the binding to `TofuBound` continuity
761    /// (and to lapsing) without breaking the session using it.
762    ///
763    /// Returns `false` when the identity has no live `OobVerified` binding.
764    pub fn revoke_promotion(&self, ed25519_pubkey: &[u8; 32]) -> bool {
765        let now = crate::envelope::current_timestamp();
766        let revoked = {
767            let mut entries = self.entries.write();
768            match entries.get_mut(ed25519_pubkey) {
769                Some(entry)
770                    if entry.is_live(now) && entry.provenance == PqProvenance::OobVerified =>
771                {
772                    entry.provenance = PqProvenance::TofuBound;
773                    entry.expires_at_ms = Some(now.saturating_add(self.tofu_ttl_ms));
774                    true
775                }
776                _ => false,
777            }
778        };
779        if revoked {
780            self.sink.on_revoked(
781                ed25519_pubkey,
782                PqProvenance::OobVerified,
783                Some(PqProvenance::TofuBound),
784            );
785        }
786        revoked
787    }
788
789    /// Withdraw the binding entirely. The identity returns to the `Classical`
790    /// state — no PQ key bound — and its next contact is a fresh first contact.
791    ///
792    /// Returns `false` when there was nothing to withdraw.
793    pub fn revoke_binding(&self, ed25519_pubkey: &[u8; 32]) -> bool {
794        let removed = self.entries.write().remove(ed25519_pubkey);
795        match removed {
796            Some(entry) => {
797                self.sink.on_revoked(ed25519_pubkey, entry.provenance, None);
798                true
799            }
800            None => false,
801        }
802    }
803
804    /// Number of live bindings.
805    #[must_use]
806    pub fn len(&self) -> usize {
807        let now = crate::envelope::current_timestamp();
808        self.entries
809            .read()
810            .values()
811            .filter(|v| v.is_live(now))
812            .count()
813    }
814
815    /// Whether the overlay holds no live bindings.
816    #[must_use]
817    pub fn is_empty(&self) -> bool {
818        self.len() == 0
819    }
820}
821
822// ============================================================================
823// Process-global overlay.
824// ============================================================================
825
826#[cfg(not(target_arch = "wasm32"))]
827static SESSION_PQ_OVERLAY: std::sync::OnceLock<Arc<SessionPqOverlay>> = std::sync::OnceLock::new();
828
829/// Install the process-global overlay. First write wins.
830///
831/// **Not installed by default.** With no overlay installed the verify path
832/// behaves exactly as it did before this existed: an identity with no
833/// admin-anchored ML-DSA-65 key is rejected under the mandatory Hybrid suite.
834/// Trust-on-first-use is a deployment decision, so it is opted into explicitly
835/// rather than acquired by linking this crate.
836///
837/// # Errors
838///
839/// Returns `Err` when an overlay was already installed.
840#[cfg(not(target_arch = "wasm32"))]
841pub fn install_session_pq_overlay(overlay: Arc<SessionPqOverlay>) -> anyhow::Result<()> {
842    SESSION_PQ_OVERLAY
843        .set(overlay)
844        .map_err(|_| anyhow::anyhow!("session PQ overlay already installed"))
845}
846
847/// The installed process-global overlay, if any.
848#[cfg(not(target_arch = "wasm32"))]
849#[must_use]
850pub fn global_session_pq_overlay() -> Option<Arc<SessionPqOverlay>> {
851    SESSION_PQ_OVERLAY.get().cloned()
852}
853
854#[cfg(test)]
855#[allow(clippy::unwrap_used, clippy::expect_used)]
856mod tests {
857    use super::*;
858
859    fn pq_key(seed: u8) -> MlDsaVerifyingKey {
860        let sk = crate::crypto::pq::ml_dsa_sk_from_seed(&[seed; 32]);
861        crate::crypto::pq::ml_dsa_vk_from_bytes(&crate::crypto::pq::ml_dsa_sk_to_vk_bytes(&sk))
862            .expect("derived verifying key round-trips")
863    }
864
865    fn ed_identity(seed: u8) -> [u8; 32] {
866        [seed; 32]
867    }
868
869    #[derive(Default)]
870    struct CountingSink {
871        refused: std::sync::atomic::AtomicUsize,
872        applied: std::sync::atomic::AtomicUsize,
873        first_contact: std::sync::atomic::AtomicUsize,
874        promoted: std::sync::atomic::AtomicUsize,
875        revoked: std::sync::atomic::AtomicUsize,
876    }
877
878    impl CountingSink {
879        fn count(v: &std::sync::atomic::AtomicUsize) -> usize {
880            v.load(std::sync::atomic::Ordering::SeqCst)
881        }
882        fn bump(v: &std::sync::atomic::AtomicUsize) {
883            v.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
884        }
885    }
886
887    impl PqBindingEventSink for CountingSink {
888        fn on_rebind_refused(&self, _event: &RebindEvent) {
889            Self::bump(&self.refused);
890        }
891        fn on_rebind_applied(&self, _approval: &RebindApproval) {
892            Self::bump(&self.applied);
893        }
894        fn on_first_contact(&self, _identity: &[u8; 32], _fingerprint: &[u8; 32]) {
895            Self::bump(&self.first_contact);
896        }
897        fn on_promoted(&self, _identity: &[u8; 32], _fingerprint: &[u8; 32], _channel: &str) {
898            Self::bump(&self.promoted);
899        }
900        fn on_revoked(&self, _i: &[u8; 32], _f: PqProvenance, _t: Option<PqProvenance>) {
901            Self::bump(&self.revoked);
902        }
903    }
904
905    fn overlay_with_sink() -> (SessionPqOverlay, Arc<CountingSink>) {
906        let sink = Arc::new(CountingSink::default());
907        (SessionPqOverlay::new(sink.clone()), sink)
908    }
909
910    #[test]
911    fn first_contact_records_a_tofu_binding() {
912        let (overlay, sink) = overlay_with_sink();
913        let id = ed_identity(1);
914        let key = pq_key(11);
915
916        assert!(matches!(
917            overlay.observe_first_contact(id, &key),
918            FirstContactOutcome::Recorded
919        ));
920        assert_eq!(CountingSink::count(&sink.first_contact), 1);
921        assert_eq!(
922            ml_dsa_vk_bytes(&overlay.verifying_key_for(&id).unwrap()),
923            ml_dsa_vk_bytes(&key)
924        );
925        assert_eq!(overlay.provenance_for(&id), Some(PqProvenance::TofuBound));
926    }
927
928    #[test]
929    fn repeat_contact_with_the_same_key_changes_nothing() {
930        let (overlay, sink) = overlay_with_sink();
931        let id = ed_identity(2);
932        let key = pq_key(12);
933
934        let _ = overlay.observe_first_contact(id, &key);
935        let outcome = overlay.observe_first_contact(id, &key);
936        assert!(matches!(
937            outcome,
938            FirstContactOutcome::AlreadyBound(PqProvenance::TofuBound)
939        ));
940        assert_eq!(CountingSink::count(&sink.refused), 0);
941        assert_eq!(CountingSink::count(&sink.first_contact), 1);
942    }
943
944    #[test]
945    fn a_different_key_is_refused_and_surfaced_not_silently_written() {
946        let (overlay, sink) = overlay_with_sink();
947        let id = ed_identity(3);
948        let original = pq_key(13);
949        let substitute = pq_key(14);
950
951        let _ = overlay.observe_first_contact(id, &original);
952        let outcome = overlay.observe_first_contact(id, &substitute);
953
954        let FirstContactOutcome::RebindRefused(event) = outcome else {
955            panic!("a different key must be refused, not accepted");
956        };
957        // The event reached the sink before the caller saw the outcome.
958        assert_eq!(CountingSink::count(&sink.refused), 1);
959        assert_eq!(event.established_provenance(), PqProvenance::TofuBound);
960        assert_ne!(
961            event.established_fingerprint(),
962            event.presented_fingerprint()
963        );
964        // Last write did NOT win.
965        assert_eq!(
966            ml_dsa_vk_bytes(&overlay.verifying_key_for(&id).unwrap()),
967            ml_dsa_vk_bytes(&original)
968        );
969    }
970
971    #[test]
972    fn replacing_a_binding_requires_an_approval_built_from_the_refusal() {
973        let (overlay, sink) = overlay_with_sink();
974        let id = ed_identity(4);
975        let original = pq_key(15);
976        let rotated = pq_key(16);
977
978        let _ = overlay.observe_first_contact(id, &original);
979        let FirstContactOutcome::RebindRefused(event) = overlay.observe_first_contact(id, &rotated)
980        else {
981            panic!("rotation must surface as a refused rebind");
982        };
983
984        assert!(overlay.apply_rebind(event.approve(PqProvenance::TofuBound, "operator rotation")));
985        assert_eq!(CountingSink::count(&sink.applied), 1);
986        assert_eq!(
987            ml_dsa_vk_bytes(&overlay.verifying_key_for(&id).unwrap()),
988            ml_dsa_vk_bytes(&rotated)
989        );
990        // Rotation through the visible path does not confer trust on its own.
991        assert_eq!(overlay.provenance_for(&id), Some(PqProvenance::TofuBound));
992    }
993
994    #[test]
995    fn a_stale_approval_does_not_apply() {
996        let (overlay, _sink) = overlay_with_sink();
997        let id = ed_identity(5);
998        let original = pq_key(17);
999        let rotated = pq_key(18);
1000        let other = pq_key(19);
1001
1002        let _ = overlay.observe_first_contact(id, &original);
1003        let FirstContactOutcome::RebindRefused(event) = overlay.observe_first_contact(id, &rotated)
1004        else {
1005            panic!("expected a refusal");
1006        };
1007        // The binding moves underneath the pending approval.
1008        overlay.revoke_binding(&id);
1009        let _ = overlay.observe_first_contact(id, &other);
1010
1011        assert!(!overlay.apply_rebind(event.approve(PqProvenance::OobVerified, "stale")));
1012        assert_eq!(
1013            ml_dsa_vk_bytes(&overlay.verifying_key_for(&id).unwrap()),
1014            ml_dsa_vk_bytes(&other)
1015        );
1016    }
1017
1018    #[test]
1019    fn tofu_never_reaches_pq_hybrid_key_material() {
1020        assert_eq!(
1021            PqProvenance::TofuBound.key_material(),
1022            VerifiedKeyMaterial::Classical
1023        );
1024        assert_eq!(
1025            PqProvenance::TofuBound.assurance_ceiling(),
1026            Assurance::Classical
1027        );
1028        assert!(PqProvenance::TofuBound.assurance_ceiling() < Assurance::PqHybrid);
1029    }
1030
1031    #[test]
1032    fn only_oob_verified_reaches_pq_hybrid() {
1033        // Exhaustive over the provenance domain: exactly one variant may raise.
1034        for p in [PqProvenance::TofuBound, PqProvenance::OobVerified] {
1035            let raises = p.key_material() == VerifiedKeyMaterial::PqHybrid;
1036            assert_eq!(raises, p == PqProvenance::OobVerified);
1037        }
1038    }
1039
1040    #[test]
1041    fn promotion_requires_the_composite_fingerprint() {
1042        let (overlay, sink) = overlay_with_sink();
1043        let id = ed_identity(6);
1044        let key = pq_key(20);
1045        let _ = overlay.observe_first_contact(id, &key);
1046
1047        // A fingerprint over the PQ half bound to a *different* identity must
1048        // not promote: the value covers the pair, not the key alone.
1049        let wrong = composite_fingerprint(&ed_identity(7), &key);
1050        assert_eq!(
1051            overlay.promote_out_of_band(&id, &wrong, "printed"),
1052            Err(PromotionError::FingerprintMismatch)
1053        );
1054        assert_eq!(overlay.provenance_for(&id), Some(PqProvenance::TofuBound));
1055
1056        let right = composite_fingerprint(&id, &key);
1057        assert!(overlay.promote_out_of_band(&id, &right, "printed").is_ok());
1058        assert_eq!(overlay.provenance_for(&id), Some(PqProvenance::OobVerified));
1059        assert_eq!(CountingSink::count(&sink.promoted), 1);
1060    }
1061
1062    #[test]
1063    fn promotion_cannot_invent_a_binding() {
1064        let (overlay, _sink) = overlay_with_sink();
1065        let id = ed_identity(8);
1066        let key = pq_key(21);
1067        assert_eq!(
1068            overlay.promote_out_of_band(&id, &composite_fingerprint(&id, &key), "printed"),
1069            Err(PromotionError::NotBound)
1070        );
1071        assert!(overlay.verifying_key_for(&id).is_none());
1072    }
1073
1074    #[test]
1075    fn a_promotion_can_be_revoked() {
1076        let (overlay, sink) = overlay_with_sink();
1077        let id = ed_identity(9);
1078        let key = pq_key(22);
1079        let _ = overlay.observe_first_contact(id, &key);
1080        overlay
1081            .promote_out_of_band(&id, &composite_fingerprint(&id, &key), "printed")
1082            .unwrap();
1083
1084        assert!(overlay.revoke_promotion(&id));
1085        assert_eq!(CountingSink::count(&sink.revoked), 1);
1086        // Trust is withdrawn; verifiability and the live session are not.
1087        assert_eq!(overlay.provenance_for(&id), Some(PqProvenance::TofuBound));
1088        assert!(overlay.verifying_key_for(&id).is_some());
1089        // Idempotent: nothing left to revoke.
1090        assert!(!overlay.revoke_promotion(&id));
1091    }
1092
1093    #[test]
1094    fn revoking_a_binding_returns_the_identity_to_unbound() {
1095        let (overlay, _sink) = overlay_with_sink();
1096        let id = ed_identity(10);
1097        let key = pq_key(23);
1098        let _ = overlay.observe_first_contact(id, &key);
1099        assert!(overlay.revoke_binding(&id));
1100        assert!(overlay.verifying_key_for(&id).is_none());
1101        assert!(overlay.provenance_for(&id).is_none());
1102        assert!(!overlay.revoke_binding(&id));
1103    }
1104
1105    #[test]
1106    fn a_lapsed_first_contact_binding_stops_verifying() {
1107        let (overlay, _sink) = overlay_with_sink();
1108        let overlay = overlay.with_tofu_ttl_ms(0);
1109        let id = ed_identity(11);
1110        let key = pq_key(24);
1111        let _ = overlay.observe_first_contact(id, &key);
1112        assert!(overlay.verifying_key_for(&id).is_none());
1113        assert!(overlay.is_empty());
1114    }
1115
1116    #[test]
1117    fn a_promoted_binding_does_not_lapse() {
1118        let (overlay, _sink) = overlay_with_sink();
1119        let overlay = overlay.with_tofu_ttl_ms(60_000);
1120        let id = ed_identity(12);
1121        let key = pq_key(25);
1122        let _ = overlay.observe_first_contact(id, &key);
1123        overlay
1124            .promote_out_of_band(&id, &composite_fingerprint(&id, &key), "printed")
1125            .unwrap();
1126        // Shrinking the TTL cannot retroactively expire a promotion: it carries
1127        // no deadline at all.
1128        assert_eq!(overlay.provenance_for(&id), Some(PqProvenance::OobVerified));
1129    }
1130
1131    #[test]
1132    fn a_full_table_evicts_the_stalest_entry_rather_than_locking_new_clients_out() {
1133        let (overlay, _sink) = overlay_with_sink();
1134        let overlay = overlay.with_max_entries(2);
1135        let stale = ed_identity(13);
1136        let recent = ed_identity(14);
1137        let arriving = ed_identity(15);
1138
1139        let _ = overlay.observe_first_contact(stale, &pq_key(26));
1140        let _ = overlay.observe_first_contact(recent, &pq_key(27));
1141        // Touch `recent` so `stale` is unambiguously the least-recently-seen.
1142        let _ = overlay.observe_first_contact(recent, &pq_key(27));
1143
1144        assert!(matches!(
1145            overlay.observe_first_contact(arriving, &pq_key(28)),
1146            FirstContactOutcome::Recorded
1147        ));
1148        assert!(
1149            overlay.verifying_key_for(&arriving).is_some(),
1150            "a new client must not be locked out by a full table"
1151        );
1152        assert!(overlay.verifying_key_for(&stale).is_none());
1153        assert!(overlay.verifying_key_for(&recent).is_some());
1154    }
1155
1156    #[test]
1157    fn a_promoted_binding_is_never_evicted() {
1158        let (overlay, _sink) = overlay_with_sink();
1159        let overlay = overlay.with_max_entries(1);
1160        let promoted = ed_identity(16);
1161        let key = pq_key(29);
1162        let _ = overlay.observe_first_contact(promoted, &key);
1163        overlay
1164            .promote_out_of_band(
1165                &promoted,
1166                &composite_fingerprint(&promoted, &key),
1167                "printed",
1168            )
1169            .unwrap();
1170
1171        // Every slot holds operator-established trust, so the arriving identity
1172        // is refused rather than that trust discarded.
1173        assert!(matches!(
1174            overlay.observe_first_contact(ed_identity(17), &pq_key(30)),
1175            FirstContactOutcome::CapacityExhausted
1176        ));
1177        assert_eq!(
1178            overlay.provenance_for(&promoted),
1179            Some(PqProvenance::OobVerified)
1180        );
1181    }
1182
1183    #[test]
1184    fn surfacing_a_rebind_can_never_record() {
1185        let (overlay, sink) = overlay_with_sink();
1186        let id = ed_identity(18);
1187        let original = pq_key(31);
1188        let other = pq_key(32);
1189
1190        // No binding at all: surfacing must not create one.
1191        overlay.surface_rebind(id, &other);
1192        assert!(overlay.verifying_key_for(&id).is_none());
1193        assert_eq!(CountingSink::count(&sink.refused), 0);
1194
1195        let _ = overlay.observe_first_contact(id, &original);
1196        overlay.surface_rebind(id, &other);
1197        assert_eq!(CountingSink::count(&sink.refused), 1);
1198        assert_eq!(
1199            ml_dsa_vk_bytes(&overlay.verifying_key_for(&id).unwrap()),
1200            ml_dsa_vk_bytes(&original)
1201        );
1202    }
1203
1204    #[test]
1205    fn the_fingerprint_covers_both_halves() {
1206        let a = ed_identity(15);
1207        let b = ed_identity(16);
1208        let k1 = pq_key(28);
1209        let k2 = pq_key(29);
1210        assert_ne!(
1211            composite_fingerprint(&a, &k1),
1212            composite_fingerprint(&b, &k1)
1213        );
1214        assert_ne!(
1215            composite_fingerprint(&a, &k1),
1216            composite_fingerprint(&a, &k2)
1217        );
1218    }
1219
1220    #[test]
1221    fn fingerprint_display_is_grouped_for_reading_aloud() {
1222        let fp = composite_fingerprint(&ed_identity(17), &pq_key(30));
1223        let rendered = format_fingerprint(&fp);
1224        assert_eq!(rendered.split(' ').count(), 16);
1225        assert!(rendered
1226            .chars()
1227            .all(|c| c.is_ascii_hexdigit() && !c.is_ascii_lowercase() || c == ' '));
1228    }
1229}