hyperlane-plugin-auth 23.3.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
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
use super::*;

/// Precomputed HMAC-SHA256 key implementation.
impl HmacSha256Key {
    /// Derives precomputed inner and outer SHA-256 midstates from `key`.
    ///
    /// # Arguments
    ///
    /// - `&[u8]` - Secret key bytes.
    ///
    /// # Returns
    ///
    /// - `Self` - Precomputed HMAC key state.
    #[inline]
    pub(crate) fn new(key: &[u8]) -> Self {
        let mut key_block: [u8; 64] = [0u8; 64];
        if key.len() > 64 {
            let hashed: [u8; 32] = sha256(key);
            key_block[..32].copy_from_slice(&hashed);
        } else {
            key_block[..key.len()].copy_from_slice(key);
        }
        let mut ipad: [u8; 64] = [0u8; 64];
        let mut opad: [u8; 64] = [0u8; 64];
        let mut i: usize = 0;
        while i < 64 {
            ipad[i] = key_block[i] ^ 0x36;
            opad[i] = key_block[i] ^ 0x5c;
            i += 1;
        }
        let mut inner_state: [u32; 8] = SHA256_INIT;
        let mut outer_state: [u32; 8] = SHA256_INIT;
        sha256_compress(&mut inner_state, &ipad);
        sha256_compress(&mut outer_state, &opad);
        Self {
            inner_state,
            outer_state,
        }
    }

    /// Computes the HMAC-SHA256 tag of `data` using the precomputed key midstates.
    ///
    /// # Arguments
    ///
    /// - `&[u8]` - Input message bytes.
    ///
    /// # Returns
    ///
    /// - `[u8; 32]` - 256-bit HMAC-SHA256 tag.
    #[inline]
    pub(crate) fn mac(&self, data: &[u8]) -> [u8; 32] {
        let Self {
            inner_state,
            outer_state,
        } = *self;
        #[cfg(all(target_arch = "aarch64", target_endian = "little"))]
        if has_aarch64_sha2() {
            return unsafe { hmac_sha256_mac_aarch64(inner_state, outer_state, data) };
        }
        let inner_words: [u32; 8] = sha256_finish_words_sw(inner_state, 64, data);
        let outer_w: [u32; 16] = [
            inner_words[0],
            inner_words[1],
            inner_words[2],
            inner_words[3],
            inner_words[4],
            inner_words[5],
            inner_words[6],
            inner_words[7],
            HMAC_OUTER_PAD_M2[0],
            0,
            0,
            0,
            0,
            0,
            0,
            HMAC_OUTER_PAD_M3[3],
        ];
        let mut state: [u32; 8] = outer_state;
        sha256_compress_words_sw(&mut state, outer_w);
        sha256_words_to_bytes(state)
    }
}

/// Stack-backed JSON serialization buffer implementation.
impl StackJsonBuf {
    /// Creates an empty [`StackJsonBuf`] without heap allocation.
    ///
    /// # Returns
    ///
    /// - `Self` - Empty stack buffer.
    #[inline]
    pub(crate) fn new() -> Self {
        Self {
            stack: [0u8; JWT_STACK_ENCODE_CAP],
            len: 0,
            heap: None,
        }
    }

    /// Appends a single byte into stack storage or spills seamlessly to the heap.
    ///
    /// # Arguments
    ///
    /// - `u8` - Byte to append.
    #[inline(always)]
    pub(crate) fn push_byte(&mut self, byte: u8) {
        let Self { stack, len, heap } = self;
        if let Some(vec) = heap {
            vec.push(byte);
            return;
        }
        if *len < stack.len() {
            stack[*len] = byte;
            *len += 1;
        } else {
            let mut vec: Vec<u8> = Vec::with_capacity(*len + 64);
            vec.extend_from_slice(&stack[..*len]);
            vec.push(byte);
            *heap = Some(vec);
        }
    }

    /// Appends a byte slice into stack storage or spills seamlessly to the heap.
    ///
    /// # Arguments
    ///
    /// - `&[u8]` - Source byte slice.
    #[inline(always)]
    pub(crate) fn push_slice(&mut self, buf: &[u8]) {
        let Self { stack, len, heap } = self;
        if let Some(vec) = heap {
            vec.extend_from_slice(buf);
            return;
        }
        let next_len: usize = len.saturating_add(buf.len());
        if next_len <= stack.len() {
            stack[*len..next_len].copy_from_slice(buf);
            *len = next_len;
        } else {
            let mut vec: Vec<u8> = Vec::with_capacity(next_len + 64);
            vec.extend_from_slice(&stack[..*len]);
            vec.extend_from_slice(buf);
            *heap = Some(vec);
        }
    }

    /// Returns the written bytes as a contiguous slice.
    ///
    /// # Returns
    ///
    /// - `&[u8]` - Written JSON bytes.
    #[inline]
    pub(crate) fn as_slice(&self) -> &[u8] {
        let Self { stack, len, heap } = self;
        match heap {
            Some(buf) => buf.as_slice(),
            None => &stack[..*len],
        }
    }
}

/// Implements [`Write`] for [`StackJsonBuf`].
impl Write for StackJsonBuf {
    /// Appends `buf` to stack storage or spills seamlessly to the heap.
    ///
    /// # Arguments
    ///
    /// - `&[u8]` - Source byte slice.
    ///
    /// # Returns
    ///
    /// - `io::Result<usize>` - Number of bytes written.
    #[inline]
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        let Self { stack, len, heap } = self;
        if let Some(vec) = heap {
            vec.extend_from_slice(buf);
            return Ok(buf.len());
        }
        let next_len: usize = len.saturating_add(buf.len());
        if next_len <= stack.len() {
            stack[*len..next_len].copy_from_slice(buf);
            *len = next_len;
        } else {
            let mut vec: Vec<u8> = Vec::with_capacity(next_len);
            vec.extend_from_slice(&stack[..*len]);
            vec.extend_from_slice(buf);
            *heap = Some(vec);
        }
        Ok(buf.len())
    }

    /// No-op flush for in-memory buffer.
    ///
    /// # Returns
    ///
    /// - `io::Result<()>` - Always `Ok(())`.
    #[inline]
    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}

/// Formatting for [`AuthError`].
impl Display for AuthError {
    /// Formats a human-readable error summary for [`AuthError`].
    ///
    /// # Arguments
    ///
    /// - `&mut Formatter<'_>` - Output formatter.
    ///
    /// # Returns
    ///
    /// - `fmt::Result` - Formatting outcome.
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::MissingCredentials => f.write_str(MSG_AUTH_MISSING),
            Self::InvalidCredentials => f.write_str(MSG_AUTH_INVALID),
            Self::TokenExpired => f.write_str(MSG_AUTH_EXPIRED),
            Self::TokenNotYetValid => f.write_str(MSG_AUTH_NOT_YET_VALID),
            Self::UnsupportedAlgorithm => f.write_str(MSG_AUTH_UNSUPPORTED_ALG),
            Self::ClaimMismatch => f.write_str(MSG_AUTH_CLAIM_MISMATCH),
            Self::Forbidden => f.write_str(MSG_AUTH_FORBIDDEN),
        }
    }
}

/// Implements [`Error`] for [`AuthError`].
impl Error for AuthError {}

/// Single-pass Serde serialization for [`JwtClaims`] without `#[serde(flatten)]` overhead.
impl Serialize for JwtClaims {
    /// Serializes standard claims and flattened `extra` entries directly into a JSON map.
    ///
    /// # Arguments
    ///
    /// - `S` - Serde serializer.
    ///
    /// # Returns
    ///
    /// - `Result<S::Ok, S::Error>` - Serialized representation or error.
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let Self {
            sub,
            iss,
            aud,
            exp,
            nbf,
            iat,
            jti,
            roles,
            extra,
        } = self;
        let mut field_count: usize = 1 + extra.len();
        if iss.is_some() {
            field_count += 1;
        }
        if aud.is_some() {
            field_count += 1;
        }
        if exp.is_some() {
            field_count += 1;
        }
        if nbf.is_some() {
            field_count += 1;
        }
        if iat.is_some() {
            field_count += 1;
        }
        if jti.is_some() {
            field_count += 1;
        }
        if !roles.is_empty() {
            field_count += 1;
        }
        let mut map: S::SerializeMap = serializer.serialize_map(Some(field_count))?;
        map.serialize_entry(CLAIM_SUB, sub)?;
        if let Some(val) = iss {
            map.serialize_entry(CLAIM_ISS, val)?;
        }
        if let Some(val) = aud {
            map.serialize_entry(CLAIM_AUD, val)?;
        }
        if let Some(val) = exp {
            map.serialize_entry(CLAIM_EXP, val)?;
        }
        if let Some(val) = nbf {
            map.serialize_entry(CLAIM_NBF, val)?;
        }
        if let Some(val) = iat {
            map.serialize_entry(CLAIM_IAT, val)?;
        }
        if let Some(val) = jti {
            map.serialize_entry(CLAIM_JTI, val)?;
        }
        if !roles.is_empty() {
            map.serialize_entry(CLAIM_ROLES, roles)?;
        }
        for (k, v) in extra {
            map.serialize_entry(k, v)?;
        }
        map.end()
    }
}

/// Zero-allocation Serde [`Visitor`] implementation for [`JwtClaimField`].
impl<'de> Visitor<'de> for JwtClaimFieldVisitor {
    type Value = JwtClaimField;

    /// Describes the expected JSON object key for error diagnostics.
    ///
    /// # Arguments
    ///
    /// - `&mut Formatter<'_>` - Output formatter.
    ///
    /// # Returns
    ///
    /// - `fmt::Result` - Formatting outcome.
    fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        formatter.write_str(EXPECTING_JWT_FIELD)
    }

    /// Matches borrowed JSON object keys against standard JWT claims without allocating.
    ///
    /// # Arguments
    ///
    /// - `&str` - Decoded JSON key string.
    ///
    /// # Returns
    ///
    /// - `Result<Self::Value, E>` - Matched field variant.
    #[inline]
    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
    where
        E: de::Error,
    {
        Ok(match value {
            CLAIM_SUB => JwtClaimField::Sub,
            CLAIM_ISS => JwtClaimField::Iss,
            CLAIM_AUD => JwtClaimField::Aud,
            CLAIM_EXP => JwtClaimField::Exp,
            CLAIM_NBF => JwtClaimField::Nbf,
            CLAIM_IAT => JwtClaimField::Iat,
            CLAIM_JTI => JwtClaimField::Jti,
            CLAIM_ROLES => JwtClaimField::Roles,
            _ => JwtClaimField::Extra(value.to_owned()),
        })
    }

    /// Matches owned JSON object keys without re-allocating when storing into `extra`.
    ///
    /// # Arguments
    ///
    /// - `String` - Owned decoded JSON key string.
    ///
    /// # Returns
    ///
    /// - `Result<Self::Value, E>` - Matched field variant.
    #[inline]
    fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
    where
        E: de::Error,
    {
        Ok(match value.as_str() {
            CLAIM_SUB => JwtClaimField::Sub,
            CLAIM_ISS => JwtClaimField::Iss,
            CLAIM_AUD => JwtClaimField::Aud,
            CLAIM_EXP => JwtClaimField::Exp,
            CLAIM_NBF => JwtClaimField::Nbf,
            CLAIM_IAT => JwtClaimField::Iat,
            CLAIM_JTI => JwtClaimField::Jti,
            CLAIM_ROLES => JwtClaimField::Roles,
            _ => JwtClaimField::Extra(value),
        })
    }
}

/// Implements [`Deserialize`] for [`JwtClaimField`] using `deserialize_identifier`.
impl<'de> Deserialize<'de> for JwtClaimField {
    /// Deserializes a JSON claim field name with zero heap allocation for standard claims.
    ///
    /// # Arguments
    ///
    /// - `D` - Serde deserializer.
    ///
    /// # Returns
    ///
    /// - `Result<Self, D::Error>` - Parsed claim field discriminator.
    #[inline]
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        deserializer.deserialize_identifier(JwtClaimFieldVisitor)
    }
}

/// Zero-buffering Serde [`Visitor`] implementation for [`JwtClaims`].
impl<'de> Visitor<'de> for JwtClaimsVisitor {
    type Value = JwtClaims;

    /// Describes the expected input structure for Serde error diagnostics.
    ///
    /// # Arguments
    ///
    /// - `&mut Formatter<'_>` - Output formatter.
    ///
    /// # Returns
    ///
    /// - `fmt::Result` - Formatting outcome.
    fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        formatter.write_str(EXPECTING_JWT_CLAIMS)
    }

    /// Streams map entries directly into [`JwtClaims`] without buffering into `Content` trees.
    ///
    /// # Arguments
    ///
    /// - `A` - Serde map access iterator.
    ///
    /// # Returns
    ///
    /// - `Result<Self::Value, A::Error>` - Deserialized [`JwtClaims`] or error.
    fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
    where
        A: MapAccess<'de>,
    {
        let mut seen: u8 = 0;
        let mut sub: Option<String> = None;
        let mut iss: Option<String> = None;
        let mut aud: Option<String> = None;
        let mut exp: Option<u64> = None;
        let mut nbf: Option<u64> = None;
        let mut iat: Option<u64> = None;
        let mut jti: Option<String> = None;
        let mut roles: Option<Vec<String>> = None;
        let mut extra: HashMap<String, Value> = HashMap::new();
        while let Some(field) = map.next_key::<JwtClaimField>()? {
            match field {
                JwtClaimField::Sub => {
                    if (seen & CLAIM_BIT_SUB) != 0 {
                        return Err(<A::Error as de::Error>::duplicate_field(CLAIM_SUB));
                    }
                    seen |= CLAIM_BIT_SUB;
                    sub = Some(map.next_value()?);
                }
                JwtClaimField::Iss => {
                    if (seen & CLAIM_BIT_ISS) != 0 {
                        return Err(<A::Error as de::Error>::duplicate_field(CLAIM_ISS));
                    }
                    seen |= CLAIM_BIT_ISS;
                    iss = map.next_value()?;
                }
                JwtClaimField::Aud => {
                    if (seen & CLAIM_BIT_AUD) != 0 {
                        return Err(<A::Error as de::Error>::duplicate_field(CLAIM_AUD));
                    }
                    seen |= CLAIM_BIT_AUD;
                    aud = map.next_value()?;
                }
                JwtClaimField::Exp => {
                    if (seen & CLAIM_BIT_EXP) != 0 {
                        return Err(<A::Error as de::Error>::duplicate_field(CLAIM_EXP));
                    }
                    seen |= CLAIM_BIT_EXP;
                    exp = map.next_value()?;
                }
                JwtClaimField::Nbf => {
                    if (seen & CLAIM_BIT_NBF) != 0 {
                        return Err(<A::Error as de::Error>::duplicate_field(CLAIM_NBF));
                    }
                    seen |= CLAIM_BIT_NBF;
                    nbf = map.next_value()?;
                }
                JwtClaimField::Iat => {
                    if (seen & CLAIM_BIT_IAT) != 0 {
                        return Err(<A::Error as de::Error>::duplicate_field(CLAIM_IAT));
                    }
                    seen |= CLAIM_BIT_IAT;
                    iat = map.next_value()?;
                }
                JwtClaimField::Jti => {
                    if (seen & CLAIM_BIT_JTI) != 0 {
                        return Err(<A::Error as de::Error>::duplicate_field(CLAIM_JTI));
                    }
                    seen |= CLAIM_BIT_JTI;
                    jti = map.next_value()?;
                }
                JwtClaimField::Roles => {
                    if (seen & CLAIM_BIT_ROLES) != 0 {
                        return Err(<A::Error as de::Error>::duplicate_field(CLAIM_ROLES));
                    }
                    seen |= CLAIM_BIT_ROLES;
                    roles = Some(map.next_value()?);
                }
                JwtClaimField::Extra(key) => {
                    let value: Value = map.next_value()?;
                    extra.insert(key, value);
                }
            }
        }
        let sub: String = sub.ok_or_else(|| <A::Error as de::Error>::missing_field(CLAIM_SUB))?;
        Ok(JwtClaims {
            sub,
            iss,
            aud,
            exp,
            nbf,
            iat,
            jti,
            roles: roles.unwrap_or_default(),
            extra,
        })
    }
}

/// Single-pass Serde deserialization for [`JwtClaims`] without `#[serde(flatten)]` buffering.
impl<'de> Deserialize<'de> for JwtClaims {
    /// Deserializes a JSON claims object directly via [`JwtClaimsVisitor`].
    ///
    /// # Arguments
    ///
    /// - `D` - Serde deserializer.
    ///
    /// # Returns
    ///
    /// - `Result<Self, D::Error>` - Deserialized [`JwtClaims`] or error.
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        deserializer.deserialize_map(JwtClaimsVisitor)
    }
}

/// Inherent implementation of [`JwtClaims`].
impl JwtClaims {
    /// Creates a minimal [`JwtClaims`] payload for `subject` expiring in `ttl_secs`.
    ///
    /// # Arguments
    ///
    /// - `S` - Subject identifier convertible into `String`.
    /// - `u64` - Lifetime in seconds from current Unix time.
    ///
    /// # Returns
    ///
    /// - `Self` - Constructed claims payload.
    pub fn new<S>(subject: S, ttl_secs: u64) -> Self
    where
        S: Into<String>,
    {
        let now: u64 = auth_now_secs();
        Self {
            sub: subject.into(),
            iss: None,
            aud: None,
            exp: Some(now.saturating_add(ttl_secs)),
            nbf: Some(now),
            iat: Some(now),
            jti: None,
            roles: Vec::new(),
            extra: HashMap::new(),
        }
    }

    /// Attaches RBAC roles to this claims payload.
    ///
    /// # Arguments
    ///
    /// - `I` - Iterator of role names.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated claims payload.
    pub fn with_roles<I, S>(mut self, roles: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.set_roles(roles.into_iter().map(Into::into).collect());
        self
    }

    /// Sets the `iss` issuer claim.
    ///
    /// # Arguments
    ///
    /// - `S` - Issuer identifier.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated claims payload.
    pub fn with_issuer<S>(mut self, issuer: S) -> Self
    where
        S: Into<String>,
    {
        self.set_iss(Some(issuer.into()));
        self
    }

    /// Sets the `aud` audience claim.
    ///
    /// # Arguments
    ///
    /// - `S` - Audience identifier.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated claims payload.
    pub fn with_audience<S>(mut self, audience: S) -> Self
    where
        S: Into<String>,
    {
        self.set_aud(Some(audience.into()));
        self
    }
}

/// Inherent implementation of [`JwtCodec`].
impl JwtCodec {
    /// Creates an HS256 [`JwtCodec`] signed and verified with `secret`.
    ///
    /// # Arguments
    ///
    /// - `S` - Shared HMAC-SHA256 secret bytes convertible into `Vec<u8>`.
    ///
    /// # Returns
    ///
    /// - `Self` - Ready JWT codec with 60 s default clock-skew leeway.
    pub fn new<S>(secret: S) -> Self
    where
        S: Into<Vec<u8>>,
    {
        let default_secret: Vec<u8> = secret.into();
        let default_hmac: HmacSha256Key = HmacSha256Key::new(&default_secret);
        Self {
            default_secret,
            default_hmac,
            default_kid: None,
            default_header_b64: DEFAULT_HS256_HEADER_B64.to_owned(),
            keyring: hash_map_xx_hash3_64(),
            keyring_hmac: hash_map_xx_hash3_64(),
            leeway_secs: DEFAULT_JWT_LEEWAY_SECS,
            required_issuer: None,
            required_audience: None,
        }
    }

    /// Registers an additional verification key under `kid` for seamless key rotation.
    ///
    /// # Arguments
    ///
    /// - `K` - Key identifier convertible into `String`.
    /// - `S` - Secret bytes for this `kid`.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated codec.
    pub fn with_key<K, S>(mut self, kid: K, secret: S) -> Self
    where
        K: Into<String>,
        S: Into<Vec<u8>>,
    {
        let Self {
            keyring,
            keyring_hmac,
            ..
        } = &mut self;
        let kid_str: String = kid.into();
        let secret_bytes: Vec<u8> = secret.into();
        let precomputed: HmacSha256Key = HmacSha256Key::new(&secret_bytes);
        keyring.insert(kid_str.clone(), secret_bytes);
        keyring_hmac.insert(kid_str, precomputed);
        self
    }

    /// Sets the default `kid` stamped on newly encoded tokens (and registers its secret if absent).
    ///
    /// # Arguments
    ///
    /// - `K` - Active signing key identifier.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated codec.
    pub fn with_default_kid<K>(mut self, kid: K) -> Self
    where
        K: Into<String>,
    {
        let Self {
            default_kid,
            default_secret,
            default_hmac,
            default_header_b64,
            keyring,
            keyring_hmac,
            ..
        } = &mut self;
        let kid_str: String = kid.into();
        if !keyring.contains_key(&kid_str) {
            keyring.insert(kid_str.clone(), default_secret.clone());
            keyring_hmac.insert(kid_str.clone(), *default_hmac);
        }
        *default_header_b64 = encode_hs256_header_b64(Some(&kid_str));
        *default_kid = Some(kid_str);
        self
    }

    /// Sets the allowed clock-skew leeway in seconds for `exp` and `nbf` checks.
    ///
    /// # Arguments
    ///
    /// - `u64` - Leeway in seconds.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated codec.
    pub fn with_leeway_secs(mut self, leeway_secs: u64) -> Self {
        let Self {
            leeway_secs: slot, ..
        } = &mut self;
        *slot = leeway_secs;
        self
    }

    /// Requires every decoded token's `iss` claim to match `issuer`.
    ///
    /// # Arguments
    ///
    /// - `S` - Required issuer string.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated codec.
    pub fn with_required_issuer<S>(mut self, issuer: S) -> Self
    where
        S: Into<String>,
    {
        let Self {
            required_issuer, ..
        } = &mut self;
        *required_issuer = Some(issuer.into());
        self
    }

    /// Requires every decoded token's `aud` claim to match `audience`.
    ///
    /// # Arguments
    ///
    /// - `S` - Required audience string.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated codec.
    pub fn with_required_audience<S>(mut self, audience: S) -> Self
    where
        S: Into<String>,
    {
        let Self {
            required_audience, ..
        } = &mut self;
        *required_audience = Some(audience.into());
        self
    }

    /// Encodes and signs `claims` into a compact HS256 JWT (`header.payload.signature`).
    ///
    /// # Arguments
    ///
    /// - `&JwtClaims` - Claims payload to sign.
    ///
    /// # Returns
    ///
    /// - `Result<String, AuthError>` - Compact JWT string, or [`AuthError::InvalidCredentials`] on serialization failure.
    pub fn encode(&self, claims: &JwtClaims) -> Result<String, AuthError> {
        let Self {
            default_hmac,
            default_kid,
            default_header_b64,
            keyring_hmac,
            ..
        } = self;
        let mut claims_buf: StackJsonBuf = StackJsonBuf::new();
        write_jwt_claims_json(claims, &mut claims_buf)?;
        let claims_json: &[u8] = claims_buf.as_slice();
        let claims_b64_len: usize = (claims_json.len() * 4).div_ceil(3);
        let total_len: usize = default_header_b64.len() + 1 + claims_b64_len + 1 + HMAC_SIG_B64_LEN;
        let mut token_bytes: Vec<u8> = Vec::with_capacity(total_len);
        token_bytes.extend_from_slice(default_header_b64.as_bytes());
        token_bytes.push(ASCII_DOT);
        base64url_encode_into(claims_json, &mut token_bytes);
        let hmac_key: &HmacSha256Key = match default_kid {
            Some(kid) => keyring_hmac.get(kid).unwrap_or(default_hmac),
            None => default_hmac,
        };
        let mac: [u8; 32] = hmac_key.mac(&token_bytes);
        token_bytes.push(ASCII_DOT);
        base64url_encode_into(&mac, &mut token_bytes);
        String::from_utf8(token_bytes).map_err(|_| AuthError::InvalidCredentials)
    }

    /// Verifies and decodes a compact HS256 JWT at timestamp `now_secs`.
    ///
    /// # Arguments
    ///
    /// - `&str` - Compact JWT string (`header.payload.signature`).
    /// - `u64` - Current Unix timestamp in seconds.
    ///
    /// # Returns
    ///
    /// - `Result<JwtClaims, AuthError>` - Verified [`JwtClaims`] or detailed [`AuthError`].
    pub fn decode_at(&self, token: &str, now_secs: u64) -> Result<JwtClaims, AuthError> {
        let Self {
            default_hmac,
            default_kid,
            default_header_b64,
            keyring_hmac,
            leeway_secs,
            required_issuer,
            required_audience,
            ..
        } = self;
        let (header_b64, rest): (&str, &str) =
            token.split_once('.').ok_or(AuthError::InvalidCredentials)?;
        let (payload_b64, sig_b64): (&str, &str) =
            rest.split_once('.').ok_or(AuthError::InvalidCredentials)?;
        if sig_b64.contains('.')
            || header_b64.is_empty()
            || payload_b64.is_empty()
            || sig_b64.is_empty()
        {
            return Err(AuthError::InvalidCredentials);
        }
        let hmac_key: &HmacSha256Key = if header_b64 == default_header_b64.as_str() {
            match default_kid {
                Some(kid) => keyring_hmac.get(kid).ok_or(AuthError::InvalidCredentials)?,
                None => default_hmac,
            }
        } else if header_b64 == DEFAULT_HS256_HEADER_B64 {
            default_hmac
        } else {
            let trimmed_hdr: &[u8] = header_b64.trim_end_matches('=').as_bytes();
            let decoded_hdr_len: usize = (trimmed_hdr.len() * 3) / 4;
            let mut hdr_stack: [u8; JWT_STACK_HEADER_CAP] = [0u8; JWT_STACK_HEADER_CAP];
            let hdr_heap: Vec<u8>;
            let hdr_slice: &[u8] = if decoded_hdr_len <= JWT_STACK_HEADER_CAP {
                let written: usize =
                    decode_base64_into(trimmed_hdr, &BASE64URL_DECODE_TABLE, &mut hdr_stack)
                        .ok_or(AuthError::InvalidCredentials)?;
                &hdr_stack[..written]
            } else {
                hdr_heap = base64url_decode(header_b64).ok_or(AuthError::InvalidCredentials)?;
                &hdr_heap
            };
            let header: JwtHeaderRef<'_> =
                from_slice(hdr_slice).map_err(|_| AuthError::InvalidCredentials)?;
            if header.alg.as_ref() != JWT_ALG_HS256 {
                return Err(AuthError::UnsupportedAlgorithm);
            }
            match header.kid.as_deref() {
                Some(kid) => keyring_hmac.get(kid).ok_or(AuthError::InvalidCredentials)?,
                None => default_hmac,
            }
        };
        let provided_sig: [u8; 32] =
            decode_base64url_32(sig_b64).ok_or(AuthError::InvalidCredentials)?;
        let signed_len: usize = header_b64.len() + 1 + payload_b64.len();
        let expected_mac: [u8; 32] = hmac_key.mac(&token.as_bytes()[..signed_len]);
        if !constant_time_eq(&provided_sig, &expected_mac) {
            return Err(AuthError::InvalidCredentials);
        }
        let trimmed_payload: &[u8] = payload_b64.trim_end_matches('=').as_bytes();
        let decoded_payload_len: usize = (trimmed_payload.len() * 3) / 4;
        let claims: JwtClaims = if decoded_payload_len <= JWT_STACK_FAST_PAYLOAD_CAP {
            let mut fast_stack: [u8; JWT_STACK_FAST_PAYLOAD_CAP] =
                [0u8; JWT_STACK_FAST_PAYLOAD_CAP];
            let written: usize =
                decode_base64_into(trimmed_payload, &BASE64URL_DECODE_TABLE, &mut fast_stack)
                    .ok_or(AuthError::InvalidCredentials)?;
            from_slice(&fast_stack[..written]).map_err(|_| AuthError::InvalidCredentials)?
        } else if decoded_payload_len <= JWT_STACK_PAYLOAD_CAP {
            let mut payload_stack: [u8; JWT_STACK_PAYLOAD_CAP] = [0u8; JWT_STACK_PAYLOAD_CAP];
            let written: usize =
                decode_base64_into(trimmed_payload, &BASE64URL_DECODE_TABLE, &mut payload_stack)
                    .ok_or(AuthError::InvalidCredentials)?;
            from_slice(&payload_stack[..written]).map_err(|_| AuthError::InvalidCredentials)?
        } else {
            let payload_heap: Vec<u8> =
                base64url_decode(payload_b64).ok_or(AuthError::InvalidCredentials)?;
            from_slice(&payload_heap).map_err(|_| AuthError::InvalidCredentials)?
        };
        let JwtClaims {
            iss, aud, exp, nbf, ..
        } = &claims;
        if let Some(exp_val) = *exp
            && now_secs > exp_val.saturating_add(*leeway_secs)
        {
            return Err(AuthError::TokenExpired);
        }
        if let Some(nbf_val) = *nbf
            && now_secs.saturating_add(*leeway_secs) < nbf_val
        {
            return Err(AuthError::TokenNotYetValid);
        }
        if let Some(expected_iss) = required_issuer
            && iss.as_deref() != Some(expected_iss.as_str())
        {
            return Err(AuthError::ClaimMismatch);
        }
        if let Some(expected_aud) = required_audience
            && aud.as_deref() != Some(expected_aud.as_str())
        {
            return Err(AuthError::ClaimMismatch);
        }
        Ok(claims)
    }

    /// Verifies and decodes a compact HS256 JWT against current system time.
    ///
    /// # Arguments
    ///
    /// - `&str` - Compact JWT string.
    ///
    /// # Returns
    ///
    /// - `Result<JwtClaims, AuthError>` - Verified [`JwtClaims`] or [`AuthError`].
    pub fn decode(&self, token: &str) -> Result<JwtClaims, AuthError> {
        self.decode_at(token, auth_now_secs())
    }
}

/// Inherent helpers for [`AuthPrincipal`].
impl AuthPrincipal {
    /// Checks whether this principal possesses `role`.
    ///
    /// # Arguments
    ///
    /// - `&str` - Role name to check.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when the role is granted.
    #[inline]
    pub fn has_role(&self, role: &str) -> bool {
        self.get_roles().iter().any(|item: &String| item == role)
    }
}

/// Inherent implementation of [`JwtAuthenticator`].
impl JwtAuthenticator {
    /// Creates a [`JwtAuthenticator`] backed by `codec`.
    ///
    /// # Arguments
    ///
    /// - `JwtCodec` - Configured HS256 codec.
    ///
    /// # Returns
    ///
    /// - `Self` - Bearer JWT authenticator.
    pub fn new(codec: JwtCodec) -> Self {
        Self { codec }
    }
}

/// Implements [`Authenticator`] for [`JwtAuthenticator`].
impl Authenticator for JwtAuthenticator {
    /// Authenticates `Authorization: Bearer <token>` requests via [`JwtCodec`].
    ///
    /// # Arguments
    ///
    /// - `&'a self` - Shared reference to self.
    /// - `&'a Context` - Incoming request context.
    ///
    /// # Returns
    ///
    /// - `AuthFuture<'a>` - Future resolving to [`AuthPrincipal`] or [`AuthError`].
    fn authenticate<'a>(&'a self, ctx: &'a Context) -> AuthFuture<'a> {
        let result: Result<AuthPrincipal, AuthError> = self.eval_sync(ctx);
        Box::pin(async move { result })
    }

    /// Evaluates Bearer JWT verification synchronously without `Box::pin` allocation.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Shared reference to self.
    /// - `&Context` - Incoming request context.
    ///
    /// # Returns
    ///
    /// - `Option<Result<AuthPrincipal, AuthError>>` - Always `Some` with the verification result.
    #[inline]
    fn authenticate_sync(&self, ctx: &Context) -> Option<Result<AuthPrincipal, AuthError>> {
        Some(self.eval_sync(ctx))
    }
}

/// Synchronous JWT authentication helper for [`JwtAuthenticator`].
impl JwtAuthenticator {
    /// Verifies `Authorization: Bearer <token>` synchronously.
    ///
    /// # Arguments
    ///
    /// - `&Context` - Incoming request context.
    ///
    /// # Returns
    ///
    /// - `Result<AuthPrincipal, AuthError>` - Verified principal or authentication error.
    #[inline]
    fn eval_sync(&self, ctx: &Context) -> Result<AuthPrincipal, AuthError> {
        let Self { codec } = self;
        match request_header_back(ctx.get_request(), AUTHORIZATION) {
            None => Err(AuthError::MissingCredentials),
            Some(header) => match strip_auth_scheme(header, PREFIX_BEARER) {
                None => Err(AuthError::MissingCredentials),
                Some(token) => codec.decode(token).map(|claims: JwtClaims| AuthPrincipal {
                    subject: claims.get_sub().clone(),
                    roles: claims.get_roles().clone(),
                    scheme: AuthScheme::BearerJwt,
                    claims: Some(claims),
                }),
            },
        }
    }
}

/// Default construction for [`ApiKeyAuthenticator`].
impl Default for ApiKeyAuthenticator {
    /// Constructs an empty [`ApiKeyAuthenticator`] reading `X-Api-Key`.
    fn default() -> Self {
        Self::new(X_API_KEY)
    }
}

/// Inherent implementation of [`ApiKeyAuthenticator`].
impl ApiKeyAuthenticator {
    /// Creates an [`ApiKeyAuthenticator`] reading `header_name`.
    ///
    /// # Arguments
    ///
    /// - `H` - Header name convertible into `String`.
    ///
    /// # Returns
    ///
    /// - `Self` - Empty API-key authenticator.
    pub fn new<H>(header_name: H) -> Self
    where
        H: Into<String>,
    {
        Self {
            header_name: header_name.into().to_ascii_lowercase(),
            entries: Vec::new(),
        }
    }

    /// Registers an allowed API key associated with `subject` and `roles`.
    ///
    /// # Arguments
    ///
    /// - `K` - Secret API key string.
    /// - `S` - Subject name assigned when matched.
    /// - `I` - Iterator of role names.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated authenticator.
    pub fn with_key<K, S, I, R>(mut self, api_key: K, subject: S, roles: I) -> Self
    where
        K: Into<String>,
        S: Into<String>,
        I: IntoIterator<Item = R>,
        R: Into<String>,
    {
        let Self { entries, .. } = &mut self;
        entries.push((
            api_key.into().into_bytes(),
            subject.into(),
            roles.into_iter().map(Into::into).collect(),
        ));
        self
    }
}

/// Implements [`Authenticator`] for [`ApiKeyAuthenticator`].
impl Authenticator for ApiKeyAuthenticator {
    /// Authenticates incoming API key headers using constant-time key comparisons.
    ///
    /// # Arguments
    ///
    /// - `&'a self` - Shared reference to self.
    /// - `&'a Context` - Incoming request context.
    ///
    /// # Returns
    ///
    /// - `AuthFuture<'a>` - Future resolving to [`AuthPrincipal`] or [`AuthError`].
    fn authenticate<'a>(&'a self, ctx: &'a Context) -> AuthFuture<'a> {
        let result: Result<AuthPrincipal, AuthError> = self.eval_sync(ctx);
        Box::pin(async move { result })
    }

    /// Evaluates API-key verification synchronously without `Box::pin` allocation.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Shared reference to self.
    /// - `&Context` - Incoming request context.
    ///
    /// # Returns
    ///
    /// - `Option<Result<AuthPrincipal, AuthError>>` - Always `Some` with the verification result.
    #[inline]
    fn authenticate_sync(&self, ctx: &Context) -> Option<Result<AuthPrincipal, AuthError>> {
        Some(self.eval_sync(ctx))
    }
}

/// Synchronous API-key authentication helper for [`ApiKeyAuthenticator`].
impl ApiKeyAuthenticator {
    /// Verifies configured API keys synchronously in constant time.
    ///
    /// # Arguments
    ///
    /// - `&Context` - Incoming request context.
    ///
    /// # Returns
    ///
    /// - `Result<AuthPrincipal, AuthError>` - Verified principal or authentication error.
    #[inline]
    fn eval_sync(&self, ctx: &Context) -> Result<AuthPrincipal, AuthError> {
        let Self {
            header_name,
            entries,
        } = self;
        match request_header_back(ctx.get_request(), header_name) {
            None => Err(AuthError::MissingCredentials),
            Some(candidate) => {
                let candidate_bytes: &[u8] = candidate.trim().as_bytes();
                let mut matched_idx: Option<usize> = None;
                for (idx, (secret, _, _)) in entries.iter().enumerate() {
                    if constant_time_eq(candidate_bytes, secret) {
                        matched_idx = Some(idx);
                    }
                }
                match matched_idx {
                    Some(idx) => {
                        let (_, subject, roles): &(Vec<u8>, String, Vec<String>) = &entries[idx];
                        Ok(AuthPrincipal {
                            subject: subject.clone(),
                            roles: roles.clone(),
                            scheme: AuthScheme::ApiKey,
                            claims: None,
                        })
                    }
                    None => Err(AuthError::InvalidCredentials),
                }
            }
        }
    }
}

/// Default construction for [`BasicAuthenticator`].
impl Default for BasicAuthenticator {
    /// Constructs an empty [`BasicAuthenticator`].
    fn default() -> Self {
        Self::new()
    }
}

/// Inherent implementation of [`BasicAuthenticator`].
impl BasicAuthenticator {
    /// Creates an empty [`BasicAuthenticator`].
    ///
    /// # Returns
    ///
    /// - `Self` - Empty HTTP Basic authenticator.
    pub fn new() -> Self {
        Self {
            users: hash_map_xx_hash3_64(),
        }
    }

    /// Registers a Basic-auth user with `username`, `password`, and `roles`.
    ///
    /// # Arguments
    ///
    /// - `U` - Username string.
    /// - `P` - Password string.
    /// - `I` - Iterator of role names.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated authenticator.
    pub fn with_user<U, P, I, R>(mut self, username: U, password: P, roles: I) -> Self
    where
        U: Into<String>,
        P: Into<String>,
        I: IntoIterator<Item = R>,
        R: Into<String>,
    {
        let Self { users } = &mut self;
        users.insert(
            username.into(),
            (
                password.into().into_bytes(),
                roles.into_iter().map(Into::into).collect(),
            ),
        );
        self
    }
}

/// Implements [`Authenticator`] for [`BasicAuthenticator`].
impl Authenticator for BasicAuthenticator {
    /// Authenticates `Authorization: Basic <base64>` using constant-time password checks.
    ///
    /// # Arguments
    ///
    /// - `&'a self` - Shared reference to self.
    /// - `&'a Context` - Incoming request context.
    ///
    /// # Returns
    ///
    /// - `AuthFuture<'a>` - Future resolving to [`AuthPrincipal`] or [`AuthError`].
    fn authenticate<'a>(&'a self, ctx: &'a Context) -> AuthFuture<'a> {
        let result: Result<AuthPrincipal, AuthError> = self.eval_sync(ctx);
        Box::pin(async move { result })
    }

    /// Evaluates HTTP Basic authentication synchronously without `Box::pin` allocation.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Shared reference to self.
    /// - `&Context` - Incoming request context.
    ///
    /// # Returns
    ///
    /// - `Option<Result<AuthPrincipal, AuthError>>` - Always `Some` with the verification result.
    #[inline]
    fn authenticate_sync(&self, ctx: &Context) -> Option<Result<AuthPrincipal, AuthError>> {
        Some(self.eval_sync(ctx))
    }
}

/// Synchronous HTTP Basic authentication helper for [`BasicAuthenticator`].
impl BasicAuthenticator {
    /// Verifies `Authorization: Basic <base64>` credentials synchronously.
    ///
    /// # Arguments
    ///
    /// - `&Context` - Incoming request context.
    ///
    /// # Returns
    ///
    /// - `Result<AuthPrincipal, AuthError>` - Verified principal or authentication error.
    #[inline]
    fn eval_sync(&self, ctx: &Context) -> Result<AuthPrincipal, AuthError> {
        let Self { users } = self;
        match request_header_back(ctx.get_request(), AUTHORIZATION) {
            None => Err(AuthError::MissingCredentials),
            Some(header) => match strip_auth_scheme(header, PREFIX_BASIC) {
                None => Err(AuthError::MissingCredentials),
                Some(encoded) => {
                    let trimmed_b64: &[u8] = encoded.trim_end_matches('=').as_bytes();
                    let decoded_len: usize = (trimmed_b64.len() * 3) / 4;
                    let mut stack_buf: [u8; BASIC_STACK_CAP] = [0u8; BASIC_STACK_CAP];
                    let heap_buf: Vec<u8>;
                    let raw_opt: Option<&[u8]> = if decoded_len <= BASIC_STACK_CAP {
                        decode_base64_into(trimmed_b64, &BASE64_STD_DECODE_TABLE, &mut stack_buf)
                            .map(|written: usize| &stack_buf[..written])
                    } else if let Some(buf) = base64_decode(encoded) {
                        heap_buf = buf;
                        Some(heap_buf.as_slice())
                    } else {
                        None
                    };
                    match raw_opt.and_then(|raw: &[u8]| from_utf8(raw).ok()) {
                        None => Err(AuthError::InvalidCredentials),
                        Some(decoded) => match decoded.split_once(':') {
                            None => Err(AuthError::InvalidCredentials),
                            Some((user, pass)) => match users.get(user) {
                                Some((expected_pass, roles))
                                    if constant_time_eq(pass.as_bytes(), expected_pass) =>
                                {
                                    Ok(AuthPrincipal {
                                        subject: user.to_owned(),
                                        roles: roles.clone(),
                                        scheme: AuthScheme::Basic,
                                        claims: None,
                                    })
                                }
                                _ => Err(AuthError::InvalidCredentials),
                            },
                        },
                    }
                }
            },
        }
    }
}

/// Inherent implementation of [`CompositeAuthenticator`].
impl CompositeAuthenticator {
    /// Creates a [`CompositeAuthenticator`] chaining `chain` in priority order.
    ///
    /// # Arguments
    ///
    /// - `Vec<Arc<dyn Authenticator>>` - Ordered list of authenticators.
    ///
    /// # Returns
    ///
    /// - `Self` - Composite authenticator.
    pub fn new(chain: Vec<Arc<dyn Authenticator>>) -> Self {
        Self { chain }
    }
}

/// Implements [`Authenticator`] for [`CompositeAuthenticator`].
impl Authenticator for CompositeAuthenticator {
    /// Evaluates each authenticator in order, returning the first verified [`AuthPrincipal`].
    ///
    /// # Arguments
    ///
    /// - `&'a self` - Shared reference to self.
    /// - `&'a Context` - Incoming request context.
    ///
    /// # Returns
    ///
    /// - `AuthFuture<'a>` - Future resolving to the first matching [`AuthPrincipal`] or last non-missing error.
    fn authenticate<'a>(&'a self, ctx: &'a Context) -> AuthFuture<'a> {
        let Self { chain } = self;
        Box::pin(async move {
            let mut last_err: AuthError = AuthError::MissingCredentials;
            for auth in chain {
                match auth.authenticate(ctx).await {
                    Ok(principal) => return Ok(principal),
                    Err(AuthError::MissingCredentials) => {}
                    Err(err) => last_err = err,
                }
            }
            Err(last_err)
        })
    }
}

/// Default construction for [`AuthConfig`].
impl Default for AuthConfig {
    /// Constructs a default [`AuthConfig`] with Bearer realm challenge and no exempt paths.
    fn default() -> Self {
        Self {
            exempt_paths: Vec::new(),
            required_roles: Vec::new(),
            require_all_roles: false,
            www_authenticate: DEFAULT_WWW_AUTHENTICATE.to_owned(),
        }
    }
}

/// Inherent builders for [`AuthConfig`].
impl AuthConfig {
    /// Configures exact paths excluded from authentication checks.
    ///
    /// # Arguments
    ///
    /// - `I` - Iterator of exempt paths.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_exempt_paths<I, S>(mut self, paths: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.set_exempt_paths(paths.into_iter().map(Into::into).collect());
        self
    }

    /// Configures roles required to access protected routes.
    ///
    /// # Arguments
    ///
    /// - `I` - Iterator of required role names.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_required_roles<I, S>(mut self, roles: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.set_required_roles(roles.into_iter().map(Into::into).collect());
        self
    }
}

/// Inherent implementation of [`AuthPlugin`].
impl AuthPlugin {
    /// Initializes the global [`AuthPlugin`] once with `config` and `authenticator`.
    ///
    /// # Arguments
    ///
    /// - `AuthConfig` - Path-exclusion and RBAC policy.
    /// - `Arc<dyn Authenticator>` - Pluggable authenticator implementation.
    ///
    /// # Returns
    ///
    /// - `&'static Self` - Reference to the initialized global plugin.
    pub fn init(config: AuthConfig, authenticator: Arc<dyn Authenticator>) -> &'static Self {
        AUTH_PLUGIN.get_or_init(|| {
            let exempt_set: Option<HashSetXxHash3_64<String>> =
                if config.get_exempt_paths().len() > EXEMPT_SET_THRESHOLD {
                    let mut set: HashSetXxHash3_64<String> = hash_set_xx_hash3_64();
                    for path in config.get_exempt_paths() {
                        set.insert(path.clone());
                    }
                    Some(set)
                } else {
                    None
                };
            let mut resp_401: Response = Response::default();
            resp_401
                .set_status_code(HttpStatus::Unauthorized.code())
                .set_header(WWW_AUTHENTICATE, config.get_www_authenticate())
                .set_body(Vec::new());
            let prebuilt_401_wire: Vec<u8> = resp_401.build();
            let mut resp_403: Response = Response::default();
            resp_403
                .set_status_code(HttpStatus::Forbidden.code())
                .set_body(Vec::new());
            let prebuilt_403_wire: Vec<u8> = resp_403.build();
            Self {
                config,
                authenticator,
                exempt_set,
                prebuilt_401_wire,
                prebuilt_403_wire,
            }
        })
    }

    /// Returns the initialized global [`AuthPlugin`], if initialized.
    ///
    /// # Returns
    ///
    /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
    #[inline(always)]
    pub fn get() -> Option<&'static Self> {
        AUTH_PLUGIN.get()
    }

    /// Returns the active [`AuthConfig`].
    ///
    /// # Returns
    ///
    /// - `&AuthConfig` - Active authorization policy.
    #[inline(always)]
    pub fn get_config(&self) -> &AuthConfig {
        &self.config
    }

    /// Returns the active [`Arc<dyn Authenticator>`].
    ///
    /// # Returns
    ///
    /// - `&Arc<dyn Authenticator>` - Active authenticator.
    #[inline(always)]
    pub fn get_authenticator(&self) -> &Arc<dyn Authenticator> {
        &self.authenticator
    }

    /// Checks whether `path` is exempt from authentication without heap allocation.
    ///
    /// # Arguments
    ///
    /// - `&str` - Incoming request path.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when `path` is excluded from authentication.
    #[inline(always)]
    pub(crate) fn is_exempt_path(&self, path: &str) -> bool {
        let Self {
            config, exempt_set, ..
        } = self;
        if let Some(set) = exempt_set {
            return set.contains(path);
        }
        let exempt: &[String] = config.get_exempt_paths().as_slice();
        if exempt.is_empty() {
            return false;
        }
        exempt.iter().any(|item: &String| item.as_str() == path)
    }

    /// Retrieves the verified [`AuthPrincipal`] previously stored in `ctx` by [`AuthHook`].
    ///
    /// # Arguments
    ///
    /// - `&Context` - Request context.
    ///
    /// # Returns
    ///
    /// - `Option<AuthPrincipal>` - Verified caller principal, if authenticated.
    pub fn principal(ctx: &Context) -> Option<AuthPrincipal> {
        ctx.try_get_attribute(ATTR_AUTH_PRINCIPAL)
    }

    /// Checks whether `principal` satisfies the configured RBAC role requirements.
    ///
    /// # Arguments
    ///
    /// - `&AuthPrincipal` - Verified principal.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when authorized.
    pub fn is_authorized(&self, principal: &AuthPrincipal) -> bool {
        let required: &Vec<String> = self.get_config().get_required_roles();
        if required.is_empty() {
            return true;
        }
        if self.get_config().get_require_all_roles() {
            required
                .iter()
                .all(|role: &String| principal.has_role(role))
        } else {
            required
                .iter()
                .any(|role: &String| principal.has_role(role))
        }
    }
}

/// Implements [`ServerHook`] for [`AuthHook`].
impl ServerHook for AuthHook {
    /// Constructs a per-request [`AuthHook`].
    ///
    /// # Arguments
    ///
    /// - `&mut Stream` - Connection stream.
    /// - `&mut Context` - Request context.
    ///
    /// # Returns
    ///
    /// - `Self` - Hook instance.
    #[inline(always)]
    async fn new(_: &mut Stream, _: &mut Context) -> Self {
        Self
    }

    /// Authenticates protected requests, verifies required roles, and attaches [`AuthPrincipal`].
    ///
    /// # Arguments
    ///
    /// - `Self` - Hook instance.
    /// - `&mut Stream` - Connection stream.
    /// - `&mut Context` - Request context.
    ///
    /// # Returns
    ///
    /// - `Status` - `Status::Continue` when unconfigured, exempt, or authorized; `Status::Reject` on `401`/`403`.
    async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
        let Some(plugin) = AuthPlugin::get() else {
            return Status::Continue;
        };
        let path: &str = ctx.get_request().get_path();
        if plugin.is_exempt_path(path) {
            return Status::Continue;
        }
        let auth_result: Result<AuthPrincipal, AuthError> =
            if let Some(sync_res) = plugin.get_authenticator().authenticate_sync(ctx) {
                sync_res
            } else {
                plugin.get_authenticator().authenticate(ctx).await
            };
        match auth_result {
            Ok(principal) => {
                if !plugin.is_authorized(&principal) {
                    let _: Result<(), ResponseError> =
                        stream.try_send(&plugin.prebuilt_403_wire).await;
                    return Status::Reject;
                }
                ctx.set_attribute(ATTR_AUTH_PRINCIPAL, principal);
                Status::Continue
            }
            Err(AuthError::Forbidden) => {
                let _: Result<(), ResponseError> = stream.try_send(&plugin.prebuilt_403_wire).await;
                Status::Reject
            }
            Err(_) => {
                let _: Result<(), ResponseError> = stream.try_send(&plugin.prebuilt_401_wire).await;
                Status::Reject
            }
        }
    }
}