hyperlane-plugin-session 22.14.0

A high-concurrency sharded session management plugin for the Hyperlane framework with pluggable async SessionStore traits, optional HMAC-SHA256 signed cookies, dirty-tracked zero-write reads, and session-fixation ID regeneration.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
use super::*;

/// Returns the current Unix epoch timestamp in seconds.
///
/// # Returns
///
/// - `u64` - Seconds since Unix epoch.
#[inline]
pub(crate) fn session_now_secs() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|dur: Duration| dur.as_secs())
        .unwrap_or(0)
}

/// Computes the shard index for `session_id` using `XxHash3_64`.
///
/// # Arguments
///
/// - `&str` - Session identifier.
///
/// # Returns
///
/// - `usize` - Shard index in `0..SESSION_SHARD_COUNT`.
#[inline]
pub(crate) fn session_shard_index(session_id: &str) -> usize {
    let mut hasher: XxHash3_64 = XxHash3_64::default();
    hasher.write(session_id.as_bytes());
    (hasher.finish() as usize) & (SESSION_SHARD_COUNT - 1)
}

/// Applies one SplitMix64 mixing round.
///
/// # Arguments
///
/// - `u64` - Input word.
///
/// # Returns
///
/// - `u64` - Mixed 64-bit output.
#[inline]
pub(crate) fn mix64(mut x: u64) -> u64 {
    x = (x ^ (x >> 30)).wrapping_mul(SPLITMIX_MUL1);
    x = (x ^ (x >> 27)).wrapping_mul(SPLITMIX_MUL2);
    x ^ (x >> 31)
}

/// Writes a 64-bit integer as 16 lowercase hexadecimal ASCII bytes into `dst`.
///
/// # Arguments
///
/// - `u64` - Input 64-bit word.
/// - `&mut [u8]` - Destination slice of at least 16 bytes.
#[inline]
pub(crate) fn write_hex_u64(word: u64, dst: &mut [u8]) {
    let mut idx: usize = 0;
    while idx < 16 {
        let shift: usize = (15 - idx) * 4;
        dst[idx] = HEX_DIGITS[((word >> shift) & 0x0F) as usize];
        idx += 1;
    }
}

/// Generates an unpredictable 128-bit lowercase hexadecimal session identifier.
///
/// # Returns
///
/// - `String` - 32-character hexadecimal session identifier.
#[inline]
pub fn generate_session_id() -> String {
    let seed: u64 = *SESSION_SEED.get_or_init(|| {
        let nanos: u128 = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|dur: Duration| dur.as_nanos())
            .unwrap_or(0);
        let pid: u64 = process::id() as u64;
        let probe: u64 = (&nanos as *const u128) as usize as u64;
        mix64((nanos as u64) ^ pid.rotate_left(23) ^ probe)
    });
    let seq: u64 = SESSION_SEQ.fetch_add(1, Ordering::Relaxed);
    let hi: u64 = mix64(seed.wrapping_add(seq.wrapping_mul(SPLITMIX_GAMMA)));
    let lo: u64 = mix64(hi.wrapping_add(SPLITMIX_GAMMA) ^ seq.rotate_left(31));
    let mut buf: [u8; 32] = [0u8; 32];
    write_hex_u64(hi, &mut buf[0..16]);
    write_hex_u64(lo, &mut buf[16..32]);
    from_utf8(&buf).unwrap_or_default().to_owned()
}

/// Computes the FIPS 180-4 SHA-256 digest of `data`.
///
/// # Arguments
///
/// - `&[u8]` - Input byte slice.
///
/// # Returns
///
/// - `[u8; 32]` - 256-bit SHA-256 digest.
#[inline]
pub(crate) fn sha256(data: &[u8]) -> [u8; 32] {
    sha256_finalize_from_state(SHA256_INIT, data, 0)
}

/// Completes a SHA-256 digest starting from an existing midstate after `prefix_bytes`.
///
/// # Arguments
///
/// - `[u32; 8]` - Starting SHA-256 state words.
/// - `&[u8]` - Remaining message bytes to absorb.
/// - `u64` - Number of bytes already compressed into `state`.
///
/// # Returns
///
/// - `[u8; 32]` - Final 256-bit SHA-256 digest.
#[inline]
pub(crate) fn sha256_finalize_from_state(
    mut state: [u32; 8],
    data: &[u8],
    prefix_bytes: u64,
) -> [u8; 32] {
    let bit_len: u64 = prefix_bytes.wrapping_add(data.len() as u64).wrapping_mul(8);
    let (blocks, rem_slice): (&[[u8; 64]], &[u8]) = data.as_chunks::<64>();
    for block in blocks {
        sha256_compress(&mut state, block);
    }
    let rem: usize = rem_slice.len();
    let mut block: [u8; 64] = [0u8; 64];
    block[..rem].copy_from_slice(rem_slice);
    block[rem] = 0x80;
    if rem < 56 {
        block[56..64].copy_from_slice(&bit_len.to_be_bytes());
        sha256_compress(&mut state, &block);
    } else {
        sha256_compress(&mut state, &block);
        let mut last_block: [u8; 64] = [0u8; 64];
        last_block[56..64].copy_from_slice(&bit_len.to_be_bytes());
        sha256_compress(&mut state, &last_block);
    }
    let mut out: [u8; 32] = [0u8; 32];
    for (i, word) in state.iter().enumerate() {
        out[i * 4..i * 4 + 4].copy_from_slice(&word.to_be_bytes());
    }
    out
}

/// Finalizes a SHA-256 digest over a fixed 32-byte inner digest starting from an existing midstate.
///
/// # Arguments
///
/// - `[u32; 8]` - Starting outer SHA-256 state words.
/// - `&[u8; 32]` - 32-byte inner digest to absorb.
/// - `u64` - Number of bytes already compressed into `state`.
///
/// # Returns
///
/// - `[u8; 32]` - Final 256-bit SHA-256 digest.
#[inline]
pub(crate) fn sha256_finalize_32(
    mut state: [u32; 8],
    digest: &[u8; 32],
    prefix_bytes: u64,
) -> [u8; 32] {
    let bit_len: u64 = prefix_bytes.wrapping_add(32).wrapping_mul(8);
    let mut block: [u8; 64] = [0u8; 64];
    block[..32].copy_from_slice(digest);
    block[32] = 0x80;
    block[56..64].copy_from_slice(&bit_len.to_be_bytes());
    sha256_compress(&mut state, &block);
    let mut out: [u8; 32] = [0u8; 32];
    for (i, word) in state.iter().enumerate() {
        out[i * 4..i * 4 + 4].copy_from_slice(&word.to_be_bytes());
    }
    out
}

/// Executes a single SHA-256 compression round updating `d` and `h` in place.
///
/// # Arguments
///
/// - `&mut [u32; 8]` - Eight working state words `[a, b, c, d, e, f, g, h]` indexed cyclically by `base`.
/// - `usize` - Rotation offset in `0..8`.
/// - `u32` - Pre-summed round constant plus schedule word (`K[i].wrapping_add(W[i])`).
#[inline(always)]
fn sha256_round_at(s: &mut [u32; 8], base: usize, kw: u32) {
    let a: u32 = s[base & 7];
    let b: u32 = s[(base + 1) & 7];
    let c: u32 = s[(base + 2) & 7];
    let d: u32 = s[(base + 3) & 7];
    let e: u32 = s[(base + 4) & 7];
    let f: u32 = s[(base + 5) & 7];
    let g: u32 = s[(base + 6) & 7];
    let h: u32 = s[(base + 7) & 7];
    let s1: u32 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25);
    let ch: u32 = (e & f) ^ ((!e) & g);
    let temp1: u32 = h.wrapping_add(s1).wrapping_add(ch).wrapping_add(kw);
    let s0: u32 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22);
    let maj: u32 = (a & b) ^ (a & c) ^ (b & c);
    s[(base + 3) & 7] = d.wrapping_add(temp1);
    s[(base + 7) & 7] = temp1.wrapping_add(s0.wrapping_add(maj));
}

/// Compresses one 64-byte SHA-256 block into `state`.
///
/// # Arguments
///
/// - `&mut [u32; 8]` - Running hash state.
/// - `&[u8; 64]` - Input 512-bit message block array.
pub(crate) fn sha256_compress(state: &mut [u32; 8], block: &[u8; 64]) {
    let mut w: [u32; 64] = [0u32; 64];
    let (words, _): (&[[u8; 4]], &[u8]) = block.as_chunks::<4>();
    for (slot, word) in w[..16].iter_mut().zip(words.iter()) {
        *slot = u32::from_be_bytes(*word);
    }
    for i in 16..64usize {
        let w15: u32 = w[i - 15];
        let w2: u32 = w[i - 2];
        let s0: u32 = w15.rotate_right(7) ^ w15.rotate_right(18) ^ (w15 >> 3);
        let s1: u32 = w2.rotate_right(17) ^ w2.rotate_right(19) ^ (w2 >> 10);
        w[i] = w[i - 16]
            .wrapping_add(s0)
            .wrapping_add(w[i - 7])
            .wrapping_add(s1);
    }
    let mut s: [u32; 8] = *state;
    let (k_chunks, _): (&[[u32; 8]], &[u32]) = SHA256_K.as_chunks::<8>();
    let (w_chunks, _): (&[[u32; 8]], &[u32]) = w.as_chunks::<8>();
    for (k, w8) in k_chunks.iter().zip(w_chunks.iter()) {
        sha256_round_at(&mut s, 0, k[0].wrapping_add(w8[0]));
        sha256_round_at(&mut s, 7, k[1].wrapping_add(w8[1]));
        sha256_round_at(&mut s, 6, k[2].wrapping_add(w8[2]));
        sha256_round_at(&mut s, 5, k[3].wrapping_add(w8[3]));
        sha256_round_at(&mut s, 4, k[4].wrapping_add(w8[4]));
        sha256_round_at(&mut s, 3, k[5].wrapping_add(w8[5]));
        sha256_round_at(&mut s, 2, k[6].wrapping_add(w8[6]));
        sha256_round_at(&mut s, 1, k[7].wrapping_add(w8[7]));
    }
    for (dst, &delta) in state.iter_mut().zip(s.iter()) {
        *dst = dst.wrapping_add(delta);
    }
}

/// Precomputes SHA-256 ipad and opad midstates for `key`.
///
/// # Arguments
///
/// - `&[u8]` - Secret HMAC key bytes.
///
/// # Returns
///
/// - `HmacSha256Key` - Precomputed inner and outer SHA-256 states.
#[inline]
pub(crate) fn precompute_hmac_sha256_key(key: &[u8]) -> HmacSha256Key {
    let mut pad: [u8; 64] = [0x36u8; 64];
    if key.len() > 64 {
        let hashed: [u8; 32] = sha256(key);
        for (slot, &byte) in pad[..32].iter_mut().zip(hashed.iter()) {
            *slot ^= byte;
        }
    } else {
        for (slot, &byte) in pad[..key.len()].iter_mut().zip(key.iter()) {
            *slot ^= byte;
        }
    }
    let mut ipad_state: [u32; 8] = SHA256_INIT;
    sha256_compress(&mut ipad_state, &pad);
    for slot in &mut pad {
        *slot ^= 0x6a;
    }
    let mut opad_state: [u32; 8] = SHA256_INIT;
    sha256_compress(&mut opad_state, &pad);
    HmacSha256Key {
        ipad_state,
        opad_state,
    }
}

/// Computes the RFC 4231 HMAC-SHA256 tag of `data` using a precomputed [`HmacSha256Key`] without allocating.
///
/// # Arguments
///
/// - `&HmacSha256Key` - Precomputed ipad and opad midstates.
/// - `&[u8]` - Input message bytes.
///
/// # Returns
///
/// - `[u8; 32]` - 256-bit HMAC tag.
#[inline]
pub(crate) fn hmac_sha256_with_key(pre: &HmacSha256Key, data: &[u8]) -> [u8; 32] {
    let inner_hash: [u8; 32] = sha256_finalize_from_state(pre.ipad_state, data, 64);
    sha256_finalize_32(pre.opad_state, &inner_hash, 64)
}

/// Computes the RFC 4231 HMAC-SHA256 tag of `data` under `key`.
///
/// # Arguments
///
/// - `&[u8]` - Secret key bytes.
/// - `&[u8]` - Input message bytes.
///
/// # Returns
///
/// - `[u8; 32]` - 256-bit HMAC tag.
#[inline]
pub(crate) fn hmac_sha256(key: &[u8], data: &[u8]) -> [u8; 32] {
    let pre: HmacSha256Key = precompute_hmac_sha256_key(key);
    hmac_sha256_with_key(&pre, data)
}

/// Encodes a 32-byte digest into a 64-byte stack ASCII lowercase hexadecimal array.
///
/// # Arguments
///
/// - `&[u8; 32]` - 256-bit digest.
///
/// # Returns
///
/// - `[u8; 64]` - Lowercase ASCII hexadecimal bytes.
#[inline]
pub(crate) fn encode_hex_32_stack(bytes: &[u8; 32]) -> [u8; 64] {
    let mut out: [u8; 64] = [0u8; 64];
    for (idx, &byte) in bytes.iter().enumerate() {
        out[idx * 2] = HEX_DIGITS[(byte >> 4) as usize];
        out[idx * 2 + 1] = HEX_DIGITS[(byte & 0x0F) as usize];
    }
    out
}

/// Compares two byte slices in constant time with respect to their contents.
///
/// # Arguments
///
/// - `&[u8]` - First byte slice.
/// - `&[u8]` - Second byte slice.
///
/// # Returns
///
/// - `bool` - `true` when lengths and bytes are identical.
#[inline]
pub(crate) fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
    if a.len() != b.len() {
        return false;
    }
    let mut diff: u8 = 0;
    for (&x, &y) in a.iter().zip(b.iter()) {
        diff |= x ^ y;
    }
    diff == 0
}

/// Reports whether `name` is a valid RFC 6265 cookie token.
///
/// # Arguments
///
/// - `&str` - Candidate cookie name.
///
/// # Returns
///
/// - `bool` - `true` when non-empty and every byte is a valid token byte.
#[inline]
pub(crate) fn is_valid_cookie_name(name: &str) -> bool {
    !name.is_empty()
        && name
            .bytes()
            .all(|b: u8| b.is_ascii_alphanumeric() || COOKIE_TOKEN_PUNCTUATION.contains(&b))
}

/// Extracts the first valid cookie value matching `target_name` directly from `raw_cookie` without allocating.
///
/// # Arguments
///
/// - `&'a str` - Raw `Cookie` request header value.
/// - `&str` - Cookie name to match.
///
/// # Returns
///
/// - `Option<&'a str>` - Borrowed cookie value if present and valid.
#[inline]
pub(crate) fn find_cookie_value<'a>(raw_cookie: &'a str, target_name: &str) -> Option<&'a str> {
    if raw_cookie.trim().is_empty() {
        return None;
    }
    for part in raw_cookie.split(COOKIE_PAIR_DELIMITER) {
        let trimmed: &'a str = part.trim();
        if trimmed.is_empty() {
            continue;
        }
        if let Some((name, value)) = trimmed.split_once(COOKIE_KV_DELIMITER) {
            let name: &'a str = name.trim();
            if name != target_name {
                continue;
            }
            let value: &'a str = value.trim();
            if is_valid_cookie_name(name) && !value.bytes().any(|b: u8| b <= 0x1F || b == 0x7F) {
                return Some(value);
            }
        }
    }
    None
}

/// Reports whether `value` contains only bytes permitted inside an RFC 6265 cookie value.
///
/// # Arguments
///
/// - `&str` - Candidate cookie value.
///
/// # Returns
///
/// - `bool` - `true` when `CookieBuilder::try_build` would accept `value`.
#[inline]
pub(crate) fn is_valid_set_cookie_value(value: &str) -> bool {
    !value
        .bytes()
        .any(|b: u8| b <= 0x1F || b == 0x7F || b == b'"' || b == b',' || b == b';' || b == b'\\')
}

/// Signs `session_id` with `secret` into `"<session_id>.<hex_hmac>"`.
///
/// # Arguments
///
/// - `&str` - Raw session identifier.
/// - `&[u8]` - HMAC-SHA256 signing secret.
///
/// # Returns
///
/// - `String` - Signed cookie value.
pub fn sign_session_cookie(session_id: &str, secret: &[u8]) -> String {
    let mac: [u8; 32] = hmac_sha256(secret, session_id.as_bytes());
    let hex: [u8; 64] = encode_hex_32_stack(&mac);
    let mut out: String = String::with_capacity(session_id.len() + 1 + hex.len());
    out.push_str(session_id);
    out.push('.');
    if let Ok(sig) = from_utf8(&hex) {
        out.push_str(sig);
    }
    out
}

/// Verifies a signed session cookie in constant time using a precomputed key without allocating.
///
/// # Arguments
///
/// - `&'a str` - Raw cookie value (`"<id>.<hex_hmac>"`).
/// - `&HmacSha256Key` - Precomputed HMAC-SHA256 key states.
///
/// # Returns
///
/// - `Option<&'a str>` - Borrowed verified session identifier, or `None`.
#[inline]
pub(crate) fn verify_session_cookie_with_key<'a>(
    cookie_value: &'a str,
    pre: &HmacSha256Key,
) -> Option<&'a str> {
    let (id, provided_sig): (&'a str, &'a str) = cookie_value.split_once('.')?;
    if id.is_empty() || provided_sig.len() != 64 {
        return None;
    }
    let expected_mac: [u8; 32] = hmac_sha256_with_key(pre, id.as_bytes());
    let expected_sig: [u8; 64] = encode_hex_32_stack(&expected_mac);
    if constant_time_eq(provided_sig.as_bytes(), &expected_sig) {
        Some(id)
    } else {
        None
    }
}

/// Verifies a signed session cookie value in constant time and returns the underlying session ID.
///
/// # Arguments
///
/// - `&str` - Raw cookie value (`"<id>.<hex_hmac>"`).
/// - `&[u8]` - HMAC-SHA256 signing secret.
///
/// # Returns
///
/// - `Option<String>` - Verified session identifier, or `None` if tampered or malformed.
#[inline]
pub fn verify_session_cookie(cookie_value: &str, secret: &[u8]) -> Option<String> {
    let (id, provided_sig): (&str, &str) = cookie_value.split_once('.')?;
    if id.is_empty() || provided_sig.len() != 64 {
        return None;
    }
    let expected_mac: [u8; 32] = hmac_sha256(secret, id.as_bytes());
    let expected_sig: [u8; 64] = encode_hex_32_stack(&expected_mac);
    if constant_time_eq(provided_sig.as_bytes(), &expected_sig) {
        Some(id.to_owned())
    } else {
        None
    }
}