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.
8pub(crate) fn session_now_secs() -> u64 {
9    SystemTime::now()
10        .duration_since(UNIX_EPOCH)
11        .map(|dur: Duration| dur.as_secs())
12        .unwrap_or(0)
13}
14
15/// Computes the shard index for `session_id` using `XxHash3_64`.
16///
17/// # Arguments
18///
19/// - `&str` - Session identifier.
20///
21/// # Returns
22///
23/// - `usize` - Shard index in `0..SESSION_SHARD_COUNT`.
24pub(crate) fn session_shard_index(session_id: &str) -> usize {
25    let mut hasher: XxHash3_64 = XxHash3_64::default();
26    hasher.write(session_id.as_bytes());
27    (hasher.finish() as usize) & (SESSION_SHARD_COUNT - 1)
28}
29
30/// Applies one SplitMix64 mixing round.
31///
32/// # Arguments
33///
34/// - `u64` - Input word.
35///
36/// # Returns
37///
38/// - `u64` - Mixed 64-bit output.
39pub(crate) fn mix64(mut x: u64) -> u64 {
40    x = (x ^ (x >> 30)).wrapping_mul(SPLITMIX_MUL1);
41    x = (x ^ (x >> 27)).wrapping_mul(SPLITMIX_MUL2);
42    x ^ (x >> 31)
43}
44
45/// Generates an unpredictable 128-bit lowercase hexadecimal session identifier.
46///
47/// # Returns
48///
49/// - `String` - 32-character hexadecimal session identifier.
50pub fn generate_session_id() -> String {
51    let seed: u64 = *SESSION_SEED.get_or_init(|| {
52        let nanos: u128 = SystemTime::now()
53            .duration_since(UNIX_EPOCH)
54            .map(|dur: Duration| dur.as_nanos())
55            .unwrap_or(0);
56        let pid: u64 = process::id() as u64;
57        let probe: u64 = (&nanos as *const u128) as usize as u64;
58        mix64((nanos as u64) ^ pid.rotate_left(23) ^ probe)
59    });
60    let seq: u64 = SESSION_SEQ.fetch_add(1, Ordering::Relaxed);
61    let nanos: u64 = SystemTime::now()
62        .duration_since(UNIX_EPOCH)
63        .map(|dur: Duration| dur.as_nanos() as u64)
64        .unwrap_or(0);
65    let hi: u64 = mix64(seed.wrapping_add(seq.wrapping_mul(SPLITMIX_GAMMA)) ^ nanos);
66    let lo: u64 = mix64(hi.wrapping_add(SPLITMIX_GAMMA) ^ seq.rotate_left(31));
67    let mut out: String = String::with_capacity(32);
68    for word in [hi, lo] {
69        for shift in (0..16).rev() {
70            let nibble: usize = ((word >> (shift * 4)) & 0x0F) as usize;
71            out.push(HEX_DIGITS[nibble] as char);
72        }
73    }
74    out
75}
76
77/// Computes the FIPS 180-4 SHA-256 digest of `data`.
78///
79/// # Arguments
80///
81/// - `&[u8]` - Input byte slice.
82///
83/// # Returns
84///
85/// - `[u8; 32]` - 256-bit SHA-256 digest.
86pub(crate) fn sha256(data: &[u8]) -> [u8; 32] {
87    let mut state: [u32; 8] = SHA256_INIT;
88    let bit_len: u64 = (data.len() as u64).wrapping_mul(8);
89    let mut offset: usize = 0;
90    while data.len() - offset >= 64 {
91        let mut block: [u8; 64] = [0u8; 64];
92        block.copy_from_slice(&data[offset..offset + 64]);
93        sha256_compress(&mut state, &block);
94        offset += 64;
95    }
96    let rem: usize = data.len() - offset;
97    let mut tail: [u8; 128] = [0u8; 128];
98    tail[..rem].copy_from_slice(&data[offset..]);
99    tail[rem] = 0x80;
100    let total_tail: usize = if rem < 56 { 64 } else { 128 };
101    tail[total_tail - 8..total_tail].copy_from_slice(&bit_len.to_be_bytes());
102    let mut b0: [u8; 64] = [0u8; 64];
103    b0.copy_from_slice(&tail[..64]);
104    sha256_compress(&mut state, &b0);
105    if total_tail == 128 {
106        let mut b1: [u8; 64] = [0u8; 64];
107        b1.copy_from_slice(&tail[64..128]);
108        sha256_compress(&mut state, &b1);
109    }
110    let mut out: [u8; 32] = [0u8; 32];
111    for (i, word) in state.iter().enumerate() {
112        out[i * 4..i * 4 + 4].copy_from_slice(&word.to_be_bytes());
113    }
114    out
115}
116
117/// Compresses one 64-byte SHA-256 block into `state`.
118///
119/// # Arguments
120///
121/// - `&mut [u32; 8]` - Running hash state.
122/// - `&[u8; 64]` - Input message block.
123pub(crate) fn sha256_compress(state: &mut [u32; 8], block: &[u8; 64]) {
124    let mut w: [u32; 64] = [0u32; 64];
125    for i in 0..16usize {
126        w[i] = u32::from_be_bytes([
127            block[i * 4],
128            block[i * 4 + 1],
129            block[i * 4 + 2],
130            block[i * 4 + 3],
131        ]);
132    }
133    for i in 16..64usize {
134        let s0: u32 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3);
135        let s1: u32 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10);
136        w[i] = w[i - 16]
137            .wrapping_add(s0)
138            .wrapping_add(w[i - 7])
139            .wrapping_add(s1);
140    }
141    let mut a: u32 = state[0];
142    let mut b: u32 = state[1];
143    let mut c: u32 = state[2];
144    let mut d: u32 = state[3];
145    let mut e: u32 = state[4];
146    let mut f: u32 = state[5];
147    let mut g: u32 = state[6];
148    let mut h: u32 = state[7];
149    for i in 0..64usize {
150        let s1: u32 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25);
151        let ch: u32 = (e & f) ^ ((!e) & g);
152        let temp1: u32 = h
153            .wrapping_add(s1)
154            .wrapping_add(ch)
155            .wrapping_add(SHA256_K[i])
156            .wrapping_add(w[i]);
157        let s0: u32 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22);
158        let maj: u32 = (a & b) ^ (a & c) ^ (b & c);
159        let temp2: u32 = s0.wrapping_add(maj);
160        h = g;
161        g = f;
162        f = e;
163        e = d.wrapping_add(temp1);
164        d = c;
165        c = b;
166        b = a;
167        a = temp1.wrapping_add(temp2);
168    }
169    state[0] = state[0].wrapping_add(a);
170    state[1] = state[1].wrapping_add(b);
171    state[2] = state[2].wrapping_add(c);
172    state[3] = state[3].wrapping_add(d);
173    state[4] = state[4].wrapping_add(e);
174    state[5] = state[5].wrapping_add(f);
175    state[6] = state[6].wrapping_add(g);
176    state[7] = state[7].wrapping_add(h);
177}
178
179/// Computes the RFC 4231 HMAC-SHA256 tag of `data` under `key`.
180///
181/// # Arguments
182///
183/// - `&[u8]` - Secret key bytes.
184/// - `&[u8]` - Input message bytes.
185///
186/// # Returns
187///
188/// - `[u8; 32]` - 256-bit HMAC tag.
189pub(crate) fn hmac_sha256(key: &[u8], data: &[u8]) -> [u8; 32] {
190    let mut key_block: [u8; 64] = [0u8; 64];
191    if key.len() > 64 {
192        let hashed: [u8; 32] = sha256(key);
193        key_block[..32].copy_from_slice(&hashed);
194    } else {
195        key_block[..key.len()].copy_from_slice(key);
196    }
197    let mut inner: Vec<u8> = Vec::with_capacity(64 + data.len());
198    for byte in key_block {
199        inner.push(byte ^ 0x36);
200    }
201    inner.extend_from_slice(data);
202    let inner_hash: [u8; 32] = sha256(&inner);
203    let mut outer: [u8; 96] = [0u8; 96];
204    for i in 0..64usize {
205        outer[i] = key_block[i] ^ 0x5c;
206    }
207    outer[64..96].copy_from_slice(&inner_hash);
208    sha256(&outer)
209}
210
211/// Compares two byte slices in constant time with respect to their contents.
212///
213/// # Arguments
214///
215/// - `&[u8]` - First byte slice.
216/// - `&[u8]` - Second byte slice.
217///
218/// # Returns
219///
220/// - `bool` - `true` when lengths and bytes are identical.
221pub(crate) fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
222    if a.len() != b.len() {
223        return false;
224    }
225    let mut diff: u8 = 0;
226    for i in 0..a.len() {
227        diff |= a[i] ^ b[i];
228    }
229    diff == 0
230}
231
232/// Signs `session_id` with `secret` into `"<session_id>.<hex_hmac>"`.
233///
234/// # Arguments
235///
236/// - `&str` - Raw session identifier.
237/// - `&[u8]` - HMAC-SHA256 signing secret.
238///
239/// # Returns
240///
241/// - `String` - Signed cookie value.
242pub fn sign_session_cookie(session_id: &str, secret: &[u8]) -> String {
243    let mac: [u8; 32] = hmac_sha256(secret, session_id.as_bytes());
244    let mut out: String = String::with_capacity(session_id.len() + 1 + 64);
245    out.push_str(session_id);
246    out.push('.');
247    for byte in mac {
248        out.push(HEX_DIGITS[(byte >> 4) as usize] as char);
249        out.push(HEX_DIGITS[(byte & 0x0F) as usize] as char);
250    }
251    out
252}
253
254/// Verifies a signed session cookie value in constant time and returns the underlying session ID.
255///
256/// # Arguments
257///
258/// - `&str` - Raw cookie value (`"<id>.<hex_hmac>"`).
259/// - `&[u8]` - HMAC-SHA256 signing secret.
260///
261/// # Returns
262///
263/// - `Option<String>` - Verified session identifier, or `None` if tampered or malformed.
264pub fn verify_session_cookie(cookie_value: &str, secret: &[u8]) -> Option<String> {
265    let (id, provided_sig): (&str, &str) = cookie_value.split_once('.')?;
266    if id.is_empty() || provided_sig.len() != 64 {
267        return None;
268    }
269    let expected: String = sign_session_cookie(id, secret);
270    let expected_sig: &str = expected.split_once('.')?.1;
271    if constant_time_eq(provided_sig.as_bytes(), expected_sig.as_bytes()) {
272        Some(id.to_owned())
273    } else {
274        None
275    }
276}