hyperlane-plugin-auth 23.2.0

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
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
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
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: &VecDeque<String>| values.back())
        .map(String::as_str)
}

/// Converts eight 32-bit big-endian SHA-256 state words into a 32-byte digest.
///
/// # Arguments
///
/// - `[u32; 8]` - Final SHA-256 hash state words.
///
/// # Returns
///
/// - `[u8; 32]` - 256-bit digest in big-endian byte order.
#[inline(always)]
pub(crate) fn sha256_words_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
}

/// Reports whether the running `aarch64` CPU supports ARMv8 SHA-256 crypto extensions.
///
/// # Returns
///
/// - `bool` - `true` when hardware `sha2` instructions are available.
#[cfg(all(target_arch = "aarch64", target_endian = "little"))]
#[inline(always)]
pub(crate) fn has_aarch64_sha2() -> bool {
    is_aarch64_feature_detected!("sha2")
}

/// Executes 4 ARMv8 hardware SHA-256 rounds for message vector `m` and round constants at `k_off`.
///
/// # Arguments
///
/// - `&mut uint32x4_t` - Working state words `[a, b, c, d]`.
/// - `&mut uint32x4_t` - Working state words `[e, f, g, h]`.
/// - `uint32x4_t` - Four scheduled message words.
/// - `usize` - Starting index into [`SHA256_K`].
#[cfg(all(target_arch = "aarch64", target_endian = "little"))]
#[target_feature(enable = "sha2")]
#[inline]
pub(crate) unsafe fn sha256_round4_aarch64(
    abcd: &mut uint32x4_t,
    efgh: &mut uint32x4_t,
    m: uint32x4_t,
    k_off: usize,
) {
    unsafe {
        let k: uint32x4_t = vld1q_u32(SHA256_K.as_ptr().add(k_off));
        let wk: uint32x4_t = vaddq_u32(m, k);
        let old_abcd: uint32x4_t = *abcd;
        *abcd = vsha256hq_u32(*abcd, *efgh, wk);
        *efgh = vsha256h2q_u32(*efgh, old_abcd, wk);
    }
}

/// Compresses one pre-loaded 16-word message block in NEON registers using ARMv8 SHA-256 instructions.
///
/// # Arguments
///
/// - `&mut uint32x4_t` - Running hash state `[H0, H1, H2, H3]`.
/// - `&mut uint32x4_t` - Running hash state `[H4, H5, H6, H7]`.
/// - `uint32x4_t` - Message words `w[0..4]`.
/// - `uint32x4_t` - Message words `w[4..8]`.
/// - `uint32x4_t` - Message words `w[8..12]`.
/// - `uint32x4_t` - Message words `w[12..16]`.
#[cfg(all(target_arch = "aarch64", target_endian = "little"))]
#[target_feature(enable = "sha2")]
#[inline]
pub(crate) unsafe fn sha256_compress_regs_aarch64(
    abcd: &mut uint32x4_t,
    efgh: &mut uint32x4_t,
    mut m0: uint32x4_t,
    mut m1: uint32x4_t,
    mut m2: uint32x4_t,
    mut m3: uint32x4_t,
) {
    let abcd_save: uint32x4_t = *abcd;
    let efgh_save: uint32x4_t = *efgh;
    unsafe {
        sha256_round4_aarch64(abcd, efgh, m0, 0);
        m0 = vsha256su1q_u32(vsha256su0q_u32(m0, m1), m2, m3);
        sha256_round4_aarch64(abcd, efgh, m1, 4);
        m1 = vsha256su1q_u32(vsha256su0q_u32(m1, m2), m3, m0);
        sha256_round4_aarch64(abcd, efgh, m2, 8);
        m2 = vsha256su1q_u32(vsha256su0q_u32(m2, m3), m0, m1);
        sha256_round4_aarch64(abcd, efgh, m3, 12);
        m3 = vsha256su1q_u32(vsha256su0q_u32(m3, m0), m1, m2);
        sha256_round4_aarch64(abcd, efgh, m0, 16);
        m0 = vsha256su1q_u32(vsha256su0q_u32(m0, m1), m2, m3);
        sha256_round4_aarch64(abcd, efgh, m1, 20);
        m1 = vsha256su1q_u32(vsha256su0q_u32(m1, m2), m3, m0);
        sha256_round4_aarch64(abcd, efgh, m2, 24);
        m2 = vsha256su1q_u32(vsha256su0q_u32(m2, m3), m0, m1);
        sha256_round4_aarch64(abcd, efgh, m3, 28);
        m3 = vsha256su1q_u32(vsha256su0q_u32(m3, m0), m1, m2);
        sha256_round4_aarch64(abcd, efgh, m0, 32);
        m0 = vsha256su1q_u32(vsha256su0q_u32(m0, m1), m2, m3);
        sha256_round4_aarch64(abcd, efgh, m1, 36);
        m1 = vsha256su1q_u32(vsha256su0q_u32(m1, m2), m3, m0);
        sha256_round4_aarch64(abcd, efgh, m2, 40);
        m2 = vsha256su1q_u32(vsha256su0q_u32(m2, m3), m0, m1);
        sha256_round4_aarch64(abcd, efgh, m3, 44);
        m3 = vsha256su1q_u32(vsha256su0q_u32(m3, m0), m1, m2);
        sha256_round4_aarch64(abcd, efgh, m0, 48);
        sha256_round4_aarch64(abcd, efgh, m1, 52);
        sha256_round4_aarch64(abcd, efgh, m2, 56);
        sha256_round4_aarch64(abcd, efgh, m3, 60);
        *abcd = vaddq_u32(*abcd, abcd_save);
        *efgh = vaddq_u32(*efgh, efgh_save);
    }
}

/// Loads one 64-byte big-endian block and compresses it into NEON state registers.
///
/// # Arguments
///
/// - `&mut uint32x4_t` - Running hash state `[H0, H1, H2, H3]`.
/// - `&mut uint32x4_t` - Running hash state `[H4, H5, H6, H7]`.
/// - `&[u8; 64]` - Input 64-byte message block.
#[cfg(all(target_arch = "aarch64", target_endian = "little"))]
#[target_feature(enable = "sha2")]
#[inline]
pub(crate) unsafe fn sha256_compress_block_regs_aarch64(
    abcd: &mut uint32x4_t,
    efgh: &mut uint32x4_t,
    block: &[u8; 64],
) {
    unsafe {
        let ptr: *const u8 = block.as_ptr();
        let m0: uint32x4_t = vreinterpretq_u32_u8(vrev32q_u8(vld1q_u8(ptr)));
        let m1: uint32x4_t = vreinterpretq_u32_u8(vrev32q_u8(vld1q_u8(ptr.add(16))));
        let m2: uint32x4_t = vreinterpretq_u32_u8(vrev32q_u8(vld1q_u8(ptr.add(32))));
        let m3: uint32x4_t = vreinterpretq_u32_u8(vrev32q_u8(vld1q_u8(ptr.add(48))));
        sha256_compress_regs_aarch64(abcd, efgh, m0, m1, m2, m3);
    }
}

/// Compresses one 64-byte block into `state` using ARMv8 SHA-256 hardware instructions.
///
/// # Arguments
///
/// - `&mut [u32; 8]` - Running SHA-256 state.
/// - `&[u8; 64]` - Input 64-byte message block.
#[cfg(all(target_arch = "aarch64", target_endian = "little"))]
#[target_feature(enable = "sha2")]
pub(crate) unsafe fn sha256_compress_aarch64(state: &mut [u32; 8], block: &[u8; 64]) {
    unsafe {
        let mut abcd: uint32x4_t = vld1q_u32(state.as_ptr());
        let mut efgh: uint32x4_t = vld1q_u32(state.as_ptr().add(4));
        sha256_compress_block_regs_aarch64(&mut abcd, &mut efgh, block);
        vst1q_u32(state.as_mut_ptr(), abcd);
        vst1q_u32(state.as_mut_ptr().add(4), efgh);
    }
}

/// Finishes SHA-256 hashing over `data` into NEON state registers using ARMv8 hardware instructions.
///
/// # Arguments
///
/// - `&mut uint32x4_t` - Running hash state `[H0, H1, H2, H3]`.
/// - `&mut uint32x4_t` - Running hash state `[H4, H5, H6, H7]`.
/// - `u64` - Number of message bytes already compressed into the initial state.
/// - `&[u8]` - Remaining message bytes.
#[cfg(all(target_arch = "aarch64", target_endian = "little"))]
#[target_feature(enable = "sha2")]
#[inline]
pub(crate) unsafe fn sha256_finish_regs_aarch64(
    abcd: &mut uint32x4_t,
    efgh: &mut uint32x4_t,
    prefix_bytes: u64,
    data: &[u8],
) {
    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>();
    unsafe {
        for block in blocks {
            sha256_compress_block_regs_aarch64(abcd, efgh, 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_block_regs_aarch64(abcd, efgh, &tail0);
        } else {
            sha256_compress_block_regs_aarch64(abcd, efgh, &tail0);
            let mut tail1: [u8; 64] = [0u8; 64];
            tail1[56..64].copy_from_slice(&bit_len.to_be_bytes());
            sha256_compress_block_regs_aarch64(abcd, efgh, &tail1);
        }
    }
}

/// Computes a finalized SHA-256 digest from `init_state` using ARMv8 hardware instructions.
///
/// # Arguments
///
/// - `[u32; 8]` - Initial or precomputed SHA-256 state.
/// - `u64` - Number of message bytes already compressed into `init_state`.
/// - `&[u8]` - Remaining message bytes.
///
/// # Returns
///
/// - `[u8; 32]` - Final 256-bit SHA-256 digest.
#[cfg(all(target_arch = "aarch64", target_endian = "little"))]
#[target_feature(enable = "sha2")]
pub(crate) unsafe fn sha256_finish_from_aarch64(
    init_state: [u32; 8],
    prefix_bytes: u64,
    data: &[u8],
) -> [u8; 32] {
    unsafe {
        let mut abcd: uint32x4_t = vld1q_u32(init_state.as_ptr());
        let mut efgh: uint32x4_t = vld1q_u32(init_state.as_ptr().add(4));
        sha256_finish_regs_aarch64(&mut abcd, &mut efgh, prefix_bytes, data);
        let mut out: [u8; 32] = [0u8; 32];
        vst1q_u8(out.as_mut_ptr(), vrev32q_u8(vreinterpretq_u8_u32(abcd)));
        vst1q_u8(
            out.as_mut_ptr().add(16),
            vrev32q_u8(vreinterpretq_u8_u32(efgh)),
        );
        out
    }
}

/// Computes an HMAC-SHA256 tag from precomputed inner/outer midstates using ARMv8 SHA-256 instructions.
///
/// # Arguments
///
/// - `[u32; 8]` - Precomputed SHA-256 state after compressing `ipad`.
/// - `[u32; 8]` - Precomputed SHA-256 state after compressing `opad`.
/// - `&[u8]` - Input message bytes.
///
/// # Returns
///
/// - `[u8; 32]` - 256-bit HMAC-SHA256 tag.
#[cfg(all(target_arch = "aarch64", target_endian = "little"))]
#[target_feature(enable = "sha2")]
pub(crate) unsafe fn hmac_sha256_mac_aarch64(
    inner_state: [u32; 8],
    outer_state: [u32; 8],
    data: &[u8],
) -> [u8; 32] {
    unsafe {
        let mut inner_abcd: uint32x4_t = vld1q_u32(inner_state.as_ptr());
        let mut inner_efgh: uint32x4_t = vld1q_u32(inner_state.as_ptr().add(4));
        sha256_finish_regs_aarch64(&mut inner_abcd, &mut inner_efgh, 64, data);
        let mut outer_abcd: uint32x4_t = vld1q_u32(outer_state.as_ptr());
        let mut outer_efgh: uint32x4_t = vld1q_u32(outer_state.as_ptr().add(4));
        let pad_m2: uint32x4_t = vld1q_u32(HMAC_OUTER_PAD_M2.as_ptr());
        let pad_m3: uint32x4_t = vld1q_u32(HMAC_OUTER_PAD_M3.as_ptr());
        sha256_compress_regs_aarch64(
            &mut outer_abcd,
            &mut outer_efgh,
            inner_abcd,
            inner_efgh,
            pad_m2,
            pad_m3,
        );
        let mut out: [u8; 32] = [0u8; 32];
        vst1q_u8(
            out.as_mut_ptr(),
            vrev32q_u8(vreinterpretq_u8_u32(outer_abcd)),
        );
        vst1q_u8(
            out.as_mut_ptr().add(16),
            vrev32q_u8(vreinterpretq_u8_u32(outer_efgh)),
        );
        out
    }
}

/// Computes a one-shot HMAC-SHA256 tag keeping inner and outer states in NEON registers.
///
/// # Arguments
///
/// - `&[u8]` - Secret key bytes.
/// - `&[u8]` - Input message bytes.
///
/// # Returns
///
/// - `[u8; 32]` - 256-bit HMAC-SHA256 tag.
#[cfg(all(target_arch = "aarch64", target_endian = "little"))]
#[target_feature(enable = "sha2")]
pub(crate) unsafe fn hmac_sha256_oneshot_aarch64(key: &[u8], data: &[u8]) -> [u8; 32] {
    unsafe {
        let mut key_block: [u8; 64] = [0u8; 64];
        if key.len() > 64 {
            let hashed: [u8; 32] = sha256_finish_from_aarch64(SHA256_INIT, 0, key);
            key_block[..32].copy_from_slice(&hashed);
        } else {
            key_block[..key.len()].copy_from_slice(key);
        }
        let kptr: *const u8 = key_block.as_ptr();
        let k0: uint8x16_t = vld1q_u8(kptr);
        let k1: uint8x16_t = vld1q_u8(kptr.add(16));
        let k2: uint8x16_t = vld1q_u8(kptr.add(32));
        let k3: uint8x16_t = vld1q_u8(kptr.add(48));
        let ipad_mask: uint8x16_t = vdupq_n_u8(0x36);
        let opad_mask: uint8x16_t = vdupq_n_u8(0x5c);
        let init_abcd: uint32x4_t = vld1q_u32(SHA256_INIT.as_ptr());
        let init_efgh: uint32x4_t = vld1q_u32(SHA256_INIT.as_ptr().add(4));
        let mut inner_abcd: uint32x4_t = init_abcd;
        let mut inner_efgh: uint32x4_t = init_efgh;
        sha256_compress_regs_aarch64(
            &mut inner_abcd,
            &mut inner_efgh,
            vreinterpretq_u32_u8(vrev32q_u8(veorq_u8(k0, ipad_mask))),
            vreinterpretq_u32_u8(vrev32q_u8(veorq_u8(k1, ipad_mask))),
            vreinterpretq_u32_u8(vrev32q_u8(veorq_u8(k2, ipad_mask))),
            vreinterpretq_u32_u8(vrev32q_u8(veorq_u8(k3, ipad_mask))),
        );
        sha256_finish_regs_aarch64(&mut inner_abcd, &mut inner_efgh, 64, data);
        let mut outer_abcd: uint32x4_t = init_abcd;
        let mut outer_efgh: uint32x4_t = init_efgh;
        sha256_compress_regs_aarch64(
            &mut outer_abcd,
            &mut outer_efgh,
            vreinterpretq_u32_u8(vrev32q_u8(veorq_u8(k0, opad_mask))),
            vreinterpretq_u32_u8(vrev32q_u8(veorq_u8(k1, opad_mask))),
            vreinterpretq_u32_u8(vrev32q_u8(veorq_u8(k2, opad_mask))),
            vreinterpretq_u32_u8(vrev32q_u8(veorq_u8(k3, opad_mask))),
        );
        let pad_m2: uint32x4_t = vld1q_u32(HMAC_OUTER_PAD_M2.as_ptr());
        let pad_m3: uint32x4_t = vld1q_u32(HMAC_OUTER_PAD_M3.as_ptr());
        sha256_compress_regs_aarch64(
            &mut outer_abcd,
            &mut outer_efgh,
            inner_abcd,
            inner_efgh,
            pad_m2,
            pad_m3,
        );
        let mut out: [u8; 32] = [0u8; 32];
        vst1q_u8(
            out.as_mut_ptr(),
            vrev32q_u8(vreinterpretq_u8_u32(outer_abcd)),
        );
        vst1q_u8(
            out.as_mut_ptr().add(16),
            vrev32q_u8(vreinterpretq_u8_u32(outer_efgh)),
        );
        out
    }
}

/// Software fallback finalizing SHA-256 into eight big-endian state words.
///
/// # Arguments
///
/// - `[u32; 8]` - Initial or precomputed SHA-256 state.
/// - `u64` - Number of message bytes already compressed into `state`.
/// - `&[u8]` - Remaining message bytes to hash.
///
/// # Returns
///
/// - `[u32; 8]` - Final SHA-256 hash state words.
#[inline]
pub(crate) fn sha256_finish_words_sw(
    mut state: [u32; 8],
    prefix_bytes: u64,
    data: &[u8],
) -> [u32; 8] {
    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_sw(&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_sw(&mut state, &tail0);
    } else {
        sha256_compress_sw(&mut state, &tail0);
        let mut tail1: [u8; 64] = [0u8; 64];
        tail1[56..64].copy_from_slice(&bit_len.to_be_bytes());
        sha256_compress_sw(&mut state, &tail1);
    }
    state
}

/// 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(init_state: [u32; 8], prefix_bytes: u64, data: &[u8]) -> [u8; 32] {
    #[cfg(all(target_arch = "aarch64", target_endian = "little"))]
    if has_aarch64_sha2() {
        return unsafe { sha256_finish_from_aarch64(init_state, prefix_bytes, data) };
    }
    sha256_words_to_bytes(sha256_finish_words_sw(init_state, prefix_bytes, data))
}

/// 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 16 message schedule words into `state` using the portable software SHA-256 kernel.
///
/// # Arguments
///
/// - `&mut [u32; 8]` - Running hash state.
/// - `[u32; 16]` - Input 16 big-endian 32-bit message words.
#[inline]
pub(crate) fn sha256_compress_words_sw(state: &mut [u32; 8], mut w: [u32; 16]) {
    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]);
}

/// Compresses one 64-byte SHA-256 block into `state` using the portable software implementation.
///
/// # Arguments
///
/// - `&mut [u32; 8]` - Running hash state.
/// - `&[u8; 64]` - Input block.
pub(crate) fn sha256_compress_sw(state: &mut [u32; 8], block: &[u8; 64]) {
    let 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]]),
    ];
    sha256_compress_words_sw(state, w);
}

/// Compresses one 64-byte SHA-256 block into `state`, dispatching to hardware crypto when available.
///
/// # Arguments
///
/// - `&mut [u32; 8]` - Running hash state.
/// - `&[u8; 64]` - Input block.
#[inline]
pub(crate) fn sha256_compress(state: &mut [u32; 8], block: &[u8; 64]) {
    #[cfg(all(target_arch = "aarch64", target_endian = "little"))]
    if has_aarch64_sha2() {
        unsafe { sha256_compress_aarch64(state, block) };
        return;
    }
    sha256_compress_sw(state, block);
}

/// 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] {
    #[cfg(all(target_arch = "aarch64", target_endian = "little"))]
    if has_aarch64_sha2() {
        return unsafe { hmac_sha256_oneshot_aarch64(key, data) };
    }
    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);
    let start: usize = out.len();
    out.resize(start + encoded_len, 0u8);
    let dst: &mut [u8] = &mut out[start..];
    let (triples, rem): (&[[u8; 3]], &[u8]) = input.as_chunks::<3>();
    let full_out: usize = triples.len() * 4;
    let (dst_quads, _): (&mut [[u8; 4]], &mut [u8]) = dst[..full_out].as_chunks_mut::<4>();
    for (chunk, dst_quad) in triples.iter().zip(dst_quads.iter_mut()) {
        let triple: u32 = ((chunk[0] as u32) << 16) | ((chunk[1] as u32) << 8) | (chunk[2] as u32);
        dst_quad[0] = BASE64URL_ALPHABET[((triple >> 18) & 0x3F) as usize];
        dst_quad[1] = BASE64URL_ALPHABET[((triple >> 12) & 0x3F) as usize];
        dst_quad[2] = BASE64URL_ALPHABET[((triple >> 6) & 0x3F) as usize];
        dst_quad[3] = BASE64URL_ALPHABET[(triple & 0x3F) as usize];
    }
    let tail: &mut [u8] = &mut dst[full_out..];
    if rem.len() == 1 {
        let val: u32 = (rem[0] as u32) << 16;
        tail[0] = BASE64URL_ALPHABET[((val >> 18) & 0x3F) as usize];
        tail[1] = 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);
        tail[0] = BASE64URL_ALPHABET[((val >> 18) & 0x3F) as usize];
        tail[1] = BASE64URL_ALPHABET[((val >> 12) & 0x3F) as usize];
        tail[2] = 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 (quads, rem): (&[[u8; 4]], &[u8]) = bytes.as_chunks::<4>();
    let mut pos: usize = quads.len() * 3;
    let mut invalid: u8 = 0;
    let (dst_triples, _): (&mut [[u8; 3]], &mut [u8]) = out[..pos].as_chunks_mut::<3>();
    for (chunk, dst) in quads.iter().zip(dst_triples.iter_mut()) {
        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];
        invalid |= (a | b) | (c | d);
        let quad: u32 = ((a as u32) << 18) | ((b as u32) << 12) | ((c as u32) << 6) | (d as u32);
        dst[0] = ((quad >> 16) & 0xFF) as u8;
        dst[1] = ((quad >> 8) & 0xFF) as u8;
        dst[2] = (quad & 0xFF) as u8;
    }
    if (invalid & 0x80) != 0 {
        return None;
    }
    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)
}

/// Appends a JSON-quoted string to `buf`, avoiding `serde_json` overhead when no escaping is needed.
///
/// # Arguments
///
/// - `&mut StackJsonBuf` - Destination JSON byte buffer.
/// - `&str` - String value to serialize.
///
/// # Returns
///
/// - `Result<(), AuthError>` - `Ok(())` on success or [`AuthError::InvalidCredentials`] on write error.
#[inline]
pub(crate) fn write_json_str_fast(buf: &mut StackJsonBuf, s: &str) -> Result<(), AuthError> {
    let bytes: &[u8] = s.as_bytes();
    let needs_escape: bool = bytes
        .iter()
        .any(|&b: &u8| b < 0x20 || b == ASCII_QUOTE || b == ASCII_BACKSLASH);
    if !needs_escape {
        buf.push_byte(ASCII_QUOTE);
        buf.push_slice(bytes);
        buf.push_byte(ASCII_QUOTE);
        return Ok(());
    }
    to_writer(buf, s).map_err(|_| AuthError::InvalidCredentials)
}

/// Appends an unsigned 64-bit decimal integer to `buf` using a 2-digit lookup table.
///
/// # Arguments
///
/// - `&mut StackJsonBuf` - Destination JSON byte buffer.
/// - `u64` - Unsigned integer to format.
#[inline]
pub(crate) fn write_u64_fast(buf: &mut StackJsonBuf, mut val: u64) {
    let mut digits: [u8; 20] = [0u8; 20];
    let mut pos: usize = 20;
    while val >= 100 {
        let pair: usize = ((val % 100) as usize) * 2;
        val /= 100;
        pos -= 2;
        digits[pos] = DEC_DIGITS_LUT[pair];
        digits[pos + 1] = DEC_DIGITS_LUT[pair + 1];
    }
    if val < 10 {
        pos -= 1;
        digits[pos] = ASCII_ZERO + (val as u8);
    } else {
        let pair: usize = (val as usize) * 2;
        pos -= 2;
        digits[pos] = DEC_DIGITS_LUT[pair];
        digits[pos + 1] = DEC_DIGITS_LUT[pair + 1];
    }
    buf.push_slice(&digits[pos..]);
}

/// Serializes [`JwtClaims`] directly into `buf` without `serde` serializer dispatch for standard claims.
///
/// # Arguments
///
/// - `&JwtClaims` - Claims payload to encode.
/// - `&mut StackJsonBuf` - Destination JSON byte buffer.
///
/// # Returns
///
/// - `Result<(), AuthError>` - `Ok(())` on success or [`AuthError::InvalidCredentials`] on failure.
#[inline]
pub(crate) fn write_jwt_claims_json(
    claims: &JwtClaims,
    buf: &mut StackJsonBuf,
) -> Result<(), AuthError> {
    let JwtClaims {
        sub,
        iss,
        aud,
        exp,
        nbf,
        iat,
        jti,
        roles,
        extra,
    } = claims;
    buf.push_slice(JSON_SUB_PREFIX);
    write_json_str_fast(buf, sub)?;
    if let Some(val) = iss {
        buf.push_slice(JSON_ISS_PREFIX);
        write_json_str_fast(buf, val)?;
    }
    if let Some(val) = aud {
        buf.push_slice(JSON_AUD_PREFIX);
        write_json_str_fast(buf, val)?;
    }
    if let Some(val) = *exp {
        buf.push_slice(JSON_EXP_PREFIX);
        write_u64_fast(buf, val);
    }
    if let Some(val) = *nbf {
        buf.push_slice(JSON_NBF_PREFIX);
        write_u64_fast(buf, val);
    }
    if let Some(val) = *iat {
        buf.push_slice(JSON_IAT_PREFIX);
        write_u64_fast(buf, val);
    }
    if let Some(val) = jti {
        buf.push_slice(JSON_JTI_PREFIX);
        write_json_str_fast(buf, val)?;
    }
    if !roles.is_empty() {
        buf.push_slice(JSON_ROLES_PREFIX);
        for (idx, role) in roles.iter().enumerate() {
            if idx > 0 {
                buf.push_byte(ASCII_COMMA);
            }
            write_json_str_fast(buf, role)?;
        }
        buf.push_byte(ASCII_RBRACKET);
    }
    for (k, v) in extra {
        buf.push_byte(ASCII_COMMA);
        write_json_str_fast(buf, k)?;
        buf.push_byte(ASCII_COLON);
        to_writer(&mut *buf, v).map_err(|_| AuthError::InvalidCredentials)?;
    }
    buf.push_byte(ASCII_RBRACE);
    Ok(())
}