hyperlane-plugin-auth 22.14.1

A zero-external-crypto-dependency authentication and RBAC plugin for the Hyperlane framework providing pure-Rust HS256 JWT with kid rotation, API key and HTTP Basic authenticators, extensible async Authenticator traits, and constant-time verification.
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
use super::*;

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

/// Borrows the last value of a lowercased HTTP request header without heap allocation.
///
/// # Arguments
///
/// - `&'a Request` - Incoming HTTP request.
/// - `&str` - Lowercased header key name.
///
/// # Returns
///
/// - `Option<&'a str>` - Borrowed last header value, if present.
#[inline(always)]
pub(crate) fn request_header_back<'a>(req: &'a Request, lower_key: &str) -> Option<&'a str> {
    req.get_headers()
        .get(lower_key)
        .and_then(|values: &RequestHeadersValue| values.back())
        .map(String::as_str)
}

/// Compresses all 64-byte chunks of `data` followed by FIPS 180-4 padding from `init_state` and `prefix_bytes`.
///
/// # Arguments
///
/// - `[u32; 8]` - Initial or precomputed SHA-256 state.
/// - `u64` - Number of message bytes already compressed 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);
    }
    let mut out: [u8; 32] = [0u8; 32];
    let b0: [u8; 4] = state[0].to_be_bytes();
    let b1: [u8; 4] = state[1].to_be_bytes();
    let b2: [u8; 4] = state[2].to_be_bytes();
    let b3: [u8; 4] = state[3].to_be_bytes();
    let b4: [u8; 4] = state[4].to_be_bytes();
    let b5: [u8; 4] = state[5].to_be_bytes();
    let b6: [u8; 4] = state[6].to_be_bytes();
    let b7: [u8; 4] = state[7].to_be_bytes();
    out[0..4].copy_from_slice(&b0);
    out[4..8].copy_from_slice(&b1);
    out[8..12].copy_from_slice(&b2);
    out[12..16].copy_from_slice(&b3);
    out[16..20].copy_from_slice(&b4);
    out[20..24].copy_from_slice(&b5);
    out[24..28].copy_from_slice(&b6);
    out[28..32].copy_from_slice(&b7);
    out
}

/// 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 fn sha256(data: &[u8]) -> [u8; 32] {
    sha256_finish_from(SHA256_INIT, 0, data)
}

/// Executes one register-rotating SHA-256 compression step without shifting all 8 state words.
///
/// # Arguments
///
/// - `(u32, u32, u32, &mut u32)` - Registers `(a, b, c, &mut d)` where `d` is updated to the next `e`.
/// - `(u32, u32, u32, &mut u32)` - Registers `(e, f, g, &mut h)` where `h` is updated to the next `a`.
/// - `u32` - Message schedule word `w[i]`.
/// - `u32` - Round constant `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 using compile-time indices.
///
/// # 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]);
}

/// Executes 16 unrolled SHA-256 rounds against the current 16-word schedule window.
///
/// # Arguments
///
/// - `&mut [u32; 8]` - Working registers `[a, b, c, d, e, f, g, h]`.
/// - `&[u32; 16]` - Current 16-word message schedule window.
/// - `usize` - Starting index into [`SHA256_K`] (`0`, `16`, `32`, or `48`).
#[inline(always)]
pub(crate) fn sha256_rounds_16(v: &mut [u32; 8], w: &[u32; 16], k_base: usize) {
    let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut h]: [u32; 8] = *v;
    sha256_step((a, b, c, &mut d), (e, f, g, &mut h), w[0], SHA256_K[k_base]);
    sha256_step(
        (h, a, b, &mut c),
        (d, e, f, &mut g),
        w[1],
        SHA256_K[k_base + 1],
    );
    sha256_step(
        (g, h, a, &mut b),
        (c, d, e, &mut f),
        w[2],
        SHA256_K[k_base + 2],
    );
    sha256_step(
        (f, g, h, &mut a),
        (b, c, d, &mut e),
        w[3],
        SHA256_K[k_base + 3],
    );
    sha256_step(
        (e, f, g, &mut h),
        (a, b, c, &mut d),
        w[4],
        SHA256_K[k_base + 4],
    );
    sha256_step(
        (d, e, f, &mut g),
        (h, a, b, &mut c),
        w[5],
        SHA256_K[k_base + 5],
    );
    sha256_step(
        (c, d, e, &mut f),
        (g, h, a, &mut b),
        w[6],
        SHA256_K[k_base + 6],
    );
    sha256_step(
        (b, c, d, &mut e),
        (f, g, h, &mut a),
        w[7],
        SHA256_K[k_base + 7],
    );
    sha256_step(
        (a, b, c, &mut d),
        (e, f, g, &mut h),
        w[8],
        SHA256_K[k_base + 8],
    );
    sha256_step(
        (h, a, b, &mut c),
        (d, e, f, &mut g),
        w[9],
        SHA256_K[k_base + 9],
    );
    sha256_step(
        (g, h, a, &mut b),
        (c, d, e, &mut f),
        w[10],
        SHA256_K[k_base + 10],
    );
    sha256_step(
        (f, g, h, &mut a),
        (b, c, d, &mut e),
        w[11],
        SHA256_K[k_base + 11],
    );
    sha256_step(
        (e, f, g, &mut h),
        (a, b, c, &mut d),
        w[12],
        SHA256_K[k_base + 12],
    );
    sha256_step(
        (d, e, f, &mut g),
        (h, a, b, &mut c),
        w[13],
        SHA256_K[k_base + 13],
    );
    sha256_step(
        (c, d, e, &mut f),
        (g, h, a, &mut b),
        w[14],
        SHA256_K[k_base + 14],
    );
    sha256_step(
        (b, c, d, &mut e),
        (f, g, h, &mut a),
        w[15],
        SHA256_K[k_base + 15],
    );
    *v = [a, b, c, d, e, f, g, h];
}

/// Compresses one 64-byte SHA-256 block into `state`.
///
/// # Arguments
///
/// - `&mut [u32; 8]` - Running hash state.
/// - `&[u8; 64]` - Input block.
pub(crate) fn sha256_compress(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 v: [u32; 8] = *state;
    sha256_rounds_16(&mut v, &w, 0);
    sha256_expand_16(&mut w);
    sha256_rounds_16(&mut v, &w, 16);
    sha256_expand_16(&mut w);
    sha256_rounds_16(&mut v, &w, 32);
    sha256_expand_16(&mut w);
    sha256_rounds_16(&mut v, &w, 48);
    state[0] = state[0].wrapping_add(v[0]);
    state[1] = state[1].wrapping_add(v[1]);
    state[2] = state[2].wrapping_add(v[2]);
    state[3] = state[3].wrapping_add(v[3]);
    state[4] = state[4].wrapping_add(v[4]);
    state[5] = state[5].wrapping_add(v[5]);
    state[6] = state[6].wrapping_add(v[6]);
    state[7] = state[7].wrapping_add(v[7]);
}

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

/// 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 fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
    if a.len() != b.len() {
        return false;
    }
    let mut diff: u8 = 0;
    for i in 0..a.len() {
        diff |= a[i] ^ b[i];
    }
    diff == 0
}

/// Appends unpadded RFC 4648 base64url bytes of `input` directly into `out`.
///
/// # Arguments
///
/// - `&[u8]` - Raw bytes to encode.
/// - `&mut Vec<u8>` - Destination ASCII byte buffer.
#[inline]
pub(crate) fn base64url_encode_into(input: &[u8], out: &mut Vec<u8>) {
    let encoded_len: usize = (input.len() * 4).div_ceil(3);
    out.reserve(encoded_len);
    let (triples, rem): (&[[u8; 3]], &[u8]) = input.as_chunks::<3>();
    for chunk in triples {
        let triple: u32 = ((chunk[0] as u32) << 16) | ((chunk[1] as u32) << 8) | (chunk[2] as u32);
        out.extend_from_slice(&[
            BASE64URL_ALPHABET[((triple >> 18) & 0x3F) as usize],
            BASE64URL_ALPHABET[((triple >> 12) & 0x3F) as usize],
            BASE64URL_ALPHABET[((triple >> 6) & 0x3F) as usize],
            BASE64URL_ALPHABET[(triple & 0x3F) as usize],
        ]);
    }
    if rem.len() == 1 {
        let val: u32 = (rem[0] as u32) << 16;
        out.extend_from_slice(&[
            BASE64URL_ALPHABET[((val >> 18) & 0x3F) as usize],
            BASE64URL_ALPHABET[((val >> 12) & 0x3F) as usize],
        ]);
    } else if rem.len() == 2 {
        let val: u32 = ((rem[0] as u32) << 16) | ((rem[1] as u32) << 8);
        out.extend_from_slice(&[
            BASE64URL_ALPHABET[((val >> 18) & 0x3F) as usize],
            BASE64URL_ALPHABET[((val >> 12) & 0x3F) as usize],
            BASE64URL_ALPHABET[((val >> 6) & 0x3F) as usize],
        ]);
    }
}

/// Encodes `input` using unpadded RFC 4648 base64url.
///
/// # Arguments
///
/// - `&[u8]` - Raw bytes to encode.
///
/// # Returns
///
/// - `String` - Unpadded base64url string.
#[inline]
pub fn base64url_encode(input: &[u8]) -> String {
    let mut buf: Vec<u8> = Vec::with_capacity((input.len() * 4).div_ceil(3));
    base64url_encode_into(input, &mut buf);
    String::from_utf8(buf).unwrap_or_default()
}

/// Decodes base64 or base64url bytes into a caller-supplied slice using a 256-byte lookup table.
///
/// # Arguments
///
/// - `&[u8]` - Trimmed input ASCII bytes without trailing `=`.
/// - `&[u8; 256]` - Lookup table mapping ASCII bytes to 6-bit values or [`B64_INVALID`].
/// - `&mut [u8]` - Destination slice with capacity at least `(bytes.len() * 3) / 4`.
///
/// # Returns
///
/// - `Option<usize>` - Number of bytes written, or `None` when input is malformed.
#[inline]
pub(crate) fn decode_base64_into(bytes: &[u8], table: &[u8; 256], out: &mut [u8]) -> Option<usize> {
    if bytes.len() % 4 == 1 {
        return None;
    }
    let decoded_len: usize = (bytes.len() * 3) / 4;
    if out.len() < decoded_len {
        return None;
    }
    let mut pos: usize = 0;
    let (quads, rem): (&[[u8; 4]], &[u8]) = bytes.as_chunks::<4>();
    for chunk in quads {
        let a: u8 = table[chunk[0] as usize];
        let b: u8 = table[chunk[1] as usize];
        let c: u8 = table[chunk[2] as usize];
        let d: u8 = table[chunk[3] as usize];
        let ab: u8 = a | b;
        let cd: u8 = c | d;
        if ((ab | cd) & 0x80) != 0 {
            return None;
        }
        let quad: u32 = ((a as u32) << 18) | ((b as u32) << 12) | ((c as u32) << 6) | (d as u32);
        out[pos] = ((quad >> 16) & 0xFF) as u8;
        out[pos + 1] = ((quad >> 8) & 0xFF) as u8;
        out[pos + 2] = (quad & 0xFF) as u8;
        pos += 3;
    }
    if rem.len() == 2 {
        let a: u8 = table[rem[0] as usize];
        let b: u8 = table[rem[1] as usize];
        if ((a | b) & 0x80) != 0 {
            return None;
        }
        let val: u32 = ((a as u32) << 18) | ((b as u32) << 12);
        out[pos] = ((val >> 16) & 0xFF) as u8;
        pos += 1;
    } else if rem.len() == 3 {
        let a: u8 = table[rem[0] as usize];
        let b: u8 = table[rem[1] as usize];
        let c: u8 = table[rem[2] as usize];
        let ab: u8 = a | b;
        if ((ab | c) & 0x80) != 0 {
            return None;
        }
        let val: u32 = ((a as u32) << 18) | ((b as u32) << 12) | ((c as u32) << 6);
        out[pos] = ((val >> 16) & 0xFF) as u8;
        out[pos + 1] = ((val >> 8) & 0xFF) as u8;
        pos += 2;
    }
    Some(pos)
}

/// Decodes a 32-byte HS256 base64url signature directly onto the stack with zero heap allocations.
///
/// # Arguments
///
/// - `&str` - Base64url signature segment.
///
/// # Returns
///
/// - `Option<[u8; 32]>` - Decoded 32-byte MAC, or `None` when length or encoding is invalid.
#[inline]
pub(crate) fn decode_base64url_32(input: &str) -> Option<[u8; 32]> {
    let trimmed: &[u8] = input.trim_end_matches('=').as_bytes();
    if trimmed.len() != HMAC_SIG_B64_LEN {
        return None;
    }
    let mut out: [u8; 32] = [0u8; 32];
    let written: usize = decode_base64_into(trimmed, &BASE64URL_DECODE_TABLE, &mut out)?;
    if written == 32 { Some(out) } else { None }
}

/// Decodes unpadded (or padded) base64 / base64url text into raw bytes.
///
/// # Arguments
///
/// - `&str` - Encoded string.
/// - `bool` - `true` for base64url, `false` for standard base64.
///
/// # Returns
///
/// - `Option<Vec<u8>>` - Decoded bytes, or `None` on malformed input.
#[inline]
pub(crate) fn decode_base64_inner(input: &str, url_safe: bool) -> Option<Vec<u8>> {
    let bytes: &[u8] = input.trim_end_matches('=').as_bytes();
    if bytes.len() % 4 == 1 {
        return None;
    }
    let table: &[u8; 256] = if url_safe {
        &BASE64URL_DECODE_TABLE
    } else {
        &BASE64_STD_DECODE_TABLE
    };
    let decoded_len: usize = (bytes.len() * 3) / 4;
    let mut out: Vec<u8> = vec![0u8; decoded_len];
    let written: usize = decode_base64_into(bytes, table, &mut out)?;
    out.truncate(written);
    Some(out)
}

/// Decodes an unpadded RFC 4648 base64url string.
///
/// # Arguments
///
/// - `&str` - Base64url-encoded string.
///
/// # Returns
///
/// - `Option<Vec<u8>>` - Decoded bytes, or `None` if malformed.
#[inline]
pub fn base64url_decode(input: &str) -> Option<Vec<u8>> {
    decode_base64_inner(input, true)
}

/// Decodes a standard RFC 4648 base64 string (used by HTTP Basic authentication).
///
/// # Arguments
///
/// - `&str` - Standard base64-encoded string.
///
/// # Returns
///
/// - `Option<Vec<u8>>` - Decoded bytes, or `None` if malformed.
#[inline]
pub fn base64_decode(input: &str) -> Option<Vec<u8>> {
    decode_base64_inner(input, false)
}

/// Extracts a case-insensitive prefix-stripped token from an `Authorization` header.
///
/// # Arguments
///
/// - `&'a str` - Raw `Authorization` header value.
/// - `&str` - Expected lowercase scheme prefix ending with space (for example `"bearer "`).
///
/// # Returns
///
/// - `Option<&'a str>` - Trimmed credential payload, or `None` when the scheme does not match.
#[inline]
pub(crate) fn strip_auth_scheme<'a>(header: &'a str, lowercase_prefix: &str) -> Option<&'a str> {
    let trimmed: &'a str = header.trim();
    if trimmed.len() < lowercase_prefix.len() {
        return None;
    }
    let (head, tail): (&'a str, &'a str) = trimmed.split_at(lowercase_prefix.len());
    if head.eq_ignore_ascii_case(lowercase_prefix) {
        let token: &'a str = tail.trim();
        if token.is_empty() { None } else { Some(token) }
    } else {
        None
    }
}

/// Pre-encodes a compact base64url HS256 JWT header for an optional `kid`.
///
/// # Arguments
///
/// - `Option<&str>` - Optional default `kid`.
///
/// # Returns
///
/// - `String` - Base64url-encoded JWT header segment.
pub(crate) fn encode_hs256_header_b64(default_kid: Option<&str>) -> String {
    let Some(kid) = default_kid else {
        return DEFAULT_HS256_HEADER_B64.to_owned();
    };
    let header: JwtHeader = JwtHeader {
        alg: JWT_ALG_HS256.to_owned(),
        typ: Some(JWT_TYP_JWT.to_owned()),
        kid: Some(kid.to_owned()),
    };
    let json_bytes: Vec<u8> = to_vec(&header).unwrap_or_default();
    base64url_encode(&json_bytes)
}