Skip to main content

hyperlane_plugin_session/
fn.rs

1use super::*;
2
3/// Returns the current Unix epoch timestamp in seconds.
4///
5/// # Returns
6///
7/// - `u64` - Seconds since Unix epoch.
8#[inline]
9pub(crate) fn session_now_secs() -> u64 {
10    SystemTime::now()
11        .duration_since(UNIX_EPOCH)
12        .map(|dur: Duration| dur.as_secs())
13        .unwrap_or(0)
14}
15
16/// Computes the shard index for `session_id` using `XxHash3_64`.
17///
18/// # Arguments
19///
20/// - `&str` - Session identifier.
21///
22/// # Returns
23///
24/// - `usize` - Shard index in `0..SESSION_SHARD_COUNT`.
25#[inline]
26pub(crate) fn session_shard_index(session_id: &str) -> usize {
27    let mut hasher: XxHash3_64 = XxHash3_64::default();
28    hasher.write(session_id.as_bytes());
29    (hasher.finish() as usize) & (SESSION_SHARD_COUNT - 1)
30}
31
32/// Applies one SplitMix64 mixing round.
33///
34/// # Arguments
35///
36/// - `u64` - Input word.
37///
38/// # Returns
39///
40/// - `u64` - Mixed 64-bit output.
41#[inline]
42pub(crate) fn mix64(mut x: u64) -> u64 {
43    x = (x ^ (x >> 30)).wrapping_mul(SPLITMIX_MUL1);
44    x = (x ^ (x >> 27)).wrapping_mul(SPLITMIX_MUL2);
45    x ^ (x >> 31)
46}
47
48/// Writes a 64-bit integer as 16 lowercase hexadecimal ASCII bytes into `dst`.
49///
50/// # Arguments
51///
52/// - `u64` - Input 64-bit word.
53/// - `&mut [u8]` - Destination slice of at least 16 bytes.
54#[inline]
55pub(crate) fn write_hex_u64(word: u64, dst: &mut [u8]) {
56    let mut idx: usize = 0;
57    while idx < 16 {
58        let shift: usize = (15 - idx) * 4;
59        dst[idx] = HEX_DIGITS[((word >> shift) & 0x0F) as usize];
60        idx += 1;
61    }
62}
63
64/// Generates an unpredictable 128-bit lowercase hexadecimal session identifier.
65///
66/// # Returns
67///
68/// - `String` - 32-character hexadecimal session identifier.
69#[inline]
70pub fn generate_session_id() -> String {
71    let seed: u64 = *SESSION_SEED.get_or_init(|| {
72        let nanos: u128 = SystemTime::now()
73            .duration_since(UNIX_EPOCH)
74            .map(|dur: Duration| dur.as_nanos())
75            .unwrap_or(0);
76        let pid: u64 = process::id() as u64;
77        let probe: u64 = (&nanos as *const u128) as usize as u64;
78        mix64((nanos as u64) ^ pid.rotate_left(23) ^ probe)
79    });
80    let seq: u64 = SESSION_SEQ.fetch_add(1, Ordering::Relaxed);
81    let hi: u64 = mix64(seed.wrapping_add(seq.wrapping_mul(SPLITMIX_GAMMA)));
82    let lo: u64 = mix64(hi.wrapping_add(SPLITMIX_GAMMA) ^ seq.rotate_left(31));
83    let mut buf: [u8; 32] = [0u8; 32];
84    write_hex_u64(hi, &mut buf[0..16]);
85    write_hex_u64(lo, &mut buf[16..32]);
86    from_utf8(&buf).unwrap_or_default().to_owned()
87}
88
89/// Computes the FIPS 180-4 SHA-256 digest of `data`.
90///
91/// # Arguments
92///
93/// - `&[u8]` - Input byte slice.
94///
95/// # Returns
96///
97/// - `[u8; 32]` - 256-bit SHA-256 digest.
98#[inline]
99pub(crate) fn sha256(data: &[u8]) -> [u8; 32] {
100    sha256_finalize_from_state(SHA256_INIT, data, 0)
101}
102
103/// Completes a SHA-256 digest starting from an existing midstate after `prefix_bytes`.
104///
105/// # Arguments
106///
107/// - `[u32; 8]` - Starting SHA-256 state words.
108/// - `&[u8]` - Remaining message bytes to absorb.
109/// - `u64` - Number of bytes already compressed into `state`.
110///
111/// # Returns
112///
113/// - `[u8; 32]` - Final 256-bit SHA-256 digest.
114#[inline]
115pub(crate) fn sha256_finalize_from_state(
116    mut state: [u32; 8],
117    data: &[u8],
118    prefix_bytes: u64,
119) -> [u8; 32] {
120    let bit_len: u64 = prefix_bytes.wrapping_add(data.len() as u64).wrapping_mul(8);
121    let (blocks, rem_slice): (&[[u8; 64]], &[u8]) = data.as_chunks::<64>();
122    for block in blocks {
123        sha256_compress(&mut state, block);
124    }
125    let rem: usize = rem_slice.len();
126    let mut block: [u8; 64] = [0u8; 64];
127    block[..rem].copy_from_slice(rem_slice);
128    block[rem] = 0x80;
129    if rem < 56 {
130        block[56..64].copy_from_slice(&bit_len.to_be_bytes());
131        sha256_compress(&mut state, &block);
132    } else {
133        sha256_compress(&mut state, &block);
134        let mut last_block: [u8; 64] = [0u8; 64];
135        last_block[56..64].copy_from_slice(&bit_len.to_be_bytes());
136        sha256_compress(&mut state, &last_block);
137    }
138    let mut out: [u8; 32] = [0u8; 32];
139    for (i, word) in state.iter().enumerate() {
140        out[i * 4..i * 4 + 4].copy_from_slice(&word.to_be_bytes());
141    }
142    out
143}
144
145/// Finalizes a SHA-256 digest over a fixed 32-byte inner digest starting from an existing midstate.
146///
147/// # Arguments
148///
149/// - `[u32; 8]` - Starting outer SHA-256 state words.
150/// - `&[u8; 32]` - 32-byte inner digest to absorb.
151/// - `u64` - Number of bytes already compressed into `state`.
152///
153/// # Returns
154///
155/// - `[u8; 32]` - Final 256-bit SHA-256 digest.
156#[inline]
157pub(crate) fn sha256_finalize_32(
158    mut state: [u32; 8],
159    digest: &[u8; 32],
160    prefix_bytes: u64,
161) -> [u8; 32] {
162    let bit_len: u64 = prefix_bytes.wrapping_add(32).wrapping_mul(8);
163    let mut block: [u8; 64] = [0u8; 64];
164    block[..32].copy_from_slice(digest);
165    block[32] = 0x80;
166    block[56..64].copy_from_slice(&bit_len.to_be_bytes());
167    sha256_compress(&mut state, &block);
168    let mut out: [u8; 32] = [0u8; 32];
169    for (i, word) in state.iter().enumerate() {
170        out[i * 4..i * 4 + 4].copy_from_slice(&word.to_be_bytes());
171    }
172    out
173}
174
175/// Executes a single SHA-256 compression round updating `d` and `h` in place.
176///
177/// # Arguments
178///
179/// - `&mut [u32; 8]` - Eight working state words `[a, b, c, d, e, f, g, h]` indexed cyclically by `base`.
180/// - `usize` - Rotation offset in `0..8`.
181/// - `u32` - Pre-summed round constant plus schedule word (`K[i].wrapping_add(W[i])`).
182#[inline(always)]
183fn sha256_round_at(s: &mut [u32; 8], base: usize, kw: u32) {
184    let a: u32 = s[base & 7];
185    let b: u32 = s[(base + 1) & 7];
186    let c: u32 = s[(base + 2) & 7];
187    let d: u32 = s[(base + 3) & 7];
188    let e: u32 = s[(base + 4) & 7];
189    let f: u32 = s[(base + 5) & 7];
190    let g: u32 = s[(base + 6) & 7];
191    let h: u32 = s[(base + 7) & 7];
192    let s1: u32 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25);
193    let ch: u32 = (e & f) ^ ((!e) & g);
194    let temp1: u32 = h.wrapping_add(s1).wrapping_add(ch).wrapping_add(kw);
195    let s0: u32 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22);
196    let maj: u32 = (a & b) ^ (a & c) ^ (b & c);
197    s[(base + 3) & 7] = d.wrapping_add(temp1);
198    s[(base + 7) & 7] = temp1.wrapping_add(s0.wrapping_add(maj));
199}
200
201/// Compresses one 64-byte SHA-256 block into `state`.
202///
203/// # Arguments
204///
205/// - `&mut [u32; 8]` - Running hash state.
206/// - `&[u8; 64]` - Input 512-bit message block array.
207pub(crate) fn sha256_compress(state: &mut [u32; 8], block: &[u8; 64]) {
208    let mut w: [u32; 64] = [0u32; 64];
209    let (words, _): (&[[u8; 4]], &[u8]) = block.as_chunks::<4>();
210    for (slot, word) in w[..16].iter_mut().zip(words.iter()) {
211        *slot = u32::from_be_bytes(*word);
212    }
213    for i in 16..64usize {
214        let w15: u32 = w[i - 15];
215        let w2: u32 = w[i - 2];
216        let s0: u32 = w15.rotate_right(7) ^ w15.rotate_right(18) ^ (w15 >> 3);
217        let s1: u32 = w2.rotate_right(17) ^ w2.rotate_right(19) ^ (w2 >> 10);
218        w[i] = w[i - 16]
219            .wrapping_add(s0)
220            .wrapping_add(w[i - 7])
221            .wrapping_add(s1);
222    }
223    let mut s: [u32; 8] = *state;
224    let (k_chunks, _): (&[[u32; 8]], &[u32]) = SHA256_K.as_chunks::<8>();
225    let (w_chunks, _): (&[[u32; 8]], &[u32]) = w.as_chunks::<8>();
226    for (k, w8) in k_chunks.iter().zip(w_chunks.iter()) {
227        sha256_round_at(&mut s, 0, k[0].wrapping_add(w8[0]));
228        sha256_round_at(&mut s, 7, k[1].wrapping_add(w8[1]));
229        sha256_round_at(&mut s, 6, k[2].wrapping_add(w8[2]));
230        sha256_round_at(&mut s, 5, k[3].wrapping_add(w8[3]));
231        sha256_round_at(&mut s, 4, k[4].wrapping_add(w8[4]));
232        sha256_round_at(&mut s, 3, k[5].wrapping_add(w8[5]));
233        sha256_round_at(&mut s, 2, k[6].wrapping_add(w8[6]));
234        sha256_round_at(&mut s, 1, k[7].wrapping_add(w8[7]));
235    }
236    for (dst, &delta) in state.iter_mut().zip(s.iter()) {
237        *dst = dst.wrapping_add(delta);
238    }
239}
240
241/// Precomputes SHA-256 ipad and opad midstates for `key`.
242///
243/// # Arguments
244///
245/// - `&[u8]` - Secret HMAC key bytes.
246///
247/// # Returns
248///
249/// - `HmacSha256Key` - Precomputed inner and outer SHA-256 states.
250#[inline]
251pub(crate) fn precompute_hmac_sha256_key(key: &[u8]) -> HmacSha256Key {
252    let mut pad: [u8; 64] = [0x36u8; 64];
253    if key.len() > 64 {
254        let hashed: [u8; 32] = sha256(key);
255        for (slot, &byte) in pad[..32].iter_mut().zip(hashed.iter()) {
256            *slot ^= byte;
257        }
258    } else {
259        for (slot, &byte) in pad[..key.len()].iter_mut().zip(key.iter()) {
260            *slot ^= byte;
261        }
262    }
263    let mut ipad_state: [u32; 8] = SHA256_INIT;
264    sha256_compress(&mut ipad_state, &pad);
265    for slot in &mut pad {
266        *slot ^= 0x6a;
267    }
268    let mut opad_state: [u32; 8] = SHA256_INIT;
269    sha256_compress(&mut opad_state, &pad);
270    HmacSha256Key {
271        ipad_state,
272        opad_state,
273    }
274}
275
276/// Computes the RFC 4231 HMAC-SHA256 tag of `data` using a precomputed [`HmacSha256Key`] without allocating.
277///
278/// # Arguments
279///
280/// - `&HmacSha256Key` - Precomputed ipad and opad midstates.
281/// - `&[u8]` - Input message bytes.
282///
283/// # Returns
284///
285/// - `[u8; 32]` - 256-bit HMAC tag.
286#[inline]
287pub(crate) fn hmac_sha256_with_key(pre: &HmacSha256Key, data: &[u8]) -> [u8; 32] {
288    let inner_hash: [u8; 32] = sha256_finalize_from_state(pre.ipad_state, data, 64);
289    sha256_finalize_32(pre.opad_state, &inner_hash, 64)
290}
291
292/// Computes the RFC 4231 HMAC-SHA256 tag of `data` under `key`.
293///
294/// # Arguments
295///
296/// - `&[u8]` - Secret key bytes.
297/// - `&[u8]` - Input message bytes.
298///
299/// # Returns
300///
301/// - `[u8; 32]` - 256-bit HMAC tag.
302#[inline]
303pub(crate) fn hmac_sha256(key: &[u8], data: &[u8]) -> [u8; 32] {
304    let pre: HmacSha256Key = precompute_hmac_sha256_key(key);
305    hmac_sha256_with_key(&pre, data)
306}
307
308/// Encodes a 32-byte digest into a 64-byte stack ASCII lowercase hexadecimal array.
309///
310/// # Arguments
311///
312/// - `&[u8; 32]` - 256-bit digest.
313///
314/// # Returns
315///
316/// - `[u8; 64]` - Lowercase ASCII hexadecimal bytes.
317#[inline]
318pub(crate) fn encode_hex_32_stack(bytes: &[u8; 32]) -> [u8; 64] {
319    let mut out: [u8; 64] = [0u8; 64];
320    for (idx, &byte) in bytes.iter().enumerate() {
321        out[idx * 2] = HEX_DIGITS[(byte >> 4) as usize];
322        out[idx * 2 + 1] = HEX_DIGITS[(byte & 0x0F) as usize];
323    }
324    out
325}
326
327/// Compares two byte slices in constant time with respect to their contents.
328///
329/// # Arguments
330///
331/// - `&[u8]` - First byte slice.
332/// - `&[u8]` - Second byte slice.
333///
334/// # Returns
335///
336/// - `bool` - `true` when lengths and bytes are identical.
337#[inline]
338pub(crate) fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
339    if a.len() != b.len() {
340        return false;
341    }
342    let mut diff: u8 = 0;
343    for (&x, &y) in a.iter().zip(b.iter()) {
344        diff |= x ^ y;
345    }
346    diff == 0
347}
348
349/// Reports whether `name` is a valid RFC 6265 cookie token.
350///
351/// # Arguments
352///
353/// - `&str` - Candidate cookie name.
354///
355/// # Returns
356///
357/// - `bool` - `true` when non-empty and every byte is a valid token byte.
358#[inline]
359pub(crate) fn is_valid_cookie_name(name: &str) -> bool {
360    !name.is_empty()
361        && name
362            .bytes()
363            .all(|b: u8| b.is_ascii_alphanumeric() || COOKIE_TOKEN_PUNCTUATION.contains(&b))
364}
365
366/// Extracts the first valid cookie value matching `target_name` directly from `raw_cookie` without allocating.
367///
368/// # Arguments
369///
370/// - `&'a str` - Raw `Cookie` request header value.
371/// - `&str` - Cookie name to match.
372///
373/// # Returns
374///
375/// - `Option<&'a str>` - Borrowed cookie value if present and valid.
376#[inline]
377pub(crate) fn find_cookie_value<'a>(raw_cookie: &'a str, target_name: &str) -> Option<&'a str> {
378    if raw_cookie.trim().is_empty() {
379        return None;
380    }
381    for part in raw_cookie.split(COOKIE_PAIR_DELIMITER) {
382        let trimmed: &'a str = part.trim();
383        if trimmed.is_empty() {
384            continue;
385        }
386        if let Some((name, value)) = trimmed.split_once(COOKIE_KV_DELIMITER) {
387            let name: &'a str = name.trim();
388            if name != target_name {
389                continue;
390            }
391            let value: &'a str = value.trim();
392            if is_valid_cookie_name(name) && !value.bytes().any(|b: u8| b <= 0x1F || b == 0x7F) {
393                return Some(value);
394            }
395        }
396    }
397    None
398}
399
400/// Reports whether `value` contains only bytes permitted inside an RFC 6265 cookie value.
401///
402/// # Arguments
403///
404/// - `&str` - Candidate cookie value.
405///
406/// # Returns
407///
408/// - `bool` - `true` when `CookieBuilder::try_build` would accept `value`.
409#[inline]
410pub(crate) fn is_valid_set_cookie_value(value: &str) -> bool {
411    !value
412        .bytes()
413        .any(|b: u8| b <= 0x1F || b == 0x7F || b == b'"' || b == b',' || b == b';' || b == b'\\')
414}
415
416/// Signs `session_id` with `secret` into `"<session_id>.<hex_hmac>"`.
417///
418/// # Arguments
419///
420/// - `&str` - Raw session identifier.
421/// - `&[u8]` - HMAC-SHA256 signing secret.
422///
423/// # Returns
424///
425/// - `String` - Signed cookie value.
426pub fn sign_session_cookie(session_id: &str, secret: &[u8]) -> String {
427    let mac: [u8; 32] = hmac_sha256(secret, session_id.as_bytes());
428    let hex: [u8; 64] = encode_hex_32_stack(&mac);
429    let mut out: String = String::with_capacity(session_id.len() + 1 + hex.len());
430    out.push_str(session_id);
431    out.push('.');
432    if let Ok(sig) = from_utf8(&hex) {
433        out.push_str(sig);
434    }
435    out
436}
437
438/// Verifies a signed session cookie in constant time using a precomputed key without allocating.
439///
440/// # Arguments
441///
442/// - `&'a str` - Raw cookie value (`"<id>.<hex_hmac>"`).
443/// - `&HmacSha256Key` - Precomputed HMAC-SHA256 key states.
444///
445/// # Returns
446///
447/// - `Option<&'a str>` - Borrowed verified session identifier, or `None`.
448#[inline]
449pub(crate) fn verify_session_cookie_with_key<'a>(
450    cookie_value: &'a str,
451    pre: &HmacSha256Key,
452) -> Option<&'a str> {
453    let (id, provided_sig): (&'a str, &'a str) = cookie_value.split_once('.')?;
454    if id.is_empty() || provided_sig.len() != 64 {
455        return None;
456    }
457    let expected_mac: [u8; 32] = hmac_sha256_with_key(pre, id.as_bytes());
458    let expected_sig: [u8; 64] = encode_hex_32_stack(&expected_mac);
459    if constant_time_eq(provided_sig.as_bytes(), &expected_sig) {
460        Some(id)
461    } else {
462        None
463    }
464}
465
466/// Verifies a signed session cookie value in constant time and returns the underlying session ID.
467///
468/// # Arguments
469///
470/// - `&str` - Raw cookie value (`"<id>.<hex_hmac>"`).
471/// - `&[u8]` - HMAC-SHA256 signing secret.
472///
473/// # Returns
474///
475/// - `Option<String>` - Verified session identifier, or `None` if tampered or malformed.
476#[inline]
477pub fn verify_session_cookie(cookie_value: &str, secret: &[u8]) -> Option<String> {
478    let (id, provided_sig): (&str, &str) = cookie_value.split_once('.')?;
479    if id.is_empty() || provided_sig.len() != 64 {
480        return None;
481    }
482    let expected_mac: [u8; 32] = hmac_sha256(secret, id.as_bytes());
483    let expected_sig: [u8; 64] = encode_hex_32_stack(&expected_mac);
484    if constant_time_eq(provided_sig.as_bytes(), &expected_sig) {
485        Some(id.to_owned())
486    } else {
487        None
488    }
489}