Skip to main content

hyprstream_rpc/crypto/
event_crypto.rs

1//! Cryptographic primitives for EventService transport.
2//!
3//! The controller supplies a fresh random secret for every committed group
4//! epoch. Confidential event objects never use that secret directly as an AEAD
5//! key: they derive session-scoped sender/track keys, bind publisher/track/
6//! session/membership-version/epoch/sequence into AAD, and use an injective
7//! counter nonce within each CSPRNG-generated session key domain. The module
8//! retains legacy low-level wrap helpers for compatibility, but the surviving
9//! EventService path distributes epochs exclusively through per-member HyKEM/COSE
10//! grants in `group_key`.
11//!
12//! Key commitment provides fast wrong-key rejection before AES-256-GCM
13//! decryption. Publisher signature transcripts bind the plaintext and epoch
14//! coordinates and are consumed by the mandatory Ed25519 + ML-DSA-65 composite
15//! attestation in `events`.
16
17use aes_gcm::{
18    aead::{Aead, AeadCore, KeyInit, Payload},
19    Aes256Gcm, Nonce,
20};
21use subtle::ConstantTimeEq;
22use zeroize::Zeroizing;
23
24use super::backend::{derive_key, keyed_mac};
25
26// ============================================================================
27// EventPrivacy Mode
28// ============================================================================
29
30/// Privacy mode for event transport.
31#[derive(Clone, Copy, Debug, PartialEq, Eq)]
32pub enum EventPrivacy {
33    /// No group-key encryption: payload is written to the moq track unmodified
34    /// (wire-identical to the pre-EV1 plaintext event bus). Use for the
35    /// public/interop firehose profile, or any event with no confidentiality
36    /// requirement. `EventPublisher::new`/`new_with_oid`/`new_oid_only`
37    /// default to this mode.
38    Public,
39    /// All events on one broadcast stream. StreamService learns nothing about interests.
40    ZeroKnowledge,
41    /// Per-prefix direct circuits. Efficient but reveals topology.
42    LimitedKnowledge,
43}
44
45// ============================================================================
46// AES-256-GCM Helpers
47// ============================================================================
48
49/// Encrypt with AES-256-GCM. Returns ciphertext (includes auth tag).
50fn aes_gcm_encrypt(
51    key: &[u8; 32],
52    nonce: &[u8; 12],
53    plaintext: &[u8],
54    aad: &[u8],
55) -> Result<Vec<u8>, String> {
56    let cipher = Aes256Gcm::new(key.into());
57    let payload = Payload {
58        msg: plaintext,
59        aad,
60    };
61    cipher
62        .encrypt(Nonce::from_slice(nonce), payload)
63        .map_err(|_| "AES-GCM encrypt failed".to_owned())
64}
65
66/// Decrypt with AES-256-GCM. Returns plaintext.
67fn aes_gcm_decrypt(
68    key: &[u8; 32],
69    nonce: &[u8; 12],
70    ciphertext: &[u8],
71    aad: &[u8],
72) -> Result<Vec<u8>, String> {
73    let cipher = Aes256Gcm::new(key.into());
74    let payload = Payload {
75        msg: ciphertext,
76        aad,
77    };
78    cipher
79        .decrypt(Nonce::from_slice(nonce), payload)
80        .map_err(|_| "AES-GCM decrypt failed".to_owned())
81}
82
83/// Generate a random 12-byte AES-GCM nonce from OsRng.
84fn random_nonce() -> [u8; 12] {
85    // Idiomatic aes-gcm nonce generation (CodeQL-recognized CSPRNG).
86    // Equivalent to the prior OsRng.fill_bytes(&mut [0u8;12]) — the value
87    // was always overwritten by OsRng — but without the init literal that
88    // tripped rust/hard-coded-cryptographic-value (false-positive root fix).
89    Aes256Gcm::generate_nonce(&mut rand::rngs::OsRng).into()
90}
91
92// ============================================================================
93// Group Key Wrapping
94// ============================================================================
95
96/// Build length-prefixed AAD for group key wrapping.
97///
98/// Format: `u32_le(len(tenant)) || tenant || u32_le(len(sub_hash)) || sub_hash ||
99/// u32_le(len(prefix)) || prefix`
100///
101/// Length prefixing prevents ambiguity where different tenant/sub_hash/prefix
102/// splits produce the same concatenated bytes. Binding the tenant prevents a
103/// wrapped key for one tenant's event prefix from being replayed in another.
104pub fn build_wrap_aad(tenant: &str, sub_hash: &[u8; 32], prefix: &str) -> Vec<u8> {
105    let mut aad = Vec::with_capacity(12 + tenant.len() + 32 + prefix.len());
106    aad.extend_from_slice(&(tenant.len() as u32).to_le_bytes());
107    aad.extend_from_slice(tenant.as_bytes());
108    aad.extend_from_slice(&(sub_hash.len() as u32).to_le_bytes());
109    aad.extend_from_slice(sub_hash);
110    aad.extend_from_slice(&(prefix.len() as u32).to_le_bytes());
111    aad.extend_from_slice(prefix.as_bytes());
112    aad
113}
114
115// ============================================================================
116// Keyed-topic AEAD (EV3 — confidential profile)
117// ============================================================================
118
119/// Domain separator for the keyed-topic AAD (EV3).
120const TOPIC_AAD_DOMAIN: &str = "hyprstream event-topic-aad v1";
121
122/// Build length-prefixed AAD binding the **keyed routing leaf + epoch** (EV3).
123///
124/// When the semantic topic moves under the payload AEAD (replacing the cleartext
125/// prefix-as-AAD), the AAD MUST bind the keyed topic leaf and the epoch, so a
126/// ciphertext from `(topic A, epoch N)` replayed onto `(topic B, epoch M)` is
127/// rejected by AEAD authentication. Without this binding, replacing the prefix
128/// with an opaque keyed leaf would invite cross-topic / cross-epoch reuse.
129///
130/// Format: `domain || u32_le(len(leaf)) || leaf || epoch_le`
131/// (`leaf` is the hex [`crate::event_subject::topic_leaf`] segment).
132pub fn build_topic_aad(keyed_leaf: &str, epoch: u64) -> Vec<u8> {
133    let leaf = keyed_leaf.as_bytes();
134    let mut aad = Vec::with_capacity(TOPIC_AAD_DOMAIN.len() + 4 + leaf.len() + 8);
135    aad.extend_from_slice(TOPIC_AAD_DOMAIN.as_bytes());
136    aad.extend_from_slice(&(leaf.len() as u32).to_le_bytes());
137    aad.extend_from_slice(leaf);
138    aad.extend_from_slice(&epoch.to_le_bytes());
139    aad
140}
141
142/// Encrypt an event with the **keyed-topic + epoch** bound into the AAD (EV3
143/// confidential profile). Otherwise identical to [`encrypt_event`].
144///
145/// Use when publishing under a [`crate::event_subject::topic_leaf`] routing key;
146/// the recipient reconstructs the same `keyed_leaf` + `epoch` for
147/// [`decrypt_event_keyed`]. The semantic topic name travels inside the encrypted
148/// payload, not in the AAD.
149pub fn encrypt_event_keyed(
150    group_key: &[u8; 32],
151    keyed_leaf: &str,
152    epoch: u64,
153    plaintext: &[u8],
154    _privacy_mode: EventPrivacy,
155) -> Result<(Vec<u8>, Vec<u8>, [u8; 12], [u8; 16]), String> {
156    let nonce = random_nonce();
157    let commitment = key_commitment(group_key, &nonce);
158    let aad = build_topic_aad(keyed_leaf, epoch);
159    let aead_output = aes_gcm_encrypt(group_key, &nonce, plaintext, &aad)?;
160    if aead_output.len() < 16 {
161        return Err("AEAD output too short".to_owned());
162    }
163    let split = aead_output.len() - 16;
164    let ciphertext = aead_output[..split].to_vec();
165    let tag = aead_output[split..].to_vec();
166    Ok((tag, ciphertext, nonce, commitment))
167}
168
169/// Decrypt an event encrypted with [`encrypt_event_keyed`] (keyed-topic + epoch
170/// AAD). The caller must supply the same `keyed_leaf` + `epoch` used at encrypt
171/// time — a mismatch (cross-topic or cross-epoch replay) fails AEAD auth.
172pub fn decrypt_event_keyed(
173    group_key: &[u8; 32],
174    nonce: &[u8; 12],
175    tag: &[u8],
176    ciphertext: &[u8],
177    keyed_leaf: &str,
178    epoch: u64,
179) -> Result<Vec<u8>, String> {
180    let mut combined = Vec::with_capacity(ciphertext.len() + tag.len());
181    combined.extend_from_slice(ciphertext);
182    combined.extend_from_slice(tag);
183    let aad = build_topic_aad(keyed_leaf, epoch);
184    aes_gcm_decrypt(group_key, nonce, &combined, &aad)
185}
186
187/// Derive a wrap key from DH shared secret + pubkey XOR salt.
188///
189/// Follows the `derive_notification_keys()` convention:
190/// - IKM: shared_secret || salt (where salt = XOR of our_pubkey and their_pubkey)
191/// - Context: event-transport-specific domain separation string
192pub fn derive_wrap_key(
193    our_secret: &[u8; 32],
194    their_pubkey: &[u8; 32],
195    our_pubkey: &[u8; 32],
196) -> Zeroizing<[u8; 32]> {
197    // XOR public keys for salt (binds both parties' keys to the derivation)
198    let mut salt = [0u8; 32];
199    for i in 0..32 {
200        salt[i] = our_pubkey[i] ^ their_pubkey[i];
201    }
202
203    // Build IKM: shared_secret || salt
204    let mut ikm = [0u8; 64];
205    ikm[..32].copy_from_slice(our_secret);
206    ikm[32..64].copy_from_slice(&salt);
207
208    let key = derive_key("hyprstream event-transport v1 wrap-key", &ikm);
209
210    // Zeroize IKM containing secret material (use zeroize crate to prevent elision)
211    use zeroize::Zeroize;
212    ikm.zeroize();
213
214    Zeroizing::new(key)
215}
216
217/// Wrap a group key for a specific subscriber.
218///
219/// Returns `(nonce || ciphertext)` as an opaque blob suitable for wire transport.
220///
221/// # Arguments
222///
223/// * `wrap_key` - 32-byte key derived from `derive_wrap_key()`
224/// * `group_key` - 32-byte group key to wrap
225/// * `tenant` - verified tenant/domain (bound via AAD)
226/// * `sub_hash` - 32-byte subscriber identity hash (bound via AAD)
227/// * `prefix` - Topic prefix string (bound via AAD)
228pub fn wrap_group_key(
229    wrap_key: &[u8; 32],
230    group_key: &[u8; 32],
231    tenant: &str,
232    sub_hash: &[u8; 32],
233    prefix: &str,
234) -> Result<Vec<u8>, String> {
235    let nonce = random_nonce();
236    let aad = build_wrap_aad(tenant, sub_hash, prefix);
237    let ciphertext = aes_gcm_encrypt(wrap_key, &nonce, group_key, &aad)?;
238
239    // Prepend nonce to ciphertext
240    let mut blob = Vec::with_capacity(12 + ciphertext.len());
241    blob.extend_from_slice(&nonce);
242    blob.extend_from_slice(&ciphertext);
243    Ok(blob)
244}
245
246/// Unwrap a group key blob.
247///
248/// Expects `wrapped_blob` in the format produced by `wrap_group_key()`:
249/// `nonce (12 bytes) || ciphertext`.
250///
251/// # Arguments
252///
253/// * `wrap_key` - 32-byte key derived from `derive_wrap_key()`
254/// * `wrapped_blob` - Opaque blob from `wrap_group_key()`
255/// * `tenant` - verified tenant/domain (must match wrapping AAD)
256/// * `sub_hash` - 32-byte subscriber identity hash (must match wrapping AAD)
257/// * `prefix` - Topic prefix string (must match wrapping AAD)
258pub fn unwrap_group_key(
259    wrap_key: &[u8; 32],
260    wrapped_blob: &[u8],
261    tenant: &str,
262    sub_hash: &[u8; 32],
263    prefix: &str,
264) -> Result<Zeroizing<[u8; 32]>, String> {
265    if wrapped_blob.len() < 12 {
266        return Err("wrapped blob too short".to_owned());
267    }
268
269    let nonce: [u8; 12] = wrapped_blob[..12]
270        .try_into()
271        .map_err(|_| "nonce extraction failed")?;
272    let ciphertext = &wrapped_blob[12..];
273
274    let aad = build_wrap_aad(tenant, sub_hash, prefix);
275    let plaintext = aes_gcm_decrypt(wrap_key, &nonce, ciphertext, &aad)?;
276
277    if plaintext.len() != 32 {
278        return Err(format!(
279            "unwrapped key wrong length: expected 32, got {}",
280            plaintext.len()
281        ));
282    }
283
284    let mut key = Zeroizing::new([0u8; 32]);
285    key.copy_from_slice(&plaintext);
286    Ok(key)
287}
288
289// ============================================================================
290// Event Encryption / Decryption
291// ============================================================================
292
293/// Compute key commitment: `keyed_mac(group_key, nonce)[0..16]`.
294///
295/// Provides a committing property for the AEAD scheme. Receivers check this
296/// commitment before attempting decryption, enabling fast rejection of events
297/// encrypted under a different group key.
298pub fn key_commitment(group_key: &[u8; 32], nonce: &[u8; 12]) -> [u8; 16] {
299    let mac = keyed_mac(group_key, nonce);
300    let mut commitment = [0u8; 16];
301    commitment.copy_from_slice(&mac[..16]);
302    commitment
303}
304
305/// Check key commitment for fast rejection before AEAD.
306///
307/// Uses constant-time comparison to avoid timing side-channels.
308pub fn check_key_commitment(group_key: &[u8; 32], nonce: &[u8; 12], expected: &[u8; 16]) -> bool {
309    let computed = key_commitment(group_key, nonce);
310    bool::from(computed.ct_eq(expected))
311}
312
313/// Encrypt an EventEnvelopeV2 payload with a group key.
314///
315/// Returns `(tag, ciphertext, nonce, key_commitment)` suitable for
316/// populating a TaggedPayload on the wire.
317///
318/// # Arguments
319///
320/// * `group_key` - 32-byte group encryption key
321/// * `prefix` - Topic prefix used as AAD for domain separation
322/// * `plaintext` - Event payload bytes to encrypt
323/// * `_privacy_mode` - Privacy mode (reserved for future routing decisions)
324///
325/// # Returns
326///
327/// * `tag` - 16-byte AES-GCM authentication tag (last 16 bytes of AEAD output)
328/// * `ciphertext` - Encrypted payload (AEAD output minus trailing tag)
329/// * `nonce` - 12-byte random nonce
330/// * `key_commitment` - 16-byte commitment for fast key rejection
331pub fn encrypt_event(
332    group_key: &[u8; 32],
333    prefix: &str,
334    plaintext: &[u8],
335    _privacy_mode: EventPrivacy,
336) -> Result<(Vec<u8>, Vec<u8>, [u8; 12], [u8; 16]), String> {
337    let nonce = random_nonce();
338    let commitment = key_commitment(group_key, &nonce);
339
340    // Use prefix as AAD for domain separation
341    let aad = prefix.as_bytes();
342    let aead_output = aes_gcm_encrypt(group_key, &nonce, plaintext, aad)?;
343
344    // AES-GCM output is ciphertext || 16-byte tag
345    if aead_output.len() < 16 {
346        return Err("AEAD output too short".to_owned());
347    }
348    let split = aead_output.len() - 16;
349    let ciphertext = aead_output[..split].to_vec();
350    let tag = aead_output[split..].to_vec();
351
352    Ok((tag, ciphertext, nonce, commitment))
353}
354
355/// Encrypt with an explicit nonce supplied by a stateful protocol.
356///
357/// This is crate-private because nonce uniqueness becomes the caller's
358/// responsibility.  The identified stream epoch profile derives the nonce from
359/// its direction/track/epoch domain plus the authenticated sequence number.
360#[cfg(not(target_arch = "wasm32"))]
361pub(crate) fn encrypt_event_with_nonce(
362    group_key: &[u8; 32],
363    nonce: [u8; 12],
364    aad: &str,
365    plaintext: &[u8],
366) -> Result<(Vec<u8>, Vec<u8>, [u8; 12], [u8; 16]), String> {
367    let commitment = key_commitment(group_key, &nonce);
368    let aead_output = aes_gcm_encrypt(group_key, &nonce, plaintext, aad.as_bytes())?;
369    if aead_output.len() < 16 {
370        return Err("AEAD output too short".to_owned());
371    }
372    let split = aead_output.len() - 16;
373    Ok((
374        aead_output[split..].to_vec(),
375        aead_output[..split].to_vec(),
376        nonce,
377        commitment,
378    ))
379}
380
381/// Decrypt an event with full AAD binding (tag + ciphertext + prefix).
382///
383/// This is the preferred decryption path for EventEnvelopeV2, which
384/// binds the prefix as AAD.
385///
386/// # Arguments
387///
388/// * `group_key` - 32-byte group encryption key
389/// * `nonce` - 12-byte nonce
390/// * `tag` - 16-byte authentication tag
391/// * `ciphertext` - Encrypted payload (without tag)
392/// * `prefix` - Topic prefix (must match encryption AAD)
393pub fn decrypt_event_full(
394    group_key: &[u8; 32],
395    nonce: &[u8; 12],
396    tag: &[u8],
397    ciphertext: &[u8],
398    prefix: &str,
399) -> Result<Vec<u8>, String> {
400    // Reconstruct AEAD input: ciphertext || tag
401    let mut combined = Vec::with_capacity(ciphertext.len() + tag.len());
402    combined.extend_from_slice(ciphertext);
403    combined.extend_from_slice(tag);
404
405    let aad = prefix.as_bytes();
406    aes_gcm_decrypt(group_key, nonce, &combined, aad)
407}
408
409// ============================================================================
410// Controller-managed epoch object profile (#555)
411// ============================================================================
412
413const EPOCH_OBJECT_AAD_DOMAIN: &[u8] = b"hyprstream event epoch object aad v2";
414
415/// Derive an AEAD key unique to one `(epoch secret, sender, track, session)`
416/// domain. The CSPRNG session prevents a restarted or concurrent publisher from
417/// reusing a key when its in-memory sequence restarts.
418pub fn derive_sender_track_key(
419    epoch_secret: &[u8; 32],
420    publisher_kid: &[u8; 32],
421    track: &str,
422    session_id: &[u8; 16],
423) -> Zeroizing<[u8; 32]> {
424    let mut material = Vec::with_capacity(32 + 32 + 4 + track.len() + 16);
425    material.extend_from_slice(epoch_secret);
426    material.extend_from_slice(publisher_kid);
427    material.extend_from_slice(&(track.len() as u32).to_be_bytes());
428    material.extend_from_slice(track.as_bytes());
429    material.extend_from_slice(session_id);
430    Zeroizing::new(blake3::derive_key(
431        "hyprstream event sender track session key v2",
432        &material,
433    ))
434}
435
436/// Return the injective 96-bit nonce for one sequence in a session-scoped key
437/// domain. The session prefix is carried through the wire object and is also
438/// bound into the AEAD key; it avoids a fixed nonce label while preserving the
439/// only property AES-GCM needs: uniqueness for each `(key, nonce)` pair.
440/// Sequence zero is reserved as the pre-publication state.
441pub fn derive_event_nonce(session_id: &[u8; 16], sequence: u64) -> Result<[u8; 12], String> {
442    if sequence == 0 {
443        return Err("event sequence zero is reserved".to_owned());
444    }
445    let sequence = sequence.to_be_bytes();
446    Ok([
447        session_id[0],
448        session_id[1],
449        session_id[2],
450        session_id[3],
451        sequence[0],
452        sequence[1],
453        sequence[2],
454        sequence[3],
455        sequence[4],
456        sequence[5],
457        sequence[6],
458        sequence[7],
459    ])
460}
461
462/// Canonical authenticated coordinates kept inside the application payload/AAD;
463/// a stock relay need not understand any of them.
464pub fn build_epoch_object_aad(
465    track: &str,
466    publisher_kid: &[u8; 32],
467    session_id: &[u8; 16],
468    membership_version: u64,
469    epoch: u64,
470    sequence: u64,
471) -> Vec<u8> {
472    let mut aad = Vec::with_capacity(EPOCH_OBJECT_AAD_DOMAIN.len() + 4 + track.len() + 72);
473    aad.extend_from_slice(EPOCH_OBJECT_AAD_DOMAIN);
474    aad.extend_from_slice(&(track.len() as u32).to_be_bytes());
475    aad.extend_from_slice(track.as_bytes());
476    aad.extend_from_slice(publisher_kid);
477    aad.extend_from_slice(session_id);
478    aad.extend_from_slice(&membership_version.to_be_bytes());
479    aad.extend_from_slice(&epoch.to_be_bytes());
480    aad.extend_from_slice(&sequence.to_be_bytes());
481    aad
482}
483
484pub fn encrypt_epoch_event(
485    epoch_secret: &[u8; 32],
486    track: &str,
487    publisher_kid: &[u8; 32],
488    session_id: &[u8; 16],
489    membership_version: u64,
490    epoch: u64,
491    sequence: u64,
492    plaintext: &[u8],
493) -> Result<(Vec<u8>, Vec<u8>, [u8; 12], [u8; 16]), String> {
494    let key = derive_sender_track_key(epoch_secret, publisher_kid, track, session_id);
495    let nonce = derive_event_nonce(session_id, sequence)?;
496    let aad = build_epoch_object_aad(
497        track,
498        publisher_kid,
499        session_id,
500        membership_version,
501        epoch,
502        sequence,
503    );
504    let commitment = key_commitment(&key, &nonce);
505    let output = aes_gcm_encrypt(&key, &nonce, plaintext, &aad)?;
506    if output.len() < 16 {
507        return Err("AEAD output too short".to_owned());
508    }
509    let split = output.len() - 16;
510    Ok((
511        output[split..].to_vec(),
512        output[..split].to_vec(),
513        nonce,
514        commitment,
515    ))
516}
517
518pub fn decrypt_epoch_event(
519    epoch_secret: &[u8; 32],
520    track: &str,
521    publisher_kid: &[u8; 32],
522    session_id: &[u8; 16],
523    membership_version: u64,
524    epoch: u64,
525    sequence: u64,
526    nonce: &[u8; 12],
527    tag: &[u8],
528    ciphertext: &[u8],
529    commitment: &[u8; 16],
530) -> Result<Vec<u8>, String> {
531    let key = derive_sender_track_key(epoch_secret, publisher_kid, track, session_id);
532    if !check_key_commitment(&key, nonce, commitment) {
533        return Err("sender/track/session key commitment mismatch".to_owned());
534    }
535    let aad = build_epoch_object_aad(
536        track,
537        publisher_kid,
538        session_id,
539        membership_version,
540        epoch,
541        sequence,
542    );
543    let mut combined = Vec::with_capacity(ciphertext.len() + tag.len());
544    combined.extend_from_slice(ciphertext);
545    combined.extend_from_slice(tag);
546    aes_gcm_decrypt(&key, nonce, &combined, &aad)
547}
548
549/// Hybrid-attested event transcript. Session, epoch coordinates, and sequence
550/// are signed, so possession of the symmetric epoch key is not publisher
551/// identity evidence.
552pub fn build_epoch_event_sig_message(
553    topic: &str,
554    payload: &[u8],
555    timestamp: i64,
556    session_id: &[u8; 16],
557    membership_version: u64,
558    epoch: u64,
559    sequence: u64,
560) -> Vec<u8> {
561    let mut msg = build_event_sig_message(topic, payload, timestamp);
562    msg.extend_from_slice(session_id);
563    msg.extend_from_slice(&membership_version.to_be_bytes());
564    msg.extend_from_slice(&epoch.to_be_bytes());
565    msg.extend_from_slice(&sequence.to_be_bytes());
566    msg
567}
568// Ed25519 Event Signing
569// ============================================================================
570
571/// Build the signing message for EventEnvelopeV2.
572///
573/// Format: `u32_le(len(topic)) || topic || u32_le(len(payload)) || payload || timestamp_i64_le`
574///
575/// Variable-length fields are length-prefixed to prevent concatenation ambiguity.
576/// The fixed-length timestamp is appended without a length prefix.
577pub fn build_event_sig_message(topic: &str, payload: &[u8], timestamp: i64) -> Vec<u8> {
578    let mut msg = Vec::with_capacity(4 + topic.len() + 4 + payload.len() + 8);
579    msg.extend_from_slice(&(topic.len() as u32).to_le_bytes());
580    msg.extend_from_slice(topic.as_bytes());
581    msg.extend_from_slice(&(payload.len() as u32).to_le_bytes());
582    msg.extend_from_slice(payload);
583    msg.extend_from_slice(&timestamp.to_le_bytes());
584    msg
585}
586
587// ============================================================================
588// Tests
589// ============================================================================
590
591#[cfg(test)]
592#[allow(clippy::unwrap_used)]
593mod tests {
594    use super::*;
595    use rand::RngCore;
596
597    fn random_bytes<const N: usize>() -> [u8; N] {
598        let mut bytes = [0; N];
599        rand::rngs::OsRng.fill_bytes(&mut bytes);
600        bytes
601    }
602
603    fn distinct_random_bytes<const N: usize>(other: &[u8; N]) -> [u8; N] {
604        let mut bytes = random_bytes();
605        if &bytes == other {
606            bytes[0] ^= 1;
607        }
608        bytes
609    }
610
611    #[test]
612    fn test_wrap_unwrap_group_key_roundtrip() {
613        let wrap_key = [0x42u8; 32];
614        let group_key = [0xABu8; 32];
615        let sub_hash = [0x01u8; 32];
616        let tenant = "tenant-a";
617        let prefix = "serve:model:qwen3";
618
619        let wrapped = wrap_group_key(&wrap_key, &group_key, tenant, &sub_hash, prefix).unwrap();
620        let unwrapped = unwrap_group_key(&wrap_key, &wrapped, tenant, &sub_hash, prefix).unwrap();
621
622        assert_eq!(&*unwrapped, &group_key);
623    }
624
625    #[test]
626    fn test_wrap_with_wrong_key_fails() {
627        let wrap_key = [0x42u8; 32];
628        let wrong_key = [0x99u8; 32];
629        let group_key = [0xABu8; 32];
630        let sub_hash = [0x01u8; 32];
631        let tenant = "tenant-a";
632        let prefix = "serve:model:qwen3";
633
634        let wrapped = wrap_group_key(&wrap_key, &group_key, tenant, &sub_hash, prefix).unwrap();
635        let result = unwrap_group_key(&wrong_key, &wrapped, tenant, &sub_hash, prefix);
636
637        assert!(result.is_err());
638    }
639
640    #[test]
641    fn test_wrap_cross_prefix_fails() {
642        let wrap_key = [0x42u8; 32];
643        let group_key = [0xABu8; 32];
644        let sub_hash = [0x01u8; 32];
645
646        let wrapped =
647            wrap_group_key(&wrap_key, &group_key, "tenant-a", &sub_hash, "prefix-a").unwrap();
648        let result = unwrap_group_key(&wrap_key, &wrapped, "tenant-a", &sub_hash, "prefix-b");
649
650        assert!(
651            result.is_err(),
652            "cross-prefix unwrap must fail due to AAD mismatch"
653        );
654    }
655
656    #[test]
657    fn test_wrap_cross_subscriber_fails() {
658        let wrap_key = [0x42u8; 32];
659        let group_key = [0xABu8; 32];
660        let sub_hash_a = [0x01u8; 32];
661        let sub_hash_b = [0x02u8; 32];
662        let tenant = "tenant-a";
663        let prefix = "serve:model:qwen3";
664
665        let wrapped = wrap_group_key(&wrap_key, &group_key, tenant, &sub_hash_a, prefix).unwrap();
666        let result = unwrap_group_key(&wrap_key, &wrapped, tenant, &sub_hash_b, prefix);
667
668        assert!(
669            result.is_err(),
670            "cross-subscriber unwrap must fail due to AAD mismatch"
671        );
672    }
673
674    #[test]
675    fn test_wrap_blob_too_short() {
676        let wrap_key = [0x42u8; 32];
677        let sub_hash = [0x01u8; 32];
678
679        let result = unwrap_group_key(&wrap_key, &[0u8; 5], "tenant-a", &sub_hash, "prefix");
680        assert!(result.is_err());
681    }
682
683    #[test]
684    fn test_wrap_cross_tenant_fails() {
685        let wrap_key = [0x42u8; 32];
686        let group_key = [0xABu8; 32];
687        let sub_hash = [0x01u8; 32];
688        let prefix = "orders";
689
690        let wrapped = wrap_group_key(&wrap_key, &group_key, "tenant-a", &sub_hash, prefix).unwrap();
691        let result = unwrap_group_key(&wrap_key, &wrapped, "tenant-b", &sub_hash, prefix);
692
693        assert!(
694            result.is_err(),
695            "cross-tenant unwrap must fail due to AAD mismatch"
696        );
697    }
698
699    #[test]
700    fn test_encrypt_decrypt_event_roundtrip() {
701        let group_key = [0x42u8; 32];
702        let prefix = "serve:model:qwen3";
703        let plaintext = b"hello, event world!";
704
705        let (tag, ciphertext, nonce, commitment) =
706            encrypt_event(&group_key, prefix, plaintext, EventPrivacy::ZeroKnowledge).unwrap();
707
708        // Verify key commitment
709        assert!(check_key_commitment(&group_key, &nonce, &commitment));
710
711        // Decrypt with full AAD binding
712        let decrypted = decrypt_event_full(&group_key, &nonce, &tag, &ciphertext, prefix).unwrap();
713
714        assert_eq!(decrypted, plaintext);
715    }
716
717    #[test]
718    fn test_encrypt_decrypt_event_simple() {
719        let group_key = [0x42u8; 32];
720        let prefix = "test";
721        let plaintext = b"simple test";
722
723        let (tag, ciphertext, nonce, _commitment) = encrypt_event(
724            &group_key,
725            prefix,
726            plaintext,
727            EventPrivacy::LimitedKnowledge,
728        )
729        .unwrap();
730
731        // Reconstruct combined ciphertext||tag for simple decrypt (no AAD)
732        // Note: simple decrypt uses empty AAD, so this will fail because
733        // encrypt uses prefix as AAD. Use decrypt_event_full instead.
734        let decrypted = decrypt_event_full(&group_key, &nonce, &tag, &ciphertext, prefix).unwrap();
735
736        assert_eq!(decrypted, plaintext);
737    }
738
739    #[test]
740    fn test_key_commitment_matches() {
741        let group_key = [0x42u8; 32];
742        let nonce = [0x01u8; 12];
743
744        let commitment = key_commitment(&group_key, &nonce);
745        assert!(check_key_commitment(&group_key, &nonce, &commitment));
746
747        // Same inputs produce same commitment
748        let commitment2 = key_commitment(&group_key, &nonce);
749        assert_eq!(commitment, commitment2);
750    }
751
752    #[test]
753    fn test_key_commitment_rejects_wrong_key() {
754        let group_key_a = [0x42u8; 32];
755        let group_key_b = [0x99u8; 32];
756        let nonce = [0x01u8; 12];
757
758        let commitment = key_commitment(&group_key_a, &nonce);
759
760        // Wrong key must not match
761        assert!(!check_key_commitment(&group_key_b, &nonce, &commitment));
762    }
763
764    #[test]
765    fn test_key_commitment_rejects_wrong_nonce() {
766        let group_key = [0x42u8; 32];
767        let nonce_a = [0x01u8; 12];
768        let nonce_b = [0x02u8; 12];
769
770        let commitment = key_commitment(&group_key, &nonce_a);
771
772        // Wrong nonce must not match
773        assert!(!check_key_commitment(&group_key, &nonce_b, &commitment));
774    }
775
776    #[test]
777    fn test_aad_binding_prevents_cross_prefix_confusion() {
778        let group_key = [0x42u8; 32];
779        let plaintext = b"sensitive data";
780
781        let (tag, ciphertext, nonce, _) = encrypt_event(
782            &group_key,
783            "prefix-a",
784            plaintext,
785            EventPrivacy::ZeroKnowledge,
786        )
787        .unwrap();
788
789        // Decrypt with wrong prefix must fail
790        let result = decrypt_event_full(&group_key, &nonce, &tag, &ciphertext, "prefix-b");
791        assert!(
792            result.is_err(),
793            "cross-prefix decryption must fail due to AAD mismatch"
794        );
795    }
796
797    #[test]
798    fn test_build_event_sig_message_deterministic() {
799        let topic = "serve:model:qwen3";
800        let payload = b"event payload";
801        let timestamp = 1700000000i64;
802
803        let msg1 = build_event_sig_message(topic, payload, timestamp);
804        let msg2 = build_event_sig_message(topic, payload, timestamp);
805
806        assert_eq!(msg1, msg2);
807    }
808
809    #[test]
810    fn test_build_event_sig_message_structure() {
811        let topic = "test-topic";
812        let payload = b"data";
813        let timestamp = 42i64;
814
815        let msg = build_event_sig_message(topic, payload, timestamp);
816
817        // Verify structure: u32_le(10) || "test-topic" || u32_le(4) || "data" || i64_le(42)
818        let expected_len = 4 + 10 + 4 + 4 + 8;
819        assert_eq!(msg.len(), expected_len);
820
821        // Parse and verify
822        let topic_len = u32::from_le_bytes(msg[0..4].try_into().unwrap()) as usize;
823        assert_eq!(topic_len, 10);
824        assert_eq!(&msg[4..14], b"test-topic");
825
826        let payload_len = u32::from_le_bytes(msg[14..18].try_into().unwrap()) as usize;
827        assert_eq!(payload_len, 4);
828        assert_eq!(&msg[18..22], b"data");
829
830        let ts = i64::from_le_bytes(msg[22..30].try_into().unwrap());
831        assert_eq!(ts, 42);
832    }
833
834    #[test]
835    fn test_build_event_sig_message_different_topics_differ() {
836        let payload = b"same";
837        let timestamp = 1i64;
838
839        let msg1 = build_event_sig_message("topic-a", payload, timestamp);
840        let msg2 = build_event_sig_message("topic-b", payload, timestamp);
841
842        assert_ne!(msg1, msg2);
843    }
844
845    #[test]
846    fn test_build_event_sig_message_prevents_concatenation_ambiguity() {
847        // "ab" + "cd" vs "abc" + "d" must differ due to length prefixing
848        let msg1 = build_event_sig_message("ab", b"cd", 0);
849        let msg2 = build_event_sig_message("abc", b"d", 0);
850
851        assert_ne!(msg1, msg2);
852    }
853
854    #[test]
855    fn test_build_wrap_aad_prevents_ambiguity() {
856        let hash_a = [0x01u8; 32];
857        let hash_b = [0x02u8; 32];
858
859        let aad1 = build_wrap_aad("tenant-a", &hash_a, "prefix");
860        let aad2 = build_wrap_aad("tenant-a", &hash_b, "prefix");
861
862        assert_ne!(aad1, aad2, "different sub_hash must produce different AAD");
863
864        // Same inputs produce same AAD
865        let aad3 = build_wrap_aad("tenant-a", &hash_a, "prefix");
866        assert_eq!(aad1, aad3);
867
868        let tenant_b = build_wrap_aad("tenant-b", &hash_a, "prefix");
869        assert_ne!(
870            aad1, tenant_b,
871            "different tenants must produce different AAD"
872        );
873    }
874
875    #[test]
876    fn test_derive_wrap_key_deterministic() {
877        let secret = [0x42u8; 32];
878        let their_pub = [0x01u8; 32];
879        let our_pub = [0x02u8; 32];
880
881        let key1 = derive_wrap_key(&secret, &their_pub, &our_pub);
882        let key2 = derive_wrap_key(&secret, &their_pub, &our_pub);
883
884        assert_eq!(&*key1, &*key2);
885    }
886
887    #[test]
888    fn test_derive_wrap_key_different_secrets_differ() {
889        let their_pub = [0x01u8; 32];
890        let our_pub = [0x02u8; 32];
891
892        let key1 = derive_wrap_key(&[0x11u8; 32], &their_pub, &our_pub);
893        let key2 = derive_wrap_key(&[0x22u8; 32], &their_pub, &our_pub);
894
895        assert_ne!(&*key1, &*key2);
896    }
897
898    #[test]
899    fn test_encrypt_empty_plaintext() {
900        let group_key = [0x42u8; 32];
901        let prefix = "test";
902
903        let (tag, ciphertext, nonce, commitment) =
904            encrypt_event(&group_key, prefix, b"", EventPrivacy::ZeroKnowledge).unwrap();
905
906        assert!(check_key_commitment(&group_key, &nonce, &commitment));
907        assert!(
908            ciphertext.is_empty(),
909            "empty plaintext produces empty ciphertext body"
910        );
911
912        let decrypted = decrypt_event_full(&group_key, &nonce, &tag, &ciphertext, prefix).unwrap();
913        assert!(decrypted.is_empty());
914    }
915
916    #[test]
917    fn test_privacy_modes_both_work() {
918        let group_key = [0x42u8; 32];
919        let prefix = "test";
920        let plaintext = b"works in both modes";
921
922        // ZeroKnowledge mode
923        let (tag_zk, ct_zk, nonce_zk, _) =
924            encrypt_event(&group_key, prefix, plaintext, EventPrivacy::ZeroKnowledge).unwrap();
925        let dec_zk = decrypt_event_full(&group_key, &nonce_zk, &tag_zk, &ct_zk, prefix).unwrap();
926        assert_eq!(dec_zk, plaintext);
927
928        // LimitedKnowledge mode
929        let (tag_lk, ct_lk, nonce_lk, _) = encrypt_event(
930            &group_key,
931            prefix,
932            plaintext,
933            EventPrivacy::LimitedKnowledge,
934        )
935        .unwrap();
936        let dec_lk = decrypt_event_full(&group_key, &nonce_lk, &tag_lk, &ct_lk, prefix).unwrap();
937        assert_eq!(dec_lk, plaintext);
938    }
939
940    #[test]
941    fn keyed_aead_round_trips_and_binds_topic_epoch() {
942        let group_key = [0x11u8; 32];
943        let plaintext = b"payload-bytes";
944        let leaf = "deadbeef".repeat(8); // 64 hex chars, like topic_leaf output
945        let epoch = 7u64;
946
947        let (tag, ct, nonce, _commitment) = encrypt_event_keyed(
948            &group_key,
949            &leaf,
950            epoch,
951            plaintext,
952            EventPrivacy::ZeroKnowledge,
953        )
954        .unwrap();
955        let recovered = decrypt_event_keyed(&group_key, &nonce, &tag, &ct, &leaf, epoch).unwrap();
956        assert_eq!(recovered, plaintext);
957
958        // Cross-epoch replay: same leaf, wrong epoch -> AEAD auth fails.
959        assert!(decrypt_event_keyed(&group_key, &nonce, &tag, &ct, &leaf, epoch + 1).is_err());
960        // Cross-topic replay: wrong leaf, same epoch -> fails.
961        let other_leaf = "cafe".repeat(16);
962        assert!(decrypt_event_keyed(&group_key, &nonce, &tag, &ct, &other_leaf, epoch).is_err());
963        // Wrong group key -> fails.
964        assert!(decrypt_event_keyed(&[0x22u8; 32], &nonce, &tag, &ct, &leaf, epoch).is_err());
965    }
966
967    #[test]
968    fn session_scoped_keys_and_injective_nonces_prevent_pair_reuse() {
969        let epoch_secret = random_bytes();
970        let publisher_kid = random_bytes();
971        let session_a = random_bytes();
972        let session_b = distinct_random_bytes(&session_a);
973        let key_a = derive_sender_track_key(&epoch_secret, &publisher_kid, "worker", &session_a);
974        let key_b = derive_sender_track_key(&epoch_secret, &publisher_kid, "worker", &session_b);
975        let session = random_bytes();
976        let nonce_1 = derive_event_nonce(&session, 1).unwrap();
977        let nonce_2 = derive_event_nonce(&session, 2).unwrap();
978
979        assert_ne!(&*key_a, &*key_b);
980        assert_eq!(&nonce_1[..4], &session[..4]);
981        assert_eq!(&nonce_1[4..], &1u64.to_be_bytes());
982        assert_eq!(&nonce_2[4..], &2u64.to_be_bytes());
983        assert_ne!(nonce_1, nonce_2);
984        assert!(derive_event_nonce(&session, 0).is_err());
985    }
986
987    #[test]
988    fn session_epoch_and_sequence_mutation_fail_aead_authentication() {
989        let epoch_secret = random_bytes();
990        let publisher_kid = random_bytes();
991        let session_id = random_bytes();
992        let (tag, ciphertext, nonce, commitment) = encrypt_epoch_event(
993            &epoch_secret,
994            "worker",
995            &publisher_kid,
996            &session_id,
997            7,
998            9,
999            11,
1000            b"session-bound payload",
1001        )
1002        .unwrap();
1003
1004        assert_eq!(
1005            decrypt_epoch_event(
1006                &epoch_secret,
1007                "worker",
1008                &publisher_kid,
1009                &session_id,
1010                7,
1011                9,
1012                11,
1013                &nonce,
1014                &tag,
1015                &ciphertext,
1016                &commitment,
1017            )
1018            .unwrap(),
1019            b"session-bound payload"
1020        );
1021
1022        let mut wrong_session = session_id;
1023        wrong_session[0] ^= 1;
1024        assert!(decrypt_epoch_event(
1025            &epoch_secret,
1026            "worker",
1027            &publisher_kid,
1028            &wrong_session,
1029            7,
1030            9,
1031            11,
1032            &nonce,
1033            &tag,
1034            &ciphertext,
1035            &commitment,
1036        )
1037        .is_err());
1038        assert!(decrypt_epoch_event(
1039            &epoch_secret,
1040            "worker",
1041            &publisher_kid,
1042            &session_id,
1043            7,
1044            10,
1045            11,
1046            &nonce,
1047            &tag,
1048            &ciphertext,
1049            &commitment,
1050        )
1051        .is_err());
1052        assert!(decrypt_epoch_event(
1053            &epoch_secret,
1054            "worker",
1055            &publisher_kid,
1056            &session_id,
1057            7,
1058            9,
1059            12,
1060            &nonce,
1061            &tag,
1062            &ciphertext,
1063            &commitment,
1064        )
1065        .is_err());
1066    }
1067
1068    #[test]
1069    fn topic_aad_is_deterministic_and_distinct() {
1070        assert_eq!(build_topic_aad("abcd", 1), build_topic_aad("abcd", 1));
1071        assert_ne!(build_topic_aad("abcd", 1), build_topic_aad("abcd", 2));
1072        assert_ne!(build_topic_aad("abcd", 1), build_topic_aad("abce", 1));
1073        assert!(build_topic_aad("abcd", 1).starts_with(b"hyprstream event-topic-aad v1"));
1074    }
1075}