Skip to main content

hyprstream_crypto/
hmac.rs

1//! Stream block HMAC for authenticating streaming responses.
2//!
3//! Streaming responses (XPUB/XSUB) use chained MACs instead of per-token Ed25519
4//! signatures for performance:
5//! - Ed25519: ~10k signatures/sec
6//! - Blake3/HMAC-SHA256: millions of MACs/sec
7//!
8//! # Wire format
9//!
10//! Each chunk's MAC depends on the previous chunk's MAC, providing cryptographic
11//! ordering without explicit sequence numbers:
12//!
13//! ```text
14//! mac_0 = HMAC(key, topic.as_bytes() || capnp_data_0)[..16]  // Block 0: seed = topic
15//! mac_n = HMAC(key, mac_{n-1} || capnp_data_n)[..16]         // Subsequent blocks
16//! ```
17//!
18//! # Security Properties
19//!
20//! - Authenticates server as holder of the DH-derived MAC key
21//! - Per-stream key derivation binds chains to specific sessions
22//! - Chained MAC provides cryptographic ordering (no separate sequence field)
23//! - Reordering is impossible — can't verify block N without mac_{N-1}
24//! - 16-byte truncation (128 bits) provides standard authentication strength
25//! - Constant-time verification via `subtle::ConstantTimeEq` prevents timing attacks
26//!
27//! # Backend
28//!
29//! - Default: Blake3 `keyed_hash()` (~10+ GB/s with SIMD)
30//! - FIPS mode: HMAC-SHA256 (FIPS 198-1)
31//!
32//! # Cryptographic notes (from external review)
33//!
34//! - 128-bit truncation is well above NIST recommendations and standard for stream auth
35//! - First-N-bytes truncation is the safe pattern for both Blake3 and HMAC-SHA256
36//! - Topic-as-seed is sound: the key is secret; topic publicness is fine
37//! - Per-stream replay protection comes from the per-call ECDH ephemeral keypair,
38//!   which makes the topic effectively per-stream-random
39
40use subtle::ConstantTimeEq;
41use zeroize::Zeroizing;
42
43/// Chained HMAC state for stream block authentication, matching wire format.
44///
45/// Used by both server (`StreamBuilder`) and client (`StreamMount`).
46///
47/// # Wire format
48/// - Block 0: HMAC(key, topic.as_bytes() || capnp_data)[..16]
49/// - Block N: HMAC(key, prev_mac (16 bytes) || capnp_data)[..16]
50#[derive(Clone)]
51pub struct StreamHmacState {
52    key: Zeroizing<[u8; 32]>,
53    prev_mac: Option<[u8; 16]>,
54    topic: String,
55}
56
57impl StreamHmacState {
58    /// Create new HMAC chain state.
59    pub fn new(key: [u8; 32], topic: String) -> Self {
60        Self {
61            key: Zeroizing::new(key),
62            prev_mac: None,
63            topic,
64        }
65    }
66
67    /// Compute 16-byte truncated MAC for next block, advancing the chain.
68    pub fn compute_next(&mut self, capnp_data: &[u8]) -> [u8; 16] {
69        let mut input = Vec::with_capacity(64 + capnp_data.len());
70        match &self.prev_mac {
71            None => input.extend_from_slice(self.topic.as_bytes()),
72            Some(prev) => input.extend_from_slice(prev),
73        }
74        input.extend_from_slice(capnp_data);
75
76        let truncated = crate::backend::keyed_mac_truncated(&self.key, &input);
77        self.prev_mac = Some(truncated);
78        truncated
79    }
80
81    /// Compute the next MAC without advancing chain state (peek).
82    fn compute_next_peek(&self, capnp_data: &[u8]) -> [u8; 16] {
83        let mut input = Vec::with_capacity(64 + capnp_data.len());
84        match &self.prev_mac {
85            None => input.extend_from_slice(self.topic.as_bytes()),
86            Some(prev) => input.extend_from_slice(prev),
87        }
88        input.extend_from_slice(capnp_data);
89        crate::backend::keyed_mac_truncated(&self.key, &input)
90    }
91
92    /// Verify the next block's MAC in constant time.
93    ///
94    /// Advances the chain only if verification succeeds.
95    /// Returns true if the MAC matches, false otherwise.
96    pub fn verify_next(&mut self, capnp_data: &[u8], expected_mac: &[u8]) -> bool {
97        if expected_mac.len() != 16 {
98            return false;
99        }
100        let computed = self.compute_next_peek(capnp_data);
101        if computed.ct_eq(expected_mac).into() {
102            self.prev_mac = Some(computed);
103            true
104        } else {
105            false
106        }
107    }
108
109    /// Get the topic.
110    pub fn topic(&self) -> &str {
111        &self.topic
112    }
113
114    /// Get previous MAC bytes (for prevMac field in StreamBlock).
115    pub fn prev_mac_bytes(&self) -> &[u8] {
116        match &self.prev_mac {
117            Some(mac) => mac,
118            None => &self.topic.as_bytes()[..16.min(self.topic.len())],
119        }
120    }
121}
122
123#[cfg(test)]
124mod tests {
125    use super::*;
126
127    #[test]
128    fn test_stream_hmac_compute_verify_roundtrip() {
129        let key = [0x42u8; 32];
130        let topic = "00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff".to_owned();
131
132        // Producer
133        let mut producer = StreamHmacState::new(key, topic.clone());
134        let mac0 = producer.compute_next(b"block 0 data");
135        let mac1 = producer.compute_next(b"block 1 data");
136        let mac2 = producer.compute_next(b"block 2 data");
137
138        // Verifier
139        let mut verifier = StreamHmacState::new(key, topic);
140        assert!(verifier.verify_next(b"block 0 data", &mac0));
141        assert!(verifier.verify_next(b"block 1 data", &mac1));
142        assert!(verifier.verify_next(b"block 2 data", &mac2));
143    }
144
145    #[test]
146    fn test_stream_hmac_rejects_wrong_mac() {
147        let key = [0x42u8; 32];
148        let topic = "topic".to_owned();
149
150        let mut verifier = StreamHmacState::new(key, topic);
151        let bad_mac = [0xffu8; 16];
152        assert!(!verifier.verify_next(b"data", &bad_mac));
153    }
154
155    #[test]
156    fn test_stream_hmac_rejects_wrong_length() {
157        let key = [0x42u8; 32];
158        let topic = "topic".to_owned();
159
160        let mut verifier = StreamHmacState::new(key, topic);
161        assert!(!verifier.verify_next(b"data", &[0u8; 32])); // 32 bytes is wrong
162        assert!(!verifier.verify_next(b"data", &[0u8; 8])); // 8 bytes is wrong
163    }
164}