1use 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
91const FINGERPRINT_DOMAIN: &[u8] = b"hyprstream/pq-composite-fingerprint/v1";
93
94pub const DEFAULT_TOFU_TTL_MS: i64 = 12 * 60 * 60 * 1000;
98
99pub const DEFAULT_MAX_ENTRIES: usize = 4096;
109
110#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
116pub enum PqProvenance {
117 TofuBound,
122 OobVerified,
126}
127
128impl PqProvenance {
129 #[must_use]
135 pub fn key_material(self) -> VerifiedKeyMaterial {
136 match self {
137 PqProvenance::TofuBound => VerifiedKeyMaterial::Classical,
139 PqProvenance::OobVerified => VerifiedKeyMaterial::PqHybrid,
140 }
141 }
142
143 #[must_use]
145 pub fn assurance_ceiling(self) -> Assurance {
146 self.key_material().assurance()
147 }
148
149 #[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#[derive(Debug, Clone)]
161struct OverlayEntry {
162 ml_dsa_vk: Vec<u8>,
163 provenance: PqProvenance,
164 expires_at_ms: Option<i64>,
168 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#[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 #[must_use]
199 pub fn identity(&self) -> &[u8; 32] {
200 &self.identity
201 }
202
203 #[must_use]
205 pub fn established_provenance(&self) -> PqProvenance {
206 self.established_provenance
207 }
208
209 #[must_use]
211 pub fn established_fingerprint(&self) -> [u8; 32] {
212 fingerprint_bytes(&self.identity, &self.established_vk)
213 }
214
215 #[must_use]
217 pub fn presented_fingerprint(&self) -> [u8; 32] {
218 fingerprint_bytes(&self.identity, &self.presented_vk)
219 }
220
221 #[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#[derive(Debug, Clone)]
243pub struct RebindApproval {
244 event: RebindEvent,
245 provenance: PqProvenance,
246 justification: String,
247}
248
249impl RebindApproval {
250 pub fn event(&self) -> &RebindEvent {
252 &self.event
253 }
254
255 #[must_use]
257 pub fn provenance(&self) -> PqProvenance {
258 self.provenance
259 }
260}
261
262#[derive(Debug, Clone)]
264#[must_use]
265pub enum FirstContactOutcome {
266 Recorded,
268 AlreadyBound(PqProvenance),
270 RebindRefused(RebindEvent),
272 CapacityExhausted,
275}
276
277#[derive(Debug, Clone, PartialEq, Eq)]
279pub enum PromotionError {
280 NotBound,
284 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
301pub trait PqBindingEventSink: Send + Sync {
306 fn on_rebind_refused(&self, event: &RebindEvent);
309
310 fn on_rebind_applied(&self, approval: &RebindApproval);
312
313 fn on_first_contact(&self, _identity: &[u8; 32], _fingerprint: &[u8; 32]) {}
315
316 fn on_promoted(&self, _identity: &[u8; 32], _fingerprint: &[u8; 32], _channel: &str) {}
318
319 fn on_revoked(&self, _identity: &[u8; 32], _from: PqProvenance, _to: Option<PqProvenance>) {}
321
322 fn on_evicted(&self, _identity: &[u8; 32]) {}
325}
326
327pub 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#[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#[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
421pub struct SessionPqOverlay {
423 entries: RwLock<HashMap<[u8; 32], OverlayEntry>>,
424 sink: Arc<dyn PqBindingEventSink>,
425 tofu_ttl_ms: i64,
426 max_entries: usize,
427 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 #[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 #[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 #[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 #[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 #[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 #[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 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 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 if entries.len() >= self.max_entries {
567 entries.retain(|_, e| e.is_live(now));
568 }
569 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 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 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 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 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 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 entry.expires_at_ms = None;
754 }
755 self.sink
756 .on_promoted(ed25519_pubkey, oob_fingerprint, channel);
757 Ok(())
758 }
759
760 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 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 #[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 #[must_use]
817 pub fn is_empty(&self) -> bool {
818 self.len() == 0
819 }
820}
821
822#[cfg(not(target_arch = "wasm32"))]
827static SESSION_PQ_OVERLAY: std::sync::OnceLock<Arc<SessionPqOverlay>> = std::sync::OnceLock::new();
828
829#[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#[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 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 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 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 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 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 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 assert_eq!(overlay.provenance_for(&id), Some(PqProvenance::TofuBound));
1088 assert!(overlay.verifying_key_for(&id).is_some());
1089 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 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 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 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 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}