Skip to main content

hyprstream_rpc/crypto/
hybrid_kem.rs

1//! Hybrid multi-KEM key agreement ("HyKEM") — #551 / S0 of epic #550.
2//!
3//! A component-pluggable hybrid Key Encapsulation Mechanism whose combined shared
4//! secret is **secure as long as at least one component KEM remains unbroken**
5//! (the standard "secure-if-one-holds" combiner property). This is the
6//! confidentiality counterpart to the hybrid EdDSA + ML-DSA-65 *signature* stack
7//! in [`crate::crypto::cose_sign`].
8//!
9//! # Construction
10//!
11//! A [`SuiteId`] fixes an **ordered** list of component KEMs. Encapsulation runs
12//! every component against the recipient's per-component encapsulation key,
13//! collects each `(ciphertext, shared_secret)`, and folds them into a single
14//! 32-byte secret with a **KMAC256 transcript-binding combiner** (NIST SP
15//! 800-185), generalizing the X-Wing combiner
16//! (`SHA3-256(ss_M ‖ ss_X ‖ ct_X ‖ pk_X ‖ label)`,
17//! draft-connolly-cfrg-xwing-kem) to N components:
18//!
19//! ```text
20//! K  = KMAC256_DOMAIN_KEY                       (fixed 32-byte domain key)
21//! S  = "HyKEM-v1-combiner" ‖ 0x00 ‖ suite_id    (KMAC customization string)
22//! X  = be16(suite_id) ‖ be32(n)
23//!      ‖  Σ_i lp(ss_i)                           (ALL component shared secrets)
24//!      ‖  Σ_i lp(ct_i)                           (ALL component ciphertexts)
25//!      ‖  Σ_i lp(ek_i)                           (ALL recipient encap keys)
26//! secret = KMAC256(K, X, L=256 bits, S)
27//! ```
28//! where `lp(x) = be32(len(x)) ‖ x` and the component order is the suite's.
29//!
30//! ## Why secure-if-one-holds
31//!
32//! KMAC256 is a PRF keyed by a fixed domain key. **Every** component shared
33//! secret is an input block, so the output is pseudorandom to an adversary who is
34//! missing *any single* `ss_i` — breaking N-1 components (learning their secrets)
35//! does not let them predict the output while one `ss_i` stays unknown. Including
36//! every `ct_i` and recipient `ek_i` binds the full transcript (X-Wing binds the
37//! X25519 `ct`/`pk` for exactly this reason), so a component's ciphertext cannot
38//! be swapped without changing the key.
39//!
40//! ## Why suite-bound (extensibility without collisions)
41//!
42//! The `suite_id` is folded into **both** the KMAC customization string `S` and
43//! the message `X`. A future suite that appends a third (e.g. non-lattice) leg is
44//! a **new `SuiteId`** with a distinct id, so its combined secret is in a
45//! separate domain and can never collide with the 2-KEM suite's — the trait and
46//! combiner never name a concrete KEM, so adding a leg is additive (epic #550 §3).
47//! Suite selection is a pinned policy decision; there is no in-band negotiation.
48//!
49//! # Forward secrecy
50//!
51//! The X25519 leg is modeled as DHKEM (RFC 9180 §4.1): each encapsulation uses a
52//! fresh **ephemeral** X25519 key, so that leg is forward-secret. The ML-KEM leg
53//! encapsulates to the recipient's (possibly long-lived) key; forward secrecy of
54//! the *suite* therefore rests on the ephemeral X25519 leg unless the ML-KEM key
55//! is itself ephemeral/rotated (handled by the caller — streams use ephemeral
56//! ML-KEM keys per #554; the envelope uses rotated `#mesh-kem` prekeys per #552).
57//!
58//! # Wasm
59//!
60//! All components are pure Rust (`x25519-dalek`, `ml-kem`, `tiny-keccak`) and
61//! compile to `wasm32-unknown-unknown`.
62//!
63//! # Scope (S0)
64//!
65//! This module is the primitive + Rust wire types only. The Cap'n Proto schema
66//! wiring of [`HybridKemMaterial`] into `RequestEnvelope` / `StreamInfo` /
67//! `SignedEnvelope` is deferred to S3 (#554) and S4 (#555).
68
69use anyhow::{bail, Result};
70use rand::rngs::OsRng;
71use rand::RngCore;
72use tiny_keccak::{Hasher, Kmac};
73use x25519_dalek::{EphemeralSecret, PublicKey, StaticSecret};
74use zeroize::Zeroizing;
75
76use crate::crypto::pq;
77
78// ============================================================================
79// Component / suite identifiers
80// ============================================================================
81
82/// Stable wire identifier for a single KEM component.
83#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
84#[repr(u16)]
85pub enum KemId {
86    /// X25519 modeled as DHKEM (RFC 9180 §4.1). `ek`=32B, `ct`=32B, `ss`=32B.
87    X25519 = 0x0001,
88    /// ML-KEM-768 (FIPS 203). `ek`=1184B, `ct`=1088B, `ss`=32B.
89    MlKem768 = 0x0002,
90}
91
92impl KemId {
93    /// Stable u16 wire id.
94    pub fn as_u16(self) -> u16 {
95        self as u16
96    }
97
98    /// Parse from the u16 wire id.
99    pub fn from_u16(v: u16) -> Option<Self> {
100        match v {
101            0x0001 => Some(Self::X25519),
102            0x0002 => Some(Self::MlKem768),
103            _ => None,
104        }
105    }
106
107    /// The component implementation for this id.
108    fn component(self) -> &'static dyn KemComponent {
109        match self {
110            Self::X25519 => &X25519Kem,
111            Self::MlKem768 => &MlKem768Kem,
112        }
113    }
114}
115
116/// A pinned hybrid-KEM suite: an ordered set of component KEMs plus a stable id
117/// that is cryptographically bound into the combiner.
118///
119/// Adding a suite (e.g. a future `…-McEliece6960119`) is a single new variant —
120/// no change to [`KemComponent`] or the combiner. Suite choice is policy-pinned
121/// (epic #550 principle: crypto-agility = pinned suite, no in-band downgrade).
122#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
123#[non_exhaustive]
124pub enum SuiteId {
125    /// X25519 + ML-KEM-768 — the 2-KEM baseline (#551).
126    HyKemX25519MlKem768,
127}
128
129impl SuiteId {
130    /// Stable string id, bound into the KMAC customization string `S`.
131    pub fn as_str(self) -> &'static str {
132        match self {
133            Self::HyKemX25519MlKem768 => "HyKEM-X25519-MLKEM768",
134        }
135    }
136
137    /// Stable u16 wire id, bound into the combiner message `X` and the
138    /// [`HybridKemMaterial`] wire encoding.
139    pub fn as_u16(self) -> u16 {
140        match self {
141            Self::HyKemX25519MlKem768 => 0x0001,
142        }
143    }
144
145    /// Parse from the u16 wire id.
146    pub fn from_u16(v: u16) -> Option<Self> {
147        match v {
148            0x0001 => Some(Self::HyKemX25519MlKem768),
149            _ => None,
150        }
151    }
152
153    /// The **ordered** component list. Order is part of the suite definition and
154    /// is covered by the combiner — never reorder without minting a new suite id.
155    pub fn components(self) -> &'static [KemId] {
156        match self {
157            Self::HyKemX25519MlKem768 => &[KemId::X25519, KemId::MlKem768],
158        }
159    }
160}
161
162// ============================================================================
163// Component trait + implementations (object-safe, byte-oriented)
164// ============================================================================
165
166/// One KEM component of a hybrid suite.
167///
168/// Object-safe and byte-oriented: the combiner iterates `&[&dyn KemComponent]`,
169/// and components have heterogeneous key/ciphertext types, so all material
170/// crosses the trait boundary as bytes. Shared secrets are wrapped in
171/// [`Zeroizing`].
172pub trait KemComponent {
173    /// Stable identifier for this component.
174    fn kem_id(&self) -> KemId;
175    /// Recipient encapsulation-key length in bytes.
176    fn ek_len(&self) -> usize;
177    /// Ciphertext length in bytes.
178    fn ct_len(&self) -> usize;
179    /// Shared-secret length in bytes.
180    fn ss_len(&self) -> usize;
181
182    /// Generate a recipient keypair, returning `(decap_key_bytes, encap_key_bytes)`.
183    fn generate_recipient_keypair(&self) -> Result<(Zeroizing<Vec<u8>>, Vec<u8>)>;
184
185    /// Encapsulate to `recipient_ek`, returning `(ciphertext, shared_secret)`.
186    fn encapsulate(&self, recipient_ek: &[u8]) -> Result<(Vec<u8>, Zeroizing<Vec<u8>>)>;
187
188    /// Decapsulate `ct` with `decap_key`, returning the shared secret.
189    fn decapsulate(&self, decap_key: &[u8], ct: &[u8]) -> Result<Zeroizing<Vec<u8>>>;
190
191    /// Byte length of the deterministic seed consumed by
192    /// [`KemComponent::recipient_from_seed`].
193    fn seed_len(&self) -> usize;
194
195    /// Deterministically derive a recipient keypair from `seed` (length
196    /// [`KemComponent::seed_len`]), returning `(decap_key_bytes, encap_key_bytes)`.
197    /// Stable identity keys (e.g. `#mesh-kem`) use this so they survive restarts,
198    /// unlike the OsRng [`KemComponent::generate_recipient_keypair`].
199    fn recipient_from_seed(&self, seed: &[u8]) -> Result<(Zeroizing<Vec<u8>>, Vec<u8>)>;
200}
201
202fn arr32(b: &[u8]) -> Result<[u8; 32]> {
203    if b.len() != 32 {
204        bail!("expected 32 bytes, got {}", b.len());
205    }
206    let mut a = [0u8; 32];
207    a.copy_from_slice(b);
208    Ok(a)
209}
210
211fn arr64(b: &[u8]) -> Result<[u8; 64]> {
212    if b.len() != 64 {
213        bail!("expected 64-byte ML-KEM seed, got {}", b.len());
214    }
215    let mut a = [0u8; 64];
216    a.copy_from_slice(b);
217    Ok(a)
218}
219
220/// X25519 as a DHKEM (RFC 9180 §4.1): `Encap` picks a fresh ephemeral key, the
221/// ciphertext is the ephemeral public key, and the shared secret is the X25519
222/// DH output. The ephemeral key gives this leg forward secrecy.
223pub struct X25519Kem;
224
225impl KemComponent for X25519Kem {
226    fn kem_id(&self) -> KemId {
227        KemId::X25519
228    }
229    fn ek_len(&self) -> usize {
230        32
231    }
232    fn ct_len(&self) -> usize {
233        32
234    }
235    fn ss_len(&self) -> usize {
236        32
237    }
238
239    fn generate_recipient_keypair(&self) -> Result<(Zeroizing<Vec<u8>>, Vec<u8>)> {
240        let sk = StaticSecret::random_from_rng(OsRng);
241        let pk = PublicKey::from(&sk);
242        Ok((
243            Zeroizing::new(sk.to_bytes().to_vec()),
244            pk.to_bytes().to_vec(),
245        ))
246    }
247
248    fn encapsulate(&self, recipient_ek: &[u8]) -> Result<(Vec<u8>, Zeroizing<Vec<u8>>)> {
249        let recipient_pk = PublicKey::from(arr32(recipient_ek)?);
250        let eph = EphemeralSecret::random_from_rng(OsRng);
251        let eph_pub = PublicKey::from(&eph);
252        let ss = eph.diffie_hellman(&recipient_pk);
253        // Reject the all-zero shared secret from a low-order recipient key. The
254        // combiner mixes in the other legs, but failing closed here is cleaner.
255        if !ss.was_contributory() {
256            bail!("X25519 KEM: non-contributory shared secret (low-order point)");
257        }
258        Ok((
259            eph_pub.to_bytes().to_vec(),
260            Zeroizing::new(ss.to_bytes().to_vec()),
261        ))
262    }
263
264    fn decapsulate(&self, decap_key: &[u8], ct: &[u8]) -> Result<Zeroizing<Vec<u8>>> {
265        let sk = StaticSecret::from(arr32(decap_key)?);
266        let eph_pub = PublicKey::from(arr32(ct)?);
267        let ss = sk.diffie_hellman(&eph_pub);
268        if !ss.was_contributory() {
269            bail!("X25519 KEM: non-contributory shared secret (low-order point)");
270        }
271        Ok(Zeroizing::new(ss.to_bytes().to_vec()))
272    }
273
274    fn seed_len(&self) -> usize {
275        32
276    }
277
278    fn recipient_from_seed(&self, seed: &[u8]) -> Result<(Zeroizing<Vec<u8>>, Vec<u8>)> {
279        // The 32-byte seed is the X25519 secret scalar (clamped internally by
280        // `x25519-dalek` at DH time); `to_bytes()` round-trips it.
281        let sk = StaticSecret::from(arr32(seed)?);
282        let pk = PublicKey::from(&sk);
283        Ok((
284            Zeroizing::new(sk.to_bytes().to_vec()),
285            pk.to_bytes().to_vec(),
286        ))
287    }
288}
289
290/// ML-KEM-768 (FIPS 203) component. The recipient decapsulation key is carried
291/// as its 64-byte FIPS 203 seed (`d ‖ z`).
292pub struct MlKem768Kem;
293
294impl KemComponent for MlKem768Kem {
295    fn kem_id(&self) -> KemId {
296        KemId::MlKem768
297    }
298    fn ek_len(&self) -> usize {
299        1184
300    }
301    fn ct_len(&self) -> usize {
302        1088
303    }
304    fn ss_len(&self) -> usize {
305        32
306    }
307
308    fn generate_recipient_keypair(&self) -> Result<(Zeroizing<Vec<u8>>, Vec<u8>)> {
309        let mut seed = [0u8; 64];
310        OsRng.fill_bytes(&mut seed);
311        let dk = pq::ml_kem_decaps_from_seed(&seed);
312        let ek_bytes = pq::ml_kem_ek_of_dk(&dk);
313        Ok((Zeroizing::new(seed.to_vec()), ek_bytes))
314    }
315
316    fn encapsulate(&self, recipient_ek: &[u8]) -> Result<(Vec<u8>, Zeroizing<Vec<u8>>)> {
317        let ek = pq::ml_kem_ek_from_bytes(recipient_ek)?;
318        let (ct, ss) = pq::ml_kem_encapsulate(&ek);
319        Ok((ct, Zeroizing::new(ss.to_vec())))
320    }
321
322    fn decapsulate(&self, decap_key: &[u8], ct: &[u8]) -> Result<Zeroizing<Vec<u8>>> {
323        let seed = arr64(decap_key)?;
324        let dk = pq::ml_kem_decaps_from_seed(&seed);
325        let ss = pq::ml_kem_decapsulate(&dk, ct)?;
326        Ok(Zeroizing::new(ss.to_vec()))
327    }
328
329    fn seed_len(&self) -> usize {
330        64
331    }
332
333    fn recipient_from_seed(&self, seed: &[u8]) -> Result<(Zeroizing<Vec<u8>>, Vec<u8>)> {
334        // FIPS 203 expandedPrivateKey seed `d ‖ z` (64 bytes); the decap key is
335        // carried as this seed (matching `decapsulate`).
336        let s = arr64(seed)?;
337        let dk = pq::ml_kem_decaps_from_seed(&s);
338        let ek_bytes = pq::ml_kem_ek_of_dk(&dk);
339        Ok((Zeroizing::new(seed.to_vec()), ek_bytes))
340    }
341}
342
343// ============================================================================
344// KMAC256 transcript-binding combiner
345// ============================================================================
346
347/// Fixed 32-byte KMAC256 domain key. A constant (not a secret) — the secrecy
348/// comes from the component shared secrets in the message, per SP 800-185 KMAC.
349const KMAC_DOMAIN_KEY: &[u8; 32] = b"hyprstream HyKEM v1 combiner key";
350/// KMAC256 customization-string prefix (the suite id is appended).
351const KMAC_CUSTOM_PREFIX: &[u8] = b"HyKEM-v1-combiner";
352
353fn update_lp(k: &mut Kmac, b: &[u8]) {
354    k.update(&(b.len() as u32).to_be_bytes());
355    k.update(b);
356}
357
358/// The combiner, parameterized by the suite's string + u16 id so tests can prove
359/// domain separation without a second registered suite.
360fn combine_inner(
361    suite_str: &str,
362    suite_u16: u16,
363    shared_secrets: &[Zeroizing<Vec<u8>>],
364    ciphertexts: &[Vec<u8>],
365    recipient_eks: &[&[u8]],
366) -> Zeroizing<[u8; 32]> {
367    let mut custom = Vec::with_capacity(KMAC_CUSTOM_PREFIX.len() + 1 + suite_str.len());
368    custom.extend_from_slice(KMAC_CUSTOM_PREFIX);
369    custom.push(0x00);
370    custom.extend_from_slice(suite_str.as_bytes());
371
372    let mut k = Kmac::v256(KMAC_DOMAIN_KEY, &custom);
373    k.update(&suite_u16.to_be_bytes());
374    k.update(&(shared_secrets.len() as u32).to_be_bytes());
375    for ss in shared_secrets {
376        update_lp(&mut k, ss);
377    }
378    for ct in ciphertexts {
379        update_lp(&mut k, ct);
380    }
381    for ek in recipient_eks {
382        update_lp(&mut k, ek);
383    }
384
385    let mut out = [0u8; 32];
386    k.finalize(&mut out);
387    Zeroizing::new(out)
388}
389
390fn combine(
391    suite: SuiteId,
392    shared_secrets: &[Zeroizing<Vec<u8>>],
393    ciphertexts: &[Vec<u8>],
394    recipient_eks: &[&[u8]],
395) -> Zeroizing<[u8; 32]> {
396    combine_inner(
397        suite.as_str(),
398        suite.as_u16(),
399        shared_secrets,
400        ciphertexts,
401        recipient_eks,
402    )
403}
404
405/// Focused #553 test seam proving that both the classical and ML-KEM shared
406/// secrets affect the content-key input.  Keeping this beside the private
407/// combiner makes an "ignore the PQ share" mutation visible to the focused
408/// COSE test command as well as this module's broader tests.
409#[cfg(test)]
410pub(crate) fn combiner_is_sensitive_to_every_component_for_cose() -> bool {
411    let suite = SuiteId::HyKemX25519MlKem768;
412    let ciphertexts = vec![vec![9u8; 32], vec![8u8; 1088]];
413    let recipient_eks: Vec<&[u8]> = vec![&[7u8; 32], &[6u8; 1184]];
414    let secret = |first, second| {
415        combine(
416            suite,
417            &[
418                Zeroizing::new(vec![first; 32]),
419                Zeroizing::new(vec![second; 32]),
420            ],
421            &ciphertexts,
422            &recipient_eks,
423        )
424    };
425    let base = secret(1, 2);
426    *base != *secret(0xff, 2) && *base != *secret(1, 0xff)
427}
428
429// ============================================================================
430// Suite-identified wire material + recipient keys
431// ============================================================================
432
433/// One component's encapsulated ciphertext, tagged with its [`KemId`].
434#[derive(Debug, Clone, PartialEq, Eq)]
435pub struct KemShare {
436    pub kem_id: KemId,
437    pub bytes: Vec<u8>,
438}
439
440/// The full set of per-component ciphertexts for a hybrid encapsulation, tagged
441/// with the suite. Replaces the legacy single fixed-ML-KEM-ciphertext field; the
442/// Cap'n Proto field wiring lands in S3/S4.
443#[derive(Debug, Clone, PartialEq, Eq)]
444pub struct HybridKemMaterial {
445    pub suite_id: SuiteId,
446    pub shares: Vec<KemShare>,
447}
448
449impl HybridKemMaterial {
450    /// Canonical length-prefixed encoding:
451    /// `be16(suite_id) ‖ be16(n) ‖ Σ_i (be16(kem_id) ‖ be32(len) ‖ bytes)`.
452    pub fn encode(&self) -> Vec<u8> {
453        let mut out = Vec::new();
454        out.extend_from_slice(&self.suite_id.as_u16().to_be_bytes());
455        out.extend_from_slice(&(self.shares.len() as u16).to_be_bytes());
456        for s in &self.shares {
457            out.extend_from_slice(&s.kem_id.as_u16().to_be_bytes());
458            out.extend_from_slice(&(s.bytes.len() as u32).to_be_bytes());
459            out.extend_from_slice(&s.bytes);
460        }
461        out
462    }
463
464    /// Parse and validate the canonical encoding. Rejects unknown suites/kem-ids,
465    /// truncation, trailing bytes, and any share that does not match the suite's
466    /// component at that position (fixed order).
467    pub fn decode(buf: &[u8]) -> Result<Self> {
468        let mut r = Reader { buf, pos: 0 };
469        let suite_id = SuiteId::from_u16(r.u16()?)
470            .ok_or_else(|| anyhow::anyhow!("unknown hybrid-KEM suite id"))?;
471        let n = r.u16()? as usize;
472        let comps = suite_id.components();
473        if n != comps.len() {
474            bail!(
475                "share count {n} does not match suite {} ({} components)",
476                suite_id.as_str(),
477                comps.len()
478            );
479        }
480        let mut shares = Vec::with_capacity(n);
481        for (i, &want) in comps.iter().enumerate() {
482            let kem_id =
483                KemId::from_u16(r.u16()?).ok_or_else(|| anyhow::anyhow!("unknown kem id"))?;
484            if kem_id != want {
485                bail!(
486                    "share {i} kem id {:?} does not match suite component {:?}",
487                    kem_id,
488                    want
489                );
490            }
491            let len = r.u32()? as usize;
492            let bytes = r.take(len)?.to_vec();
493            if bytes.len() != want.component().ct_len() {
494                bail!(
495                    "share {i} ({:?}) ciphertext length {} != expected {}",
496                    want,
497                    bytes.len(),
498                    want.component().ct_len()
499                );
500            }
501            shares.push(KemShare { kem_id, bytes });
502        }
503        if r.pos != buf.len() {
504            bail!("trailing bytes after hybrid-KEM material");
505        }
506        Ok(Self { suite_id, shares })
507    }
508}
509
510struct Reader<'a> {
511    buf: &'a [u8],
512    pos: usize,
513}
514
515impl<'a> Reader<'a> {
516    fn take(&mut self, n: usize) -> Result<&'a [u8]> {
517        let end = self
518            .pos
519            .checked_add(n)
520            .filter(|e| *e <= self.buf.len())
521            .ok_or_else(|| anyhow::anyhow!("hybrid-KEM material truncated"))?;
522        let s = &self.buf[self.pos..end];
523        self.pos = end;
524        Ok(s)
525    }
526    fn u16(&mut self) -> Result<u16> {
527        let b = self.take(2)?;
528        Ok(u16::from_be_bytes([b[0], b[1]]))
529    }
530    fn u32(&mut self) -> Result<u32> {
531        let b = self.take(4)?;
532        Ok(u32::from_be_bytes([b[0], b[1], b[2], b[3]]))
533    }
534}
535
536/// A recipient's hybrid keypair: per-component decapsulation keys (secret) and
537/// encapsulation keys (public), in suite-component order.
538pub struct RecipientKeypair {
539    pub suite_id: SuiteId,
540    dks: Vec<Zeroizing<Vec<u8>>>,
541    eks: Vec<Vec<u8>>,
542}
543
544/// A recipient's public hybrid material: per-component encapsulation keys in
545/// suite order. This is what an encapsulator needs (published via `#mesh-kem`
546/// for the envelope, or sent in the stream handshake — wiring in S3/S4).
547#[derive(Debug, Clone, PartialEq, Eq)]
548pub struct RecipientPublic {
549    pub suite_id: SuiteId,
550    pub eks: Vec<Vec<u8>>,
551}
552
553impl RecipientKeypair {
554    /// The public half (encapsulation keys), for handing to encapsulators.
555    pub fn public(&self) -> RecipientPublic {
556        RecipientPublic {
557            suite_id: self.suite_id,
558            eks: self.eks.clone(),
559        }
560    }
561
562    /// The per-component decapsulation-key bytes, suite order (e.g. to persist /
563    /// publish via `#mesh-kem`).
564    pub fn decap_keys(&self) -> &[Zeroizing<Vec<u8>>] {
565        &self.dks
566    }
567}
568
569impl RecipientPublic {
570    /// Validate component count, order-by-position, and public-key lengths
571    /// before callers encode or perform KEM work on manually constructed public
572    /// material.
573    pub fn validate(&self) -> Result<()> {
574        let components = self.suite_id.components();
575        if self.eks.len() != components.len() {
576            bail!(
577                "recipient has {} encap keys, suite {} needs {}",
578                self.eks.len(),
579                self.suite_id.as_str(),
580                components.len()
581            );
582        }
583        for (index, (&kem, key)) in components.iter().zip(&self.eks).enumerate() {
584            let expected = kem.component().ek_len();
585            if key.len() != expected {
586                bail!(
587                    "recipient component {index} {:?} encap key length {} != expected {expected}",
588                    kem,
589                    key.len()
590                );
591            }
592        }
593        Ok(())
594    }
595
596    /// Canonical length-prefixed encoding of the recipient's per-component
597    /// encapsulation keys, mirroring [`HybridKemMaterial::encode`]:
598    /// `be16(suite_id) ‖ be16(n) ‖ Σ_i (be16(kem_id) ‖ be32(len) ‖ ek_bytes)`.
599    ///
600    /// This is what the stream client sends as its ephemeral public material
601    /// (`RequestEnvelope.clientKemPublic`, S3 #554), and what `#mesh-kem`
602    /// publishes for the envelope path (S4 #555).
603    pub fn encode(&self) -> Vec<u8> {
604        let comps = self.suite_id.components();
605        let mut out = Vec::new();
606        out.extend_from_slice(&self.suite_id.as_u16().to_be_bytes());
607        out.extend_from_slice(&(self.eks.len() as u16).to_be_bytes());
608        for (i, ek) in self.eks.iter().enumerate() {
609            // Component order is the suite's; tag each ek with its kem id so the
610            // decoder can fail closed on a reordered / wrong-suite encoding.
611            out.extend_from_slice(&comps[i].as_u16().to_be_bytes());
612            out.extend_from_slice(&(ek.len() as u32).to_be_bytes());
613            out.extend_from_slice(ek);
614        }
615        out
616    }
617
618    /// Parse + validate the canonical encoding. Rejects unknown suites/kem-ids,
619    /// wrong component count or order, wrong ek length, truncation, or trailing
620    /// bytes — fail-closed against malformed client public material.
621    pub fn decode(buf: &[u8]) -> Result<Self> {
622        let mut r = Reader { buf, pos: 0 };
623        let suite_id = SuiteId::from_u16(r.u16()?)
624            .ok_or_else(|| anyhow::anyhow!("unknown hybrid-KEM suite id"))?;
625        let n = r.u16()? as usize;
626        let comps = suite_id.components();
627        if n != comps.len() {
628            bail!(
629                "ek count {n} does not match suite {} ({} components)",
630                suite_id.as_str(),
631                comps.len()
632            );
633        }
634        let mut eks = Vec::with_capacity(n);
635        for (i, &want) in comps.iter().enumerate() {
636            let kem_id =
637                KemId::from_u16(r.u16()?).ok_or_else(|| anyhow::anyhow!("unknown kem id"))?;
638            if kem_id != want {
639                bail!(
640                    "ek {i} kem id {:?} does not match suite component {:?}",
641                    kem_id,
642                    want
643                );
644            }
645            let len = r.u32()? as usize;
646            let expected_len = want.component().ek_len();
647            if len != expected_len {
648                bail!(
649                    "ek {i} length {len} does not match {:?} public-key length {expected_len}",
650                    want
651                );
652            }
653            eks.push(r.take(len)?.to_vec());
654        }
655        if r.pos != buf.len() {
656            bail!("trailing bytes after recipient public material");
657        }
658        let recipient = Self { suite_id, eks };
659        recipient.validate()?;
660        Ok(recipient)
661    }
662}
663
664// ============================================================================
665// High-level hybrid KEM API
666// ============================================================================
667
668/// Generate a fresh recipient keypair for `suite` (one component keypair each).
669pub fn generate_recipient(suite: SuiteId) -> Result<RecipientKeypair> {
670    let mut dks = Vec::new();
671    let mut eks = Vec::new();
672    for &kem in suite.components() {
673        let (dk, ek) = kem.component().generate_recipient_keypair()?;
674        dks.push(dk);
675        eks.push(ek);
676    }
677    Ok(RecipientKeypair {
678        suite_id: suite,
679        dks,
680        eks,
681    })
682}
683
684/// Deterministically build a recipient keypair for `suite` from per-component
685/// seeds — one per suite component, in suite order, each of that component's
686/// [`KemComponent::seed_len`].
687///
688/// Used for stable identity keys such as `#mesh-kem` (whose component seeds are
689/// HKDF-derived from the node Ed25519 root, see
690/// `crate::node_identity::derive_mesh_kem_recipient`), which MUST be stable
691/// across restarts — unlike [`generate_recipient`], which draws fresh OS
692/// randomness each call.
693pub fn recipient_from_seeds(suite: SuiteId, seeds: &[&[u8]]) -> Result<RecipientKeypair> {
694    let comps = suite.components();
695    if seeds.len() != comps.len() {
696        bail!(
697            "suite {} needs {} component seeds, got {}",
698            suite.as_str(),
699            comps.len(),
700            seeds.len()
701        );
702    }
703    let mut dks = Vec::with_capacity(comps.len());
704    let mut eks = Vec::with_capacity(comps.len());
705    for (i, &kem) in comps.iter().enumerate() {
706        let c = kem.component();
707        if seeds[i].len() != c.seed_len() {
708            bail!(
709                "suite {} component {:?} seed length {} != expected {}",
710                suite.as_str(),
711                kem,
712                seeds[i].len(),
713                c.seed_len()
714            );
715        }
716        let (dk, ek) = c.recipient_from_seed(seeds[i])?;
717        dks.push(dk);
718        eks.push(ek);
719    }
720    Ok(RecipientKeypair {
721        suite_id: suite,
722        dks,
723        eks,
724    })
725}
726
727/// Encapsulate to a recipient's public material, returning the wire
728/// [`HybridKemMaterial`] (the per-component ciphertexts) and the combined 32-byte
729/// shared secret.
730pub fn encapsulate_to(
731    recipient: &RecipientPublic,
732) -> Result<(HybridKemMaterial, Zeroizing<[u8; 32]>)> {
733    recipient.validate()?;
734    let suite = recipient.suite_id;
735    let comps = suite.components();
736
737    let mut shares = Vec::with_capacity(comps.len());
738    let mut sss = Vec::with_capacity(comps.len());
739    let mut cts = Vec::with_capacity(comps.len());
740    let mut eks: Vec<&[u8]> = Vec::with_capacity(comps.len());
741
742    for (i, &kem) in comps.iter().enumerate() {
743        let ek = &recipient.eks[i];
744        let (ct, ss) = kem.component().encapsulate(ek)?;
745        cts.push(ct.clone());
746        shares.push(KemShare {
747            kem_id: kem,
748            bytes: ct,
749        });
750        sss.push(ss);
751        eks.push(ek.as_slice());
752    }
753
754    let secret = combine(suite, &sss, &cts, &eks);
755    Ok((
756        HybridKemMaterial {
757            suite_id: suite,
758            shares,
759        },
760        secret,
761    ))
762}
763
764/// Decapsulate hybrid material with a recipient keypair, recovering the same
765/// combined 32-byte shared secret. Fails closed on suite/share mismatch.
766pub fn decapsulate(
767    recipient: &RecipientKeypair,
768    material: &HybridKemMaterial,
769) -> Result<Zeroizing<[u8; 32]>> {
770    let suite = recipient.suite_id;
771    if material.suite_id != suite {
772        bail!(
773            "material suite {} != recipient suite {}",
774            material.suite_id.as_str(),
775            suite.as_str()
776        );
777    }
778    let comps = suite.components();
779    if material.shares.len() != comps.len() || recipient.dks.len() != comps.len() {
780        bail!("share/key count does not match suite {}", suite.as_str());
781    }
782
783    let mut sss = Vec::with_capacity(comps.len());
784    let mut cts = Vec::with_capacity(comps.len());
785    let mut eks: Vec<&[u8]> = Vec::with_capacity(comps.len());
786
787    for (i, &kem) in comps.iter().enumerate() {
788        let share = &material.shares[i];
789        if share.kem_id != kem {
790            bail!(
791                "share {i} kem {:?} != suite component {:?}",
792                share.kem_id,
793                kem
794            );
795        }
796        let ss = kem
797            .component()
798            .decapsulate(&recipient.dks[i], &share.bytes)?;
799        sss.push(ss);
800        cts.push(share.bytes.clone());
801        eks.push(recipient.eks[i].as_slice());
802    }
803
804    Ok(combine(suite, &sss, &cts, &eks))
805}
806
807// ============================================================================
808// #mesh-kem trust store (kid-anchored recipient public keys)
809// ============================================================================
810
811/// Resolves the anchored hybrid-KEM recipient public material for a peer's
812/// Ed25519 signer identity (its `#mesh-kem` keyAgreement key).
813///
814/// The confidentiality-side mirror of [`crate::envelope::PqTrustStore`]: the
815/// binding is established out-of-band (DID `keyAgreement` resolution / peer
816/// attestation), NEVER self-asserted on the wire. **Fail-closed:** an unanchored
817/// peer returns `None`, and callers MUST reject rather than fall back to a
818/// classical or self-asserted key (epic #550 principle 1 — mandatory hybrid, no
819/// in-band downgrade).
820pub trait KemTrustStore: Send + Sync {
821    /// The anchored `#mesh-kem` recipient public bound to `ed25519_pubkey`, or
822    /// `None` if unknown (caller fails closed).
823    fn kem_recipient_for(&self, ed25519_pubkey: &[u8; 32]) -> Option<RecipientPublic>;
824}
825
826/// In-memory kid-anchored `#mesh-kem` trust store: Ed25519 signer identity →
827/// anchored hybrid-KEM [`RecipientPublic`]. Bindings come from the node's own
828/// hybrid identity and from attested peer identities (their resolved DID
829/// `keyAgreement`), established out-of-band — never from wire-asserted material.
830#[derive(Default, Clone)]
831pub struct KeyedKemTrustStore {
832    bindings: std::collections::HashMap<[u8; 32], RecipientPublic>,
833}
834
835impl KeyedKemTrustStore {
836    /// Create an empty store.
837    pub fn new() -> Self {
838        Self {
839            bindings: std::collections::HashMap::new(),
840        }
841    }
842
843    /// Bind an Ed25519 signer identity to its anchored `#mesh-kem` recipient public.
844    pub fn bind(&mut self, ed25519_pubkey: [u8; 32], recipient: RecipientPublic) {
845        self.bindings.insert(ed25519_pubkey, recipient);
846    }
847
848    /// Number of bindings.
849    pub fn len(&self) -> usize {
850        self.bindings.len()
851    }
852
853    /// Whether the store has no bindings.
854    pub fn is_empty(&self) -> bool {
855        self.bindings.is_empty()
856    }
857}
858
859impl KemTrustStore for KeyedKemTrustStore {
860    fn kem_recipient_for(&self, ed25519_pubkey: &[u8; 32]) -> Option<RecipientPublic> {
861        self.bindings.get(ed25519_pubkey).cloned()
862    }
863}
864
865// ============================================================================
866// #mesh-kem prekey seam (forward secrecy for the one-shot envelope, S4 / #555)
867// ============================================================================
868
869/// A short-lived, rotated `#mesh-kem` recipient prekey.
870///
871/// The one-shot request envelope (#555) encapsulates to a *published* recipient
872/// key, so — unlike streams — it cannot get forward secrecy from a per-session
873/// ephemeral key. The standard remedy (X3DH-style) is to publish short-lived
874/// rotated prekeys and drop the matching decapsulation key after expiry, so a
875/// later key compromise cannot decrypt past envelopes. This type is the seam:
876/// the publisher advertises the current `recipient` + `key_id`; the decryptor
877/// keeps the matching [`RecipientKeypair`] only until `not_after_unix_ms`.
878///
879/// The full rotation scheduler + keystore are follow-up work (tracked under
880/// #552); this fixes the wire/identity shape that #555 binds to.
881#[derive(Debug, Clone, PartialEq, Eq)]
882pub struct KemPrekey {
883    /// Stable id of this prekey, bound into the envelope so the decryptor can
884    /// select the matching decapsulation key.
885    pub key_id: [u8; 16],
886    /// The rotated recipient public material (suite + encap keys).
887    pub recipient: RecipientPublic,
888    /// Expiry (Unix ms). The decryptor MUST drop the matching decap key after
889    /// this instant, which is what gives the envelope forward secrecy across
890    /// rotation.
891    pub not_after_unix_ms: i64,
892}
893
894#[cfg(test)]
895#[allow(clippy::unwrap_used, clippy::expect_used)]
896mod tests {
897    use super::*;
898
899    // ---- per-component roundtrips ----
900
901    fn component_roundtrip(c: &dyn KemComponent) {
902        let (dk, ek) = c.generate_recipient_keypair().unwrap();
903        assert_eq!(ek.len(), c.ek_len());
904        let (ct, ss_enc) = c.encapsulate(&ek).unwrap();
905        assert_eq!(ct.len(), c.ct_len());
906        assert_eq!(ss_enc.len(), c.ss_len());
907        let ss_dec = c.decapsulate(&dk, &ct).unwrap();
908        assert_eq!(
909            &*ss_enc, &*ss_dec,
910            "component encap/decap shared secret must agree"
911        );
912    }
913
914    #[test]
915    fn x25519_component_roundtrip() {
916        component_roundtrip(&X25519Kem);
917    }
918
919    #[test]
920    fn mlkem768_component_roundtrip() {
921        component_roundtrip(&MlKem768Kem);
922    }
923
924    #[test]
925    fn mlkem_dk_seed_roundtrip() {
926        // The decap key serializes to a 64-byte seed and back.
927        let (dk, _ek) = crate::crypto::pq::ml_kem_generate_keypair();
928        let seed = crate::crypto::pq::ml_kem_dk_to_seed(&dk).expect("generated key is seed-backed");
929        let dk2 = crate::crypto::pq::ml_kem_decaps_from_seed(&seed);
930        assert_eq!(
931            crate::crypto::pq::ml_kem_ek_of_dk(&dk),
932            crate::crypto::pq::ml_kem_ek_of_dk(&dk2)
933        );
934    }
935
936    // ---- full suite roundtrip ----
937
938    #[test]
939    fn suite_roundtrip_secrets_agree() {
940        let suite = SuiteId::HyKemX25519MlKem768;
941        let recipient = generate_recipient(suite).unwrap();
942        let (material, ss_enc) = encapsulate_to(&recipient.public()).unwrap();
943        assert_eq!(material.suite_id, suite);
944        assert_eq!(material.shares.len(), 2);
945        let ss_dec = decapsulate(&recipient, &material).unwrap();
946        assert_eq!(
947            *ss_enc, *ss_dec,
948            "suite encap/decap shared secret must agree"
949        );
950    }
951
952    #[test]
953    fn distinct_encapsulations_differ() {
954        // Fresh ephemeral X25519 each time → different secret & material.
955        let recipient = generate_recipient(SuiteId::HyKemX25519MlKem768).unwrap();
956        let (m1, s1) = encapsulate_to(&recipient.public()).unwrap();
957        let (m2, s2) = encapsulate_to(&recipient.public()).unwrap();
958        assert_ne!(*s1, *s2);
959        assert_ne!(m1, m2);
960    }
961
962    // ---- secure-if-one-holds (combiner) ----
963
964    fn z(v: &[u8]) -> Zeroizing<Vec<u8>> {
965        Zeroizing::new(v.to_vec())
966    }
967
968    #[test]
969    fn combiner_changes_when_any_single_ss_changes() {
970        // The "secure-if-one-holds" surface: perturbing ANY single component's
971        // shared secret (others fixed) changes the combined key — so an adversary
972        // missing one ss cannot predict the output.
973        let suite = SuiteId::HyKemX25519MlKem768;
974        let cts = vec![vec![9u8; 32], vec![8u8; 1088]];
975        let ek_refs: Vec<&[u8]> = vec![&[7u8; 32], &[6u8; 1184]];
976
977        let base = combine(suite, &[z(&[1u8; 32]), z(&[2u8; 32])], &cts, &ek_refs);
978        // change ONLY component 0's ss
979        let only_first = combine(suite, &[z(&[0xff; 32]), z(&[2u8; 32])], &cts, &ek_refs);
980        // change ONLY component 1's ss
981        let only_second = combine(suite, &[z(&[1u8; 32]), z(&[0xff; 32])], &cts, &ek_refs);
982
983        assert_ne!(
984            *base, *only_first,
985            "changing component 0 ss must change the key"
986        );
987        assert_ne!(
988            *base, *only_second,
989            "changing component 1 ss must change the key"
990        );
991    }
992
993    #[test]
994    fn combiner_is_deterministic() {
995        let suite = SuiteId::HyKemX25519MlKem768;
996        let sss = vec![z(&[3u8; 32]), z(&[4u8; 32])];
997        let cts = vec![vec![1u8; 32], vec![2u8; 1088]];
998        let ek_refs: Vec<&[u8]> = vec![&[5u8; 32], &[6u8; 1184]];
999        let a = combine(suite, &sss, &cts, &ek_refs);
1000        let b = combine(suite, &sss, &cts, &ek_refs);
1001        assert_eq!(*a, *b);
1002    }
1003
1004    #[test]
1005    fn combiner_binds_ciphertexts_and_eks() {
1006        let suite = SuiteId::HyKemX25519MlKem768;
1007        let sss = vec![z(&[3u8; 32]), z(&[4u8; 32])];
1008        let cts = vec![vec![1u8; 32], vec![2u8; 1088]];
1009        let cts2 = vec![vec![1u8; 32], vec![0u8; 1088]]; // one ct byte differs
1010        let ek_refs: Vec<&[u8]> = vec![&[5u8; 32], &[6u8; 1184]];
1011        let ek_refs2: Vec<&[u8]> = vec![&[5u8; 32], &[7u8; 1184]]; // one ek differs
1012        let base = combine(suite, &sss, &cts, &ek_refs);
1013        assert_ne!(
1014            *base,
1015            *combine(suite, &sss, &cts2, &ek_refs),
1016            "ct must be bound"
1017        );
1018        assert_ne!(
1019            *base,
1020            *combine(suite, &sss, &cts, &ek_refs2),
1021            "ek must be bound"
1022        );
1023    }
1024
1025    #[test]
1026    fn suite_domain_separation() {
1027        // Same secrets/cts/eks under two different suite ids → different keys.
1028        let sss = vec![z(&[3u8; 32]), z(&[4u8; 32])];
1029        let cts = vec![vec![1u8; 32], vec![2u8; 1088]];
1030        let ek_refs: Vec<&[u8]> = vec![&[5u8; 32], &[6u8; 1184]];
1031        let a = combine_inner("HyKEM-X25519-MLKEM768", 0x0001, &sss, &cts, &ek_refs);
1032        let b = combine_inner(
1033            "HyKEM-X25519-MLKEM768-McEliece6960119",
1034            0x0002,
1035            &sss,
1036            &cts,
1037            &ek_refs,
1038        );
1039        assert_ne!(
1040            *a, *b,
1041            "different suite id must domain-separate the combined key"
1042        );
1043    }
1044
1045    // ---- tamper / failure ----
1046
1047    #[test]
1048    fn tampered_ciphertext_changes_or_fails() {
1049        let recipient = generate_recipient(SuiteId::HyKemX25519MlKem768).unwrap();
1050        let (mut material, ss_enc) = encapsulate_to(&recipient.public()).unwrap();
1051        // flip a byte in the ML-KEM ciphertext (component 1)
1052        material.shares[1].bytes[0] ^= 0xff;
1053        // ML-KEM implicit rejection yields a *different* ss (no error), so the
1054        // combined secret must differ from the encapsulator's.
1055        let ss_dec = decapsulate(&recipient, &material).unwrap();
1056        assert_ne!(*ss_enc, *ss_dec);
1057    }
1058
1059    #[test]
1060    fn wrong_recipient_fails_to_agree() {
1061        let r1 = generate_recipient(SuiteId::HyKemX25519MlKem768).unwrap();
1062        let r2 = generate_recipient(SuiteId::HyKemX25519MlKem768).unwrap();
1063        let (material, ss_enc) = encapsulate_to(&r1.public()).unwrap();
1064        let ss_dec = decapsulate(&r2, &material).unwrap();
1065        assert_ne!(*ss_enc, *ss_dec);
1066    }
1067
1068    // ---- wire encode/decode ----
1069
1070    #[test]
1071    fn material_encode_decode_roundtrip() {
1072        let recipient = generate_recipient(SuiteId::HyKemX25519MlKem768).unwrap();
1073        let (material, _) = encapsulate_to(&recipient.public()).unwrap();
1074        let enc = material.encode();
1075        let dec = HybridKemMaterial::decode(&enc).unwrap();
1076        assert_eq!(material, dec);
1077    }
1078
1079    #[test]
1080    fn decode_rejects_malformed() {
1081        let recipient = generate_recipient(SuiteId::HyKemX25519MlKem768).unwrap();
1082        let (material, _) = encapsulate_to(&recipient.public()).unwrap();
1083        let enc = material.encode();
1084        // truncated
1085        assert!(HybridKemMaterial::decode(&enc[..enc.len() - 1]).is_err());
1086        // trailing byte
1087        let mut extra = enc.clone();
1088        extra.push(0);
1089        assert!(HybridKemMaterial::decode(&extra).is_err());
1090        // unknown suite id
1091        let mut bad_suite = enc.clone();
1092        bad_suite[0] = 0xff;
1093        bad_suite[1] = 0xff;
1094        assert!(HybridKemMaterial::decode(&bad_suite).is_err());
1095        // wrong ML-KEM ct length (shrink the declared len → trailing/῾len mismatch)
1096        let mut wrong_len = enc.clone();
1097        // component 0 share starts at offset 4 (suite u16 + count u16); its len u32
1098        // is at offset 6..10. Corrupt the second component instead is complex; just
1099        // assert a single-byte flip in the count breaks it.
1100        wrong_len[3] = 0x05;
1101        assert!(HybridKemMaterial::decode(&wrong_len).is_err());
1102    }
1103
1104    // ---- KAT regression pin ----
1105    //
1106    // Pins the combiner output over fixed inputs so a future refactor cannot
1107    // silently change the construction. Value computed by this implementation.
1108    #[test]
1109    fn combiner_kat() {
1110        let sss = vec![z(&[0xaa; 32]), z(&[0xbb; 32])];
1111        let cts = vec![vec![0xcc; 32], vec![0xdd; 1088]];
1112        let ek_refs: Vec<&[u8]> = vec![&[0xee; 32], &[0x11; 1184]];
1113        let out = combine(SuiteId::HyKemX25519MlKem768, &sss, &cts, &ek_refs);
1114        let got = hex::encode(*out);
1115        // Pinned output of the KMAC256 combiner over the fixed inputs above. A
1116        // change here means the construction (KMAC key/customization, field order,
1117        // or length-prefixing) was altered — review before updating.
1118        const KAT: &str = "00f1efc789785e571aa6e985a9f2567cca39dfc7dc272b514380b212524ce031";
1119        assert_eq!(got, KAT, "combiner KAT changed — construction altered!");
1120    }
1121
1122    // ---- deterministic seed-based recipient (stable identity keys, S1) ----
1123
1124    #[test]
1125    fn recipient_from_seeds_is_deterministic_and_roundtrips() {
1126        let suite = SuiteId::HyKemX25519MlKem768;
1127        let x_seed = [0x07u8; 32];
1128        let m_seed = [0x09u8; 64];
1129        let seeds: [&[u8]; 2] = [&x_seed, &m_seed];
1130
1131        let kp1 = recipient_from_seeds(suite, &seeds).unwrap();
1132        let kp2 = recipient_from_seeds(suite, &seeds).unwrap();
1133        // Same seeds → identical published encap keys (stable across restarts).
1134        assert_eq!(kp1.public(), kp2.public());
1135
1136        // The deterministic recipient interoperates with encap/decap.
1137        let (material, ss_enc) = encapsulate_to(&kp1.public()).unwrap();
1138        let ss_dec = decapsulate(&kp2, &material).unwrap();
1139        assert_eq!(*ss_enc, *ss_dec);
1140    }
1141
1142    #[test]
1143    fn recipient_from_seeds_rejects_wrong_lengths() {
1144        let suite = SuiteId::HyKemX25519MlKem768;
1145        let bad_x: [&[u8]; 2] = [&[0u8; 31], &[0u8; 64]];
1146        assert!(recipient_from_seeds(suite, &bad_x).is_err());
1147        let bad_m: [&[u8]; 2] = [&[0u8; 32], &[0u8; 63]];
1148        assert!(recipient_from_seeds(suite, &bad_m).is_err());
1149        let wrong_count: [&[u8]; 1] = [&[0u8; 32]];
1150        assert!(recipient_from_seeds(suite, &wrong_count).is_err());
1151    }
1152
1153    // ---- #mesh-kem trust store (fail-closed, S1) ----
1154
1155    #[test]
1156    fn kem_trust_store_binds_and_fails_closed() {
1157        let suite = SuiteId::HyKemX25519MlKem768;
1158        let kp = generate_recipient(suite).unwrap();
1159        let id = [0x42u8; 32];
1160
1161        let mut store = KeyedKemTrustStore::new();
1162        assert!(store.is_empty());
1163        assert!(
1164            store.kem_recipient_for(&id).is_none(),
1165            "unanchored identity must resolve to None (fail closed)"
1166        );
1167
1168        store.bind(id, kp.public());
1169        assert_eq!(store.len(), 1);
1170        assert_eq!(store.kem_recipient_for(&id), Some(kp.public()));
1171        assert!(
1172            store.kem_recipient_for(&[0x43u8; 32]).is_none(),
1173            "a different identity stays unanchored"
1174        );
1175    }
1176}
1177
1178#[cfg(test)]
1179#[allow(clippy::unwrap_used)]
1180mod recipient_public_codec_tests {
1181    use super::*;
1182
1183    #[test]
1184    fn recipient_public_roundtrip() {
1185        let kp = generate_recipient(SuiteId::HyKemX25519MlKem768).unwrap();
1186        let pubmat = kp.public();
1187        let enc = pubmat.encode();
1188        let dec = RecipientPublic::decode(&enc).unwrap();
1189        assert_eq!(dec, pubmat);
1190        assert_eq!(dec.encode(), enc, "encoding is canonical");
1191        // The decoded public actually works for encapsulation.
1192        let (material, _secret) = encapsulate_to(&dec).unwrap();
1193        assert_eq!(material.suite_id, SuiteId::HyKemX25519MlKem768);
1194    }
1195
1196    #[test]
1197    fn recipient_public_rejects_malformed() {
1198        assert!(RecipientPublic::decode(&[]).is_err());
1199        assert!(RecipientPublic::decode(b"garbage bytes here").is_err());
1200        let kp = generate_recipient(SuiteId::HyKemX25519MlKem768).unwrap();
1201        // Truncation.
1202        let mut enc = kp.public().encode();
1203        enc.truncate(enc.len() - 1);
1204        assert!(RecipientPublic::decode(&enc).is_err());
1205        // Trailing bytes.
1206        let mut enc2 = kp.public().encode();
1207        enc2.push(0xff);
1208        assert!(RecipientPublic::decode(&enc2).is_err());
1209    }
1210
1211    #[test]
1212    fn recipient_public_rejects_wrong_ek_length() {
1213        let kp = generate_recipient(SuiteId::HyKemX25519MlKem768).unwrap();
1214        let mut bad = kp.public();
1215        bad.eks[0] = vec![0u8; 31]; // wrong X25519 ek length (must be 32)
1216        assert!(RecipientPublic::decode(&bad.encode()).is_err());
1217    }
1218}