hyperlane-plugin-webhook 23.3.0

A production inbound HTTP webhook verification plugin for the Hyperlane framework featuring zero-allocation precomputed-midstate pure-Rust HMAC-SHA256 (Hex, Base64, and Stripe-style timestamped schemes), per-route secret rotation, timestamp skew enforcement, 64-shard bounded TTL replay-nonce caching, and verified WebhookEvent Context injection.
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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
use super::*;

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

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

/// Computes the RFC 4231 HMAC-SHA256 authentication tag of `data` under `key` with zero heap allocations.
///
/// # Arguments
///
/// - `&[u8]` - Secret key bytes.
/// - `&[u8]` - Message payload bytes.
///
/// # Returns
///
/// - `[u8; 32]` - 256-bit HMAC-SHA256 digest.
#[inline]
pub fn hmac_sha256(key: &[u8], data: &[u8]) -> [u8; 32] {
    HmacSha256Key::new(key).sign(data)
}

/// Compares two byte slices in constant time with respect to their contents using 8-byte word XORs.
///
/// # Arguments
///
/// - `&[u8]` - First byte slice.
/// - `&[u8]` - Second byte slice.
///
/// # Returns
///
/// - `bool` - `true` iff both slices have identical length and contents.
#[inline]
pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
    if a.len() != b.len() {
        return false;
    }
    let (a_chunks, a_rem): (&[[u8; 8]], &[u8]) = a.as_chunks::<8>();
    let (b_chunks, b_rem): (&[[u8; 8]], &[u8]) = b.as_chunks::<8>();
    let mut diff64: u64 = 0;
    for i in 0..a_chunks.len() {
        diff64 |= u64::from_ne_bytes(a_chunks[i]) ^ u64::from_ne_bytes(b_chunks[i]);
    }
    let mut diff8: u8 = 0;
    for i in 0..a_rem.len() {
        diff8 |= a_rem[i] ^ b_rem[i];
    }
    diff64 == 0 && diff8 == 0
}

/// Encodes a 32-byte digest into a 64-character lowercase hexadecimal string using a 2-byte pair LUT.
///
/// # Arguments
///
/// - `&[u8; 32]` - 256-bit digest.
///
/// # Returns
///
/// - `String` - 64-character lowercase hex string.
#[inline]
pub fn encode_hex_32(bytes: &[u8; 32]) -> String {
    let mut buf: Vec<u8> = vec![0u8; 64];
    for i in 0..32usize {
        let pair: [u8; 2] = HEX_ENCODE_PAIRS[bytes[i] as usize];
        buf[i * 2] = pair[0];
        buf[i * 2 + 1] = pair[1];
    }
    String::from_utf8(buf).unwrap_or_default()
}

/// Decodes a 64-character ASCII hex digest directly onto the stack using a branchless 256-entry LUT.
///
/// # Arguments
///
/// - `&str` - 64-character hex string.
///
/// # Returns
///
/// - `Option<[u8; 32]>` - Decoded 32-byte digest.
#[inline]
pub fn decode_hex_32(hex_str: &str) -> Option<[u8; 32]> {
    let raw: &[u8] = hex_str.trim().as_bytes();
    if raw.len() != 64 {
        return None;
    }
    let mut out: [u8; 32] = [0u8; 32];
    let mut err: u8 = 0;
    for i in 0..32usize {
        let hi: u8 = HEX_DECODE_LUT[raw[i * 2] as usize];
        let lo: u8 = HEX_DECODE_LUT[raw[i * 2 + 1] as usize];
        err |= hi | lo;
        out[i] = (hi << 4) | lo;
    }
    if (err & 0xF0) != 0 {
        return None;
    }
    Some(out)
}

/// Encodes a 32-byte digest into standard padded RFC 4648 base64 (44 characters).
///
/// # Arguments
///
/// - `&[u8; 32]` - 256-bit digest.
///
/// # Returns
///
/// - `String` - Standard padded base64 string.
#[inline]
pub fn encode_base64_32(bytes: &[u8; 32]) -> String {
    let mut out: Vec<u8> = vec![0u8; 44];
    let mut src: usize = 0;
    let mut dst: usize = 0;
    while src < 30 {
        let triple: u32 =
            ((bytes[src] as u32) << 16) | ((bytes[src + 1] as u32) << 8) | (bytes[src + 2] as u32);
        out[dst] = BASE64_ALPHABET[((triple >> 18) & 0x3F) as usize];
        out[dst + 1] = BASE64_ALPHABET[((triple >> 12) & 0x3F) as usize];
        out[dst + 2] = BASE64_ALPHABET[((triple >> 6) & 0x3F) as usize];
        out[dst + 3] = BASE64_ALPHABET[(triple & 0x3F) as usize];
        src += 3;
        dst += 4;
    }
    let pair: u32 = ((bytes[30] as u32) << 16) | ((bytes[31] as u32) << 8);
    out[40] = BASE64_ALPHABET[((pair >> 18) & 0x3F) as usize];
    out[41] = BASE64_ALPHABET[((pair >> 12) & 0x3F) as usize];
    out[42] = BASE64_ALPHABET[((pair >> 6) & 0x3F) as usize];
    out[43] = BYTE_EQ;
    String::from_utf8(out).unwrap_or_default()
}

/// Decodes a 32-byte RFC 4648 base64 digest (44-char padded or 43-char unpadded) using a branchless LUT.
///
/// # Arguments
///
/// - `&str` - Base64-encoded 32-byte digest.
///
/// # Returns
///
/// - `Option<[u8; 32]>` - Decoded 32-byte digest.
#[inline]
pub fn decode_base64_32(encoded: &str) -> Option<[u8; 32]> {
    let trimmed: &[u8] = encoded.trim().as_bytes();
    let unpadded: &[u8] = match trimmed.len() {
        44 if trimmed[43] == BYTE_EQ => &trimmed[..43],
        43 => trimmed,
        _ => return None,
    };
    let mut out: [u8; 32] = [0u8; 32];
    let mut err: u8 = 0;
    let mut out_idx: usize = 0;
    let mut i: usize = 0;
    while i < 40 {
        let a: u8 = BASE64_DECODE_LUT[unpadded[i] as usize];
        let b: u8 = BASE64_DECODE_LUT[unpadded[i + 1] as usize];
        let c: u8 = BASE64_DECODE_LUT[unpadded[i + 2] as usize];
        let d: u8 = BASE64_DECODE_LUT[unpadded[i + 3] as usize];
        err |= a;
        err |= b;
        err |= c;
        err |= d;
        let hi_part: u32 = (u32::from(a) << 18) | (u32::from(b) << 12);
        let lo_part: u32 = (u32::from(c) << 6) | u32::from(d);
        let triple: u32 = hi_part | lo_part;
        out[out_idx] = (triple >> 16) as u8;
        out[out_idx + 1] = ((triple >> 8) & 0xFF) as u8;
        out[out_idx + 2] = (triple & 0xFF) as u8;
        out_idx += 3;
        i += 4;
    }
    let a: u8 = BASE64_DECODE_LUT[unpadded[40] as usize];
    let b: u8 = BASE64_DECODE_LUT[unpadded[41] as usize];
    let c: u8 = BASE64_DECODE_LUT[unpadded[42] as usize];
    err |= a;
    err |= b;
    err |= c;
    if (err & 0xC0) != 0 || (c & 0x03) != 0 {
        return None;
    }
    let pair_hi: u32 = (u32::from(a) << 18) | (u32::from(b) << 12);
    let pair: u32 = pair_hi | (u32::from(c) << 6);
    out[30] = (pair >> 16) as u8;
    out[31] = ((pair >> 8) & 0xFF) as u8;
    Some(out)
}

/// Compresses one 64-byte FIPS 180-4 SHA-256 block into `state` using ARMv8 `sha2` SIMD instructions.
///
/// # Arguments
///
/// - `&mut [u32; 8]` - Running SHA-256 hash state.
/// - `&[u8; 64]` - 512-bit input block.
#[cfg(target_arch = "aarch64")]
#[cfg(target_feature = "sha2")]
#[cfg(target_endian = "little")]
#[inline]
pub(crate) fn sha256_compress_aarch64(state: &mut [u32; 8], block: &[u8; 64]) {
    unsafe {
        let abcd0: uint32x4_t = vld1q_u32(state.as_ptr());
        let efgh0: uint32x4_t = vld1q_u32(state.as_ptr().add(4));
        let mut abcd: uint32x4_t = abcd0;
        let mut efgh: uint32x4_t = efgh0;
        let ptr: *const u8 = block.as_ptr();
        let mut m0: uint32x4_t = vreinterpretq_u32_u8(vrev32q_u8(vld1q_u8(ptr)));
        let mut m1: uint32x4_t = vreinterpretq_u32_u8(vrev32q_u8(vld1q_u8(ptr.add(16))));
        let mut m2: uint32x4_t = vreinterpretq_u32_u8(vrev32q_u8(vld1q_u8(ptr.add(32))));
        let mut m3: uint32x4_t = vreinterpretq_u32_u8(vrev32q_u8(vld1q_u8(ptr.add(48))));
        let k: *const u32 = SHA256_K.as_ptr();
        let mut r: usize = 0;
        while r < 48 {
            let t0: uint32x4_t = vaddq_u32(m0, vld1q_u32(k.add(r)));
            let prev0: uint32x4_t = abcd;
            abcd = vsha256hq_u32(abcd, efgh, t0);
            efgh = vsha256h2q_u32(efgh, prev0, t0);
            m0 = vsha256su1q_u32(vsha256su0q_u32(m0, m1), m2, m3);
            let t1: uint32x4_t = vaddq_u32(m1, vld1q_u32(k.add(r + 4)));
            let prev1: uint32x4_t = abcd;
            abcd = vsha256hq_u32(abcd, efgh, t1);
            efgh = vsha256h2q_u32(efgh, prev1, t1);
            m1 = vsha256su1q_u32(vsha256su0q_u32(m1, m2), m3, m0);
            let t2: uint32x4_t = vaddq_u32(m2, vld1q_u32(k.add(r + 8)));
            let prev2: uint32x4_t = abcd;
            abcd = vsha256hq_u32(abcd, efgh, t2);
            efgh = vsha256h2q_u32(efgh, prev2, t2);
            m2 = vsha256su1q_u32(vsha256su0q_u32(m2, m3), m0, m1);
            let t3: uint32x4_t = vaddq_u32(m3, vld1q_u32(k.add(r + 12)));
            let prev3: uint32x4_t = abcd;
            abcd = vsha256hq_u32(abcd, efgh, t3);
            efgh = vsha256h2q_u32(efgh, prev3, t3);
            m3 = vsha256su1q_u32(vsha256su0q_u32(m3, m0), m1, m2);
            r += 16;
        }
        let t12: uint32x4_t = vaddq_u32(m0, vld1q_u32(k.add(48)));
        let prev12: uint32x4_t = abcd;
        abcd = vsha256hq_u32(abcd, efgh, t12);
        efgh = vsha256h2q_u32(efgh, prev12, t12);
        let t13: uint32x4_t = vaddq_u32(m1, vld1q_u32(k.add(52)));
        let prev13: uint32x4_t = abcd;
        abcd = vsha256hq_u32(abcd, efgh, t13);
        efgh = vsha256h2q_u32(efgh, prev13, t13);
        let t14: uint32x4_t = vaddq_u32(m2, vld1q_u32(k.add(56)));
        let prev14: uint32x4_t = abcd;
        abcd = vsha256hq_u32(abcd, efgh, t14);
        efgh = vsha256h2q_u32(efgh, prev14, t14);
        let t15: uint32x4_t = vaddq_u32(m3, vld1q_u32(k.add(60)));
        let prev15: uint32x4_t = abcd;
        abcd = vsha256hq_u32(abcd, efgh, t15);
        efgh = vsha256h2q_u32(efgh, prev15, t15);
        vst1q_u32(state.as_mut_ptr(), vaddq_u32(abcd, abcd0));
        vst1q_u32(state.as_mut_ptr().add(4), vaddq_u32(efgh, efgh0));
    }
}

/// Executes one register-rotating scalar SHA-256 compression round.
///
/// # Arguments
///
/// - `(u32, u32, u32, &mut u32)` - Registers `(a, b, c, &mut d)` where `d` receives next `e`.
/// - `(u32, u32, u32, &mut u32)` - Registers `(e, f, g, &mut h)` where `h` receives next `a`.
/// - `u32` - Message schedule word `w[i]`.
/// - `u32` - Round constant `SHA256_K[i]`.
#[inline(always)]
pub(crate) fn sha256_step(
    abcd: (u32, u32, u32, &mut u32),
    efgh: (u32, u32, u32, &mut u32),
    w: u32,
    k: u32,
) {
    let (a, b, c, d): (u32, u32, u32, &mut u32) = abcd;
    let (e, f, g, h): (u32, u32, u32, &mut u32) = efgh;
    let s1: u32 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25);
    let ch: u32 = (e & f) ^ ((!e) & g);
    let t1: u32 = (*h)
        .wrapping_add(s1)
        .wrapping_add(ch)
        .wrapping_add(k)
        .wrapping_add(w);
    let s0: u32 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22);
    let maj: u32 = (a & b) ^ (a & c) ^ (b & c);
    *d = (*d).wrapping_add(t1);
    *h = t1.wrapping_add(s0.wrapping_add(maj));
}

/// Computes one next SHA-256 message schedule word from its four predecessor words.
///
/// # Arguments
///
/// - `u32` - Word `w[t - 16]`.
/// - `u32` - Word `w[t - 15]`.
/// - `u32` - Word `w[t - 7]`.
/// - `u32` - Word `w[t - 2]`.
///
/// # Returns
///
/// - `u32` - Expanded schedule word `w[t]`.
#[inline(always)]
pub(crate) fn sha256_w_next(w0: u32, w1: u32, w9: u32, w14: u32) -> u32 {
    let s0: u32 = w1.rotate_right(7) ^ w1.rotate_right(18) ^ (w1 >> 3);
    let s1: u32 = w14.rotate_right(17) ^ w14.rotate_right(19) ^ (w14 >> 10);
    w0.wrapping_add(s0).wrapping_add(w9).wrapping_add(s1)
}

/// Expands the rolling 16-word SHA-256 message schedule in place.
///
/// # Arguments
///
/// - `&mut [u32; 16]` - Rolling 16-word message schedule window.
#[inline(always)]
pub(crate) fn sha256_expand_16(w: &mut [u32; 16]) {
    w[0] = sha256_w_next(w[0], w[1], w[9], w[14]);
    w[1] = sha256_w_next(w[1], w[2], w[10], w[15]);
    w[2] = sha256_w_next(w[2], w[3], w[11], w[0]);
    w[3] = sha256_w_next(w[3], w[4], w[12], w[1]);
    w[4] = sha256_w_next(w[4], w[5], w[13], w[2]);
    w[5] = sha256_w_next(w[5], w[6], w[14], w[3]);
    w[6] = sha256_w_next(w[6], w[7], w[15], w[4]);
    w[7] = sha256_w_next(w[7], w[8], w[0], w[5]);
    w[8] = sha256_w_next(w[8], w[9], w[1], w[6]);
    w[9] = sha256_w_next(w[9], w[10], w[2], w[7]);
    w[10] = sha256_w_next(w[10], w[11], w[3], w[8]);
    w[11] = sha256_w_next(w[11], w[12], w[4], w[9]);
    w[12] = sha256_w_next(w[12], w[13], w[5], w[10]);
    w[13] = sha256_w_next(w[13], w[14], w[6], w[11]);
    w[14] = sha256_w_next(w[14], w[15], w[7], w[12]);
    w[15] = sha256_w_next(w[15], w[0], w[8], w[13]);
}

/// Compresses one 64-byte FIPS 180-4 SHA-256 block using an unrolled rolling-16 scalar schedule.
///
/// # Arguments
///
/// - `&mut [u32; 8]` - Running SHA-256 hash state.
/// - `&[u8; 64]` - 512-bit input block.
#[inline]
pub(crate) fn sha256_compress_scalar(state: &mut [u32; 8], block: &[u8; 64]) {
    let mut w: [u32; 16] = [
        u32::from_be_bytes([block[0], block[1], block[2], block[3]]),
        u32::from_be_bytes([block[4], block[5], block[6], block[7]]),
        u32::from_be_bytes([block[8], block[9], block[10], block[11]]),
        u32::from_be_bytes([block[12], block[13], block[14], block[15]]),
        u32::from_be_bytes([block[16], block[17], block[18], block[19]]),
        u32::from_be_bytes([block[20], block[21], block[22], block[23]]),
        u32::from_be_bytes([block[24], block[25], block[26], block[27]]),
        u32::from_be_bytes([block[28], block[29], block[30], block[31]]),
        u32::from_be_bytes([block[32], block[33], block[34], block[35]]),
        u32::from_be_bytes([block[36], block[37], block[38], block[39]]),
        u32::from_be_bytes([block[40], block[41], block[42], block[43]]),
        u32::from_be_bytes([block[44], block[45], block[46], block[47]]),
        u32::from_be_bytes([block[48], block[49], block[50], block[51]]),
        u32::from_be_bytes([block[52], block[53], block[54], block[55]]),
        u32::from_be_bytes([block[56], block[57], block[58], block[59]]),
        u32::from_be_bytes([block[60], block[61], block[62], block[63]]),
    ];
    let mut a: u32 = state[0];
    let mut b: u32 = state[1];
    let mut c: u32 = state[2];
    let mut d: u32 = state[3];
    let mut e: u32 = state[4];
    let mut f: u32 = state[5];
    let mut g: u32 = state[6];
    let mut h: u32 = state[7];
    let mut round: usize = 0;
    while round < 64 {
        if round > 0 {
            sha256_expand_16(&mut w);
        }
        sha256_step((a, b, c, &mut d), (e, f, g, &mut h), w[0], SHA256_K[round]);
        sha256_step(
            (h, a, b, &mut c),
            (d, e, f, &mut g),
            w[1],
            SHA256_K[round + 1],
        );
        sha256_step(
            (g, h, a, &mut b),
            (c, d, e, &mut f),
            w[2],
            SHA256_K[round + 2],
        );
        sha256_step(
            (f, g, h, &mut a),
            (b, c, d, &mut e),
            w[3],
            SHA256_K[round + 3],
        );
        sha256_step(
            (e, f, g, &mut h),
            (a, b, c, &mut d),
            w[4],
            SHA256_K[round + 4],
        );
        sha256_step(
            (d, e, f, &mut g),
            (h, a, b, &mut c),
            w[5],
            SHA256_K[round + 5],
        );
        sha256_step(
            (c, d, e, &mut f),
            (g, h, a, &mut b),
            w[6],
            SHA256_K[round + 6],
        );
        sha256_step(
            (b, c, d, &mut e),
            (f, g, h, &mut a),
            w[7],
            SHA256_K[round + 7],
        );
        sha256_step(
            (a, b, c, &mut d),
            (e, f, g, &mut h),
            w[8],
            SHA256_K[round + 8],
        );
        sha256_step(
            (h, a, b, &mut c),
            (d, e, f, &mut g),
            w[9],
            SHA256_K[round + 9],
        );
        sha256_step(
            (g, h, a, &mut b),
            (c, d, e, &mut f),
            w[10],
            SHA256_K[round + 10],
        );
        sha256_step(
            (f, g, h, &mut a),
            (b, c, d, &mut e),
            w[11],
            SHA256_K[round + 11],
        );
        sha256_step(
            (e, f, g, &mut h),
            (a, b, c, &mut d),
            w[12],
            SHA256_K[round + 12],
        );
        sha256_step(
            (d, e, f, &mut g),
            (h, a, b, &mut c),
            w[13],
            SHA256_K[round + 13],
        );
        sha256_step(
            (c, d, e, &mut f),
            (g, h, a, &mut b),
            w[14],
            SHA256_K[round + 14],
        );
        sha256_step(
            (b, c, d, &mut e),
            (f, g, h, &mut a),
            w[15],
            SHA256_K[round + 15],
        );
        round += 16;
    }
    state[0] = state[0].wrapping_add(a);
    state[1] = state[1].wrapping_add(b);
    state[2] = state[2].wrapping_add(c);
    state[3] = state[3].wrapping_add(d);
    state[4] = state[4].wrapping_add(e);
    state[5] = state[5].wrapping_add(f);
    state[6] = state[6].wrapping_add(g);
    state[7] = state[7].wrapping_add(h);
}

/// Compresses one 64-byte FIPS 180-4 SHA-256 block into `state`, dispatching to ARMv8 `sha2` SIMD when available.
///
/// # Arguments
///
/// - `&mut [u32; 8]` - Running SHA-256 hash state.
/// - `&[u8; 64]` - 512-bit input block.
#[inline]
pub(crate) fn sha256_compress(state: &mut [u32; 8], block: &[u8; 64]) {
    if USE_AARCH64_SHA2 {
        #[cfg(target_arch = "aarch64")]
        #[cfg(target_feature = "sha2")]
        #[cfg(target_endian = "little")]
        sha256_compress_aarch64(state, block);
    } else {
        sha256_compress_scalar(state, block);
    }
}

/// Converts eight big-endian SHA-256 state words into a 32-byte digest array.
///
/// # Arguments
///
/// - `&[u32; 8]` - Final SHA-256 state words.
///
/// # Returns
///
/// - `[u8; 32]` - 256-bit SHA-256 digest.
#[inline(always)]
pub(crate) fn sha256_state_to_bytes(state: &[u32; 8]) -> [u8; 32] {
    let mut out: [u8; 32] = [0u8; 32];
    out[0..4].copy_from_slice(&state[0].to_be_bytes());
    out[4..8].copy_from_slice(&state[1].to_be_bytes());
    out[8..12].copy_from_slice(&state[2].to_be_bytes());
    out[12..16].copy_from_slice(&state[3].to_be_bytes());
    out[16..20].copy_from_slice(&state[4].to_be_bytes());
    out[20..24].copy_from_slice(&state[5].to_be_bytes());
    out[24..28].copy_from_slice(&state[6].to_be_bytes());
    out[28..32].copy_from_slice(&state[7].to_be_bytes());
    out
}

/// Compresses all 64-byte chunks of `data` followed by FIPS 180-4 padding from `init_state`.
///
/// # Arguments
///
/// - `[u32; 8]` - Initial or precomputed SHA-256 state.
/// - `u64` - Message bytes already absorbed into `init_state`.
/// - `&[u8]` - Remaining message bytes to hash.
///
/// # Returns
///
/// - `[u8; 32]` - Final 256-bit SHA-256 digest.
#[inline]
pub(crate) fn sha256_finish_from(mut state: [u32; 8], prefix_bytes: u64, data: &[u8]) -> [u8; 32] {
    let total_bytes: u64 = prefix_bytes.wrapping_add(data.len() as u64);
    let bit_len: u64 = total_bytes.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 tail0: [u8; 64] = [0u8; 64];
    tail0[..rem].copy_from_slice(rem_slice);
    tail0[rem] = 0x80;
    if rem < 56 {
        tail0[56..64].copy_from_slice(&bit_len.to_be_bytes());
        sha256_compress(&mut state, &tail0);
    } else {
        sha256_compress(&mut state, &tail0);
        let mut tail1: [u8; 64] = [0u8; 64];
        tail1[56..64].copy_from_slice(&bit_len.to_be_bytes());
        sha256_compress(&mut state, &tail1);
    }
    sha256_state_to_bytes(&state)
}

/// Finalizes the single-block outer HMAC-SHA256 compression directly from `opad_state` and `inner_digest`.
///
/// # Arguments
///
/// - `[u32; 8]` - Precomputed opad SHA-256 midstate (64 bytes absorbed).
/// - `&[u8; 32]` - 32-byte inner SHA-256 digest.
///
/// # Returns
///
/// - `[u8; 32]` - Final 256-bit HMAC-SHA256 tag.
#[inline(always)]
pub(crate) fn hmac_finish_outer(mut opad_state: [u32; 8], inner_digest: &[u8; 32]) -> [u8; 32] {
    let mut block: [u8; 64] = [0u8; 64];
    block[..32].copy_from_slice(inner_digest);
    block[32] = 0x80;
    block[56..64].copy_from_slice(&HMAC_OUTER_BIT_LEN_BE);
    sha256_compress(&mut opad_state, &block);
    sha256_state_to_bytes(&opad_state)
}

/// Checks whether `timestamp` lies within `±tolerance_secs` of `now_secs`.
///
/// # Arguments
///
/// - `u64` - Candidate Unix timestamp in seconds.
/// - `u64` - Current Unix timestamp in seconds.
/// - `u64` - Maximum allowed skew in seconds.
///
/// # Returns
///
/// - `bool` - `true` when within tolerance.
#[inline(always)]
pub(crate) fn is_timestamp_within_skew(timestamp: u64, now_secs: u64, tolerance_secs: u64) -> bool {
    timestamp.abs_diff(now_secs) <= tolerance_secs
}

/// Looks up a header value without cloning using an `O(1)` lowercase fast path.
///
/// # Arguments
///
/// - `&'a RequestHeaders` - Request header map.
/// - `&str` - Canonical lowercase header name.
///
/// # Returns
///
/// - `Option<&'a str>` - Last header value slice if present.
#[inline]
pub(crate) fn find_header_back_ref<'a>(
    headers: &'a RequestHeaders,
    lower_name: &str,
) -> Option<&'a str> {
    if let Some(vals) = headers.get(lower_name) {
        return vals.back().map(String::as_str);
    }
    headers
        .iter()
        .find(|(k, _): &(&String, &VecDeque<String>)| k.eq_ignore_ascii_case(lower_name))
        .and_then(|(_, v): (&String, &VecDeque<String>)| v.back().map(String::as_str))
}

/// Normalizes a path prefix by stripping trailing slashes while preserving `"/"`.
///
/// # Arguments
///
/// - `&str` - Raw path prefix.
///
/// # Returns
///
/// - `String` - Normalized prefix.
pub(crate) fn normalize_prefix(prefix: &str) -> String {
    let trimmed: &str = prefix.trim();
    if trimmed == "/" {
        return "/".to_owned();
    }
    let stripped: &str = trimmed.trim_end_matches('/');
    if stripped.is_empty() {
        "/".to_owned()
    } else {
        stripped.to_owned()
    }
}

/// Reports whether `path` matches normalized `prefix` on a segment boundary.
///
/// # Arguments
///
/// - `&str` - Incoming request path.
/// - `&str` - Normalized prefix.
///
/// # Returns
///
/// - `bool` - `true` when matched.
#[inline]
pub(crate) fn path_matches_prefix(path: &str, prefix: &str) -> bool {
    if prefix == "/" {
        return true;
    }
    if path.len() < prefix.len() {
        return false;
    }
    let Some(rest) = path.strip_prefix(prefix) else {
        return false;
    };
    rest.is_empty() || rest.as_bytes()[0] == BYTE_SLASH
}

/// Stores `event` in `ctx` under [`ATTR_WEBHOOK_EVENT`] reusing any existing slot allocation in-place.
///
/// # Arguments
///
/// - `&mut Context` - Active request context.
/// - `WebhookEvent` - Verified webhook delivery metadata.
#[inline]
pub(crate) fn store_webhook_event_attr(ctx: &mut Context, event: WebhookEvent) {
    if let Some(slot) = ctx.get_mut_attributes().get_mut(ATTR_WEBHOOK_EVENT_MAP_KEY) {
        if let Some(any_mut) = Arc::get_mut(slot)
            && let Some(existing) = any_mut.downcast_mut::<WebhookEvent>()
        {
            *existing = event;
            return;
        }
        *slot = Arc::new(event);
    } else {
        ctx.get_mut_attributes()
            .insert(ATTR_WEBHOOK_EVENT_MAP_KEY.to_owned(), Arc::new(event));
    }
}

/// Builds a pre-serialized static rejection HTTP wire buffer.
///
/// # Arguments
///
/// - `HttpStatus` - Rejection HTTP status code.
/// - `&[u8]` - Static plain-text body bytes.
///
/// # Returns
///
/// - `Vec<u8>` - Pre-serialized wire bytes.
pub(crate) fn build_reject_wire(status: HttpStatus, body: &[u8]) -> Vec<u8> {
    let mut resp: Response = Response::default();
    resp.set_status_code(status.code())
        .set_header(CONTENT_TYPE, REJECT_CONTENT_TYPE)
        .set_body(body);
    resp.build()
}