broadcast-auth 0.4.0

Shared multi-scheme HTTP/RTSP auth: Basic/Digest (RFC 7235, RFC 2326 §14) via http-auth, Bearer (RFC 6750); one Credentials model + challenge->response helper for rtsp-runtime and multimux's HTTP clients.
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
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
//! Server-side challenge + verify — the origin half of RFC 7235
//! (`WWW-Authenticate`/`Authorization`), RFC 7617 (Basic), RFC 7616 (Digest),
//! RFC 2326 §14 (RTSP's reuse of the same two schemes), and RFC 6750
//! (Bearer).
//!
//! [`crate::Authenticator`]/[`crate::respond`] are the *client* half: answer
//! a challenge. [`Verifier`] is the other side of the same handshake: an
//! origin (multimux's shared output auth gating every `/{stream}/…` route,
//! issue #663; or any other credentialed origin in this workspace) builds
//! one from a configured [`Credentials`] + realm, calls [`Verifier::challenge`]
//! for the `WWW-Authenticate` value to send on a `401`, and
//! [`Verifier::verify`] to check an incoming `Authorization` header.
//!
//! Promoted from `multimux`'s test-only mock auth server
//! (`multimux::testutil`, issue #663 "Finish client-side multi-scheme
//! auth"): that module's Digest verification was already a real,
//! independent RFC 7616 §3.4.1 computation (not a literal-string match)
//! purely to drive multimux's own client-side tests against something that
//! genuinely rejects wrong credentials. This module is that same
//! computation, promoted into the shared crate so it is the *production*
//! server-side verifier (multimux's output-auth middleware) rather than a
//! test-only fixture, and so no crate hand-rolls a second copy.
//!
//! # Verification per scheme
//!
//! - **Basic** (RFC 7617 §2): the header's base64 payload is decoded and
//!   compared, in constant time, against `"{username}:{password}"`.
//! - **Bearer** (RFC 6750 §2.1): the token is compared, in constant time,
//!   against the configured token.
//! - **Digest** (RFC 7616 §3.4.1): `HA1 = MD5(username:realm:password)`,
//!   `HA2 = MD5(method:digest-uri-value)`, `response =
//!   MD5(HA1:nonce:nc:cnonce:qop:HA2)` — `qop=auth`/`algorithm=MD5` only (the
//!   one shape every client in this workspace answers) — recomputed and
//!   compared, in constant time, against the client's `response` field.
//!   `digest-uri-value` is the client's own claimed `uri` field (RFC 7616
//!   §3.4.1: HA2 is always computed over what the client actually hashed),
//!   not the server's request URI — the two need not be textually identical,
//!   only to refer to the same request-target (see below). The client's
//!   claimed `uri` field must also match the actual request URI (RFC 7616
//!   §3.4.1: the server "SHOULD check" this), not merely be internally
//!   consistent with its own `response` — but RFC 7230 §5.3 permits a
//!   request-target in either origin-form (`/path`) or absolute-form
//!   (`scheme://authority/path`), and a legitimate client may hash either;
//!   [`digest_uri_matches`] accepts both representations of the same target
//!   while still rejecting a genuinely different one.
//!   The `Authorization` fields are read with `http-auth`'s
//!   `ChallengeParser` (RFC 7235 `auth-param` list): quoted-pairs are
//!   unescaped, parameter names are case-insensitive, and a repeated
//!   parameter or a second challenge is rejected. A non-ASCII user
//!   authenticates through the RFC 7616 §3.4.4 `username*` extended parameter
//!   (RFC 8187 `UTF-8''<pct-encoded>`); a raw non-ASCII `username` and
//!   `userhash=true` are rejected.
//! - **Forwarded** ([`Self::forwarded`], issue #663 extensibility wave part
//!   1): not an RFC 7235 challenge scheme at all — trusts that a fronting
//!   reverse proxy has already authenticated the caller and forwards the
//!   authenticated username in a configured header (conventionally
//!   `X-Forwarded-User`). Authenticated iff that header is present and
//!   non-empty. **Safe ONLY behind a trusted reverse proxy that strips any
//!   client-supplied copies of that header (and of the forwarded-for header,
//!   if configured) before forwarding** — this crate performs no such
//!   stripping and trusts [`crate::RequestContext::headers`] completely; a
//!   direct or spoofed client could otherwise set the header itself and
//!   bypass authentication entirely. [`Self::challenge`] returns just the
//!   bare scheme name for diagnostics (there is no challenge/response
//!   round-trip a direct client could answer).
//! - **SignedUrl** ([`Self::signed_url`], issue #747): a CDN-style,
//!   short-lived, tamper-proof token in the URL's own query string — no
//!   `Authorization` header at all, so a player can fetch segments without
//!   carrying a credential. See [`crate::signed_url`] for the full wire
//!   form, canonical string, and rejection semantics. Like `Forwarded`,
//!   [`Self::challenge`] returns just the bare scheme name — there is no
//!   `WWW-Authenticate` round-trip a client could answer for a query-string
//!   token.
//!
//! # Nonce handling (RFC 7616 §3.3 / §5.4)
//!
//! A `Digest` [`Verifier`] issues a fresh nonce on every
//! [`Verifier::challenge`] call: `issue-time ‖ issue-sequence ‖
//! HMAC-SHA256(secret, issue-time ‖ issue-sequence)`, hex-encoded, where
//! `secret` is drawn from the OS RNG once per verifier. A nonce is accepted
//! only if its HMAC checks out and it is younger than
//! [`DIGEST_NONCE_LIFETIME`]. Expiry is absolute; a correctly answered but
//! expired nonce is reported via [`Verifier::challenge_for`], whose challenge
//! then carries `stale=true`, so a compliant client retries with the new
//! nonce without re-prompting (RFC 7616 §3.3). Callers should answer a `401`
//! with [`Verifier::challenge_for`] rather than [`Verifier::challenge`].
//!
//! Replay: for each `(nonce, cnonce)` pair the verifier keeps the highest
//! `nc` accepted plus a bitmap of the [`NC_WINDOW`] values below it (the
//! RFC 4303 §3.4.3 anti-replay window), so requests pipelined on one pair may
//! arrive out of order, but no `nc` is accepted twice and one more than
//! [`NC_WINDOW`] below the highest is refused. At most
//! [`DIGEST_NC_TRACK_CAP`] pairs are tracked by default
//! ([`Verifier::with_digest_nc_capacity`] changes it); past that the
//! least-recently-used pair is dropped, and any pair not in the table whose
//! nonce was issued no later than a dropped live one is answered as stale, so
//! a dropped pair can never be replayed.
//!
//! The verifier's clock defaults to [`SystemTime::now`] and can be replaced
//! with [`Verifier::with_clock`]; a clock that steps backwards is clamped to
//! the latest nonce issue time seen.

use std::collections::HashMap;
use std::sync::Mutex;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use headers::authorization::{Basic, Bearer, Credentials as HeaderCredentials};
use headers::{Authorization, Header, HeaderValue};
use hmac::digest::Key;
use hmac::{Hmac, KeyInit, Mac};
use http_auth::{ChallengeParser, ChallengeRef};
use lru::LruCache;
use md5::{Digest as _, Md5};
use percent_encoding::percent_decode_str;
use sha2::Sha256;
use url::{Position, Url};

use crate::credentials::Credentials;
use crate::request::RequestContext;
use crate::signed_url::{self, SignedUrlKeySet};

/// The outcome of [`Verifier::verify`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum AuthResult {
    /// The `Authorization` header (or absence of one) satisfies the
    /// verifier's configured credential.
    Ok,
    /// Missing, malformed, or wrong-credential `Authorization` — the caller
    /// should respond `401` with [`Verifier::challenge`].
    Unauthorized,
}

/// Per-scheme state a [`Verifier`] holds — mirrors [`Credentials`] but adds
/// the realm (Basic/Digest) and the nonce secret + `nc` tracker (Digest; see
/// the module docs' nonce handling).
enum VerifierScheme {
    Basic {
        username: String,
        password: String,
        realm: String,
    },
    Digest {
        username: String,
        password: String,
        realm: String,
        nonces: DigestNonces,
    },
    Bearer {
        token: String,
    },
    /// Reverse-proxy forwarded-auth (see the module docs) — no
    /// `Credentials`/realm/nonce at all, since there is no client-answered
    /// challenge for this scheme.
    Forwarded {
        user_header: String,
        forwarded_for_header: Option<String>,
    },
    /// HMAC signed-URL (see the module docs / [`crate::signed_url`]) — no
    /// `Credentials`/realm/nonce either: the token lives in the request's own
    /// query string, verified against `keys`.
    SignedUrl {
        keys: SignedUrlKeySet,
    },
}

/// Challenges + verifies incoming requests against one configured
/// [`Credentials`] (RFC 7235 origin-side auth) — see the module docs.
pub struct Verifier {
    scheme: VerifierScheme,
    clock: Clock,
}

/// The time source a [`Verifier`] reads nonce ages from.
type Clock = Box<dyn Fn() -> SystemTime + Send + Sync>;

/// How long an issued Digest nonce is accepted, measured from issue (RFC 7616
/// §5.4 leaves the lifetime to the server). An older nonce is refused, and
/// [`Verifier::challenge_for`] answers it with `stale=true` so the client
/// retries silently with a fresh nonce.
pub const DIGEST_NONCE_LIFETIME: Duration = Duration::from_secs(3600);

/// Default number of `(nonce, cnonce)` pairs a Digest [`Verifier`] tracks
/// (see [`Verifier::with_digest_nc_capacity`]). Each tracked pair costs about
/// 128 bytes (a 32-byte key hash stored twice, 28 bytes of counters, and
/// hash-map/B-tree overhead), so the default is roughly 8 MiB at most.
pub const DIGEST_NC_TRACK_CAP: usize = 65_536;

/// Width of the per-pair `nc` anti-replay window: how far below the highest
/// accepted `nc` a not-yet-seen `nc` is still accepted (RFC 4303 §3.4.3).
pub const NC_WINDOW: u32 = u64::BITS;

/// Bytes of per-verifier HMAC key drawn from the OS RNG.
const NONCE_SECRET_LEN: usize = 32;
// `DigestNonces::mac` zero-pads the secret into one SHA-256 block (64 bytes).
const _: () = assert!(NONCE_SECRET_LEN <= 64);
/// Bytes of the big-endian issue time (seconds since the Unix epoch).
const NONCE_TIME_LEN: usize = 8;
/// Bytes of the big-endian per-verifier issue sequence number, so every
/// challenge gets a distinct nonce and nonces are totally ordered by issue.
const NONCE_SEQ_LEN: usize = 8;
/// Bytes of HMAC-SHA256 output.
const NONCE_MAC_LEN: usize = 32;
/// Bytes of the decoded nonce.
const NONCE_LEN: usize = NONCE_TIME_LEN + NONCE_SEQ_LEN + NONCE_MAC_LEN;
/// RFC 7616 §3.4: `nc-value = 8LHEX`.
const NC_HEX_LEN: usize = 8;

/// Digest nonce secret plus the per-`(nonce, cnonce)` `nc` table.
struct DigestNonces {
    secret: [u8; NONCE_SECRET_LEN],
    seen: Mutex<NcTable>,
}

/// SHA-256 of `nonce ‖ cnonce` (the nonce has a fixed length, so this is
/// unambiguous) — keeps table entries small whatever the client sends.
type PairKey = [u8; 32];

/// When and in which order a nonce was issued.
#[derive(Clone, Copy)]
struct NonceStamp {
    time: u64,
    seq: u64,
}

struct NcEntry {
    stamp: NonceStamp,
    /// Highest `nc` accepted.
    highest: u32,
    /// Bit `i` set: `highest - 1 - i` has been accepted.
    window: u64,
    // No `last_used`: `LruCache` owns the use order.
}

impl NcEntry {
    /// Accepts `nc` if it has not been seen and is within the window.
    fn accept(&mut self, nc: u32) -> bool {
        if nc > self.highest {
            let shift = nc - self.highest;
            let old_highest = 1u64.checked_shl(shift - 1).unwrap_or(0);
            self.window = self.window.checked_shl(shift).unwrap_or(0) | old_highest;
            self.highest = nc;
            return true;
        }
        let below = self.highest - nc;
        if below == 0 || below > NC_WINDOW {
            return false;
        }
        let bit = 1u64 << (below - 1);
        if self.window & bit != 0 {
            return false;
        }
        self.window |= bit;
        true
    }
}

struct NcTable {
    /// Per-`(nonce, cnonce)` anti-replay state, in least-recently-used order.
    /// Unbounded as far as `lru` is concerned: the cap below is enforced by
    /// `record` so a dropped live pair can raise `floor_seq`.
    entries: LruCache<PairKey, NcEntry>,
    capacity: usize,
    /// Nonces with a lower issue sequence are accepted only for pairs still
    /// in `entries` — raised when a live pair had to be dropped.
    floor_seq: u64,
    next_seq: u64,
    latest_issue_time: u64,
}

/// What a Digest `Authorization` header amounts to, before any `nc` is
/// recorded.
enum DigestCheck {
    /// Correct response on a live nonce.
    Accept {
        key: PairKey,
        stamp: NonceStamp,
        nc: u32,
    },
    /// Correct response, but the nonce is past its lifetime or its pair was
    /// dropped from the table.
    Stale,
    /// Anything else.
    Reject,
}

fn pair_key(nonce: &str, cnonce: &str) -> PairKey {
    let mut hash = Sha256::new();
    hash.update(nonce.as_bytes());
    hash.update(cnonce.as_bytes());
    hash.finalize().into()
}

impl DigestNonces {
    fn new() -> Self {
        DigestNonces {
            secret: rand::random(),
            seen: Mutex::new(NcTable {
                entries: LruCache::unbounded(),
                capacity: DIGEST_NC_TRACK_CAP,
                floor_seq: 0,
                next_seq: 0,
                latest_issue_time: 0,
            }),
        }
    }

    fn table(&self) -> std::sync::MutexGuard<'_, NcTable> {
        self.seen.lock().unwrap_or_else(|e| e.into_inner())
    }

    fn set_capacity(&self, capacity: usize) {
        self.table().capacity = capacity.max(1);
    }

    /// `clock_secs`, clamped so it never runs behind a nonce already issued.
    fn now(&self, clock_secs: u64) -> u64 {
        clock_secs.max(self.table().latest_issue_time)
    }

    fn mac(&self, signed: &[u8]) -> Hmac<Sha256> {
        // Infallible keying: HMAC (RFC 2104 §2) zero-pads a key shorter than
        // the hash block to the block size, so a fixed-size block key built
        // here is exactly equivalent to `new_from_slice(&self.secret)`
        // without its (never-taken) error arm.
        let mut block = Key::<Hmac<Sha256>>::default();
        block[..NONCE_SECRET_LEN].copy_from_slice(&self.secret);
        let mut mac = <Hmac<Sha256> as KeyInit>::new(&block);
        mac.update(signed);
        mac
    }

    /// A fresh nonce issued now (`clock_secs`, clamped as in [`Self::now`]).
    fn issue(&self, clock_secs: u64) -> String {
        let (time, seq) = {
            let mut table = self.table();
            let time = clock_secs.max(table.latest_issue_time);
            table.latest_issue_time = time;
            let seq = table.next_seq;
            table.next_seq = seq.wrapping_add(1);
            (time, seq)
        };
        let mut raw = [0u8; NONCE_LEN];
        raw[..NONCE_TIME_LEN].copy_from_slice(&time.to_be_bytes());
        raw[NONCE_TIME_LEN..NONCE_TIME_LEN + NONCE_SEQ_LEN].copy_from_slice(&seq.to_be_bytes());
        let tag = self
            .mac(&raw[..NONCE_TIME_LEN + NONCE_SEQ_LEN])
            .finalize()
            .into_bytes();
        raw[NONCE_TIME_LEN + NONCE_SEQ_LEN..].copy_from_slice(&tag);
        hex::encode(raw)
    }

    /// The issue stamp of `nonce` if this verifier minted it, else `None`.
    fn issued_at(&self, nonce: &str) -> Option<NonceStamp> {
        let raw = unhex::<NONCE_LEN>(nonce)?;
        let (signed, tag) = raw.split_at(NONCE_TIME_LEN + NONCE_SEQ_LEN);
        self.mac(signed).verify_slice(tag).ok()?;
        let mut time = [0u8; NONCE_TIME_LEN];
        time.copy_from_slice(&raw[..NONCE_TIME_LEN]);
        let mut seq = [0u8; NONCE_SEQ_LEN];
        seq.copy_from_slice(&raw[NONCE_TIME_LEN..NONCE_TIME_LEN + NONCE_SEQ_LEN]);
        Some(NonceStamp {
            time: u64::from_be_bytes(time),
            seq: u64::from_be_bytes(seq),
        })
    }

    fn is_expired(issued: u64, now_secs: u64) -> bool {
        now_secs.saturating_sub(issued) >= DIGEST_NONCE_LIFETIME.as_secs()
    }

    /// Records `nc` for `key`; `false` when it was already seen, falls below
    /// the window, or the pair can no longer be tracked.
    fn record(&self, key: PairKey, stamp: NonceStamp, nc: u32, now_secs: u64) -> bool {
        let mut guard = self.table();
        let table = &mut *guard;
        // `peek_mut` does not touch the use order: a rejected replay must not
        // refresh the pair, only a successful accept does.
        if let Some(entry) = table.entries.peek_mut(&key) {
            if !entry.accept(nc) {
                return false;
            }
            table.entries.promote(&key);
            return true;
        }
        while table.entries.len() >= table.capacity {
            let Some((_, dropped)) = table.entries.pop_lru() else {
                break;
            };
            if !Self::is_expired(dropped.stamp.time, now_secs) {
                table.floor_seq = table.floor_seq.max(dropped.stamp.seq.saturating_add(1));
            }
        }
        if stamp.seq < table.floor_seq {
            return false;
        }
        table.entries.put(
            key,
            NcEntry {
                stamp,
                highest: nc,
                window: 0,
            },
        );
        true
    }

    /// Whether an untracked pair under a nonce with `stamp` would be refused
    /// because a live pair issued no earlier was dropped.
    fn below_floor(&self, key: &PairKey, stamp: NonceStamp) -> bool {
        let table = self.table();
        stamp.seq < table.floor_seq && !table.entries.contains(key)
    }
}

fn unix_secs(t: SystemTime) -> u64 {
    t.duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs())
}

fn default_clock() -> Clock {
    Box::new(SystemTime::now)
}

impl Verifier {
    /// Builds a verifier for `credentials`, using `realm` for the
    /// `WWW-Authenticate` challenge (Basic/Digest only — RFC 6750 Bearer has
    /// no realm parameter in this crate's minimal challenge, see
    /// [`Self::challenge`]).
    ///
    /// For `Credentials::Digest`, a random nonce-signing secret is generated
    /// now; every [`Self::challenge`] then issues a fresh, time-limited nonce
    /// (see the module docs' nonce handling).
    pub fn new(credentials: Credentials, realm: impl Into<String>) -> Self {
        // Stored in the form it is rendered in, so the realm a client echoes
        // back (and hashes into HA1) is the realm the server compares.
        let realm = sanitize_realm(&realm.into());
        let scheme = match credentials {
            Credentials::Basic { username, password } => VerifierScheme::Basic {
                username,
                password,
                realm,
            },
            Credentials::Digest { username, password } => VerifierScheme::Digest {
                username,
                password,
                realm,
                nonces: DigestNonces::new(),
            },
            Credentials::Bearer { token } => VerifierScheme::Bearer { token },
        };
        Verifier {
            scheme,
            clock: default_clock(),
        }
    }

    /// Replaces the clock Digest nonce ages are measured against (default
    /// [`SystemTime::now`]) — for sans-IO drivers and tests.
    pub fn with_clock(mut self, clock: impl Fn() -> SystemTime + Send + Sync + 'static) -> Self {
        self.clock = Box::new(clock);
        self
    }

    fn now_secs(&self) -> u64 {
        unix_secs((self.clock)())
    }

    /// Sets how many `(nonce, cnonce)` pairs a Digest verifier tracks
    /// (default [`DIGEST_NC_TRACK_CAP`], minimum 1; see the module docs).
    /// No effect on other schemes.
    pub fn with_digest_nc_capacity(self, capacity: usize) -> Self {
        if let VerifierScheme::Digest { nonces, .. } = &self.scheme {
            nonces.set_capacity(capacity);
        }
        self
    }

    /// Builds a verifier for the reverse-proxy forwarded-auth scheme (see the
    /// module docs' trust assumption — read it before using this).
    ///
    /// `user_header` (conventionally `X-Forwarded-User`) is the header whose
    /// presence (non-empty) [`Self::verify`] treats as "the proxy already
    /// authenticated this caller". `forwarded_for_header` (conventionally
    /// `Some("X-Forwarded-For".to_string())`), if configured, is read back by
    /// [`Self::forwarded_for`] for observability only — this crate makes no
    /// trust decision based on it.
    pub fn forwarded(user_header: impl Into<String>, forwarded_for_header: Option<String>) -> Self {
        Verifier {
            scheme: VerifierScheme::Forwarded {
                user_header: user_header.into(),
                forwarded_for_header,
            },
            clock: default_clock(),
        }
    }

    /// Builds a verifier for the HMAC signed-URL scheme (issue #747) —
    /// see [`crate::signed_url`] for the wire form, canonical string, and
    /// rejection semantics.
    pub fn signed_url(keys: SignedUrlKeySet) -> Self {
        Verifier {
            scheme: VerifierScheme::SignedUrl { keys },
            clock: default_clock(),
        }
    }

    /// The `WWW-Authenticate` header value to send on a `401` in response to
    /// a missing/failed [`Self::verify`] call.
    ///
    /// `Forwarded` (built via [`Self::forwarded`]) has no real RFC 7235
    /// challenge (a direct client cannot answer it — see the module docs);
    /// this just names the scheme for diagnostics.
    ///
    /// For Digest every call issues a fresh nonce; prefer
    /// [`Self::challenge_for`] when the rejected request is at hand, so an
    /// expired nonce is flagged `stale=true`.
    pub fn challenge(&self) -> String {
        self.render_challenge(false)
    }

    /// Like [`Self::challenge`], but for the request that [`Self::verify`]
    /// just rejected: when that request answered a Digest challenge
    /// correctly and only its nonce had expired, the new challenge carries
    /// `stale=true` (RFC 7616 §3.3) so the client retries without
    /// re-prompting for credentials. Identical to [`Self::challenge`] for
    /// every other scheme and outcome.
    pub fn challenge_for(&self, ctx: &RequestContext<'_>) -> String {
        let stale = match &self.scheme {
            VerifierScheme::Digest {
                username,
                password,
                realm,
                nonces,
            } => ctx.header("authorization").is_some_and(|header| {
                matches!(
                    check_digest(
                        header,
                        username,
                        password,
                        realm,
                        nonces,
                        ctx.method,
                        ctx.uri,
                        nonces.now(self.now_secs()),
                    ),
                    DigestCheck::Stale
                )
            }),
            _ => false,
        };
        self.render_challenge(stale)
    }

    fn render_challenge(&self, stale: bool) -> String {
        match &self.scheme {
            VerifierScheme::Basic { realm, .. } => format!("Basic realm={}", quoted(realm)),
            VerifierScheme::Digest { realm, nonces, .. } => {
                let nonce = nonces.issue(self.now_secs());
                let stale = if stale { ", stale=true" } else { "" };
                format!(
                    "Digest realm={}, nonce=\"{nonce}\", qop=\"auth\", algorithm=MD5{stale}",
                    quoted(realm)
                )
            }
            VerifierScheme::Bearer { .. } => "Bearer".to_string(),
            VerifierScheme::Forwarded { .. } => "Forwarded".to_string(),
            VerifierScheme::SignedUrl { .. } => "SignedUrl".to_string(),
        }
    }

    /// Verifies an incoming request against this verifier's configured
    /// scheme.
    ///
    /// Basic/Digest/Bearer read `ctx`'s `Authorization` header
    /// ([`RequestContext::header`], case-insensitive) — missing entirely is
    /// `Unauthorized`, same as before this took a full [`RequestContext`].
    /// `ctx.method` feeds Digest's `HA2` directly; `ctx.uri` is the request
    /// URI the client's claimed `uri` field is matched against (RFC 7616
    /// §3.4.1's SHOULD, accepting either origin-form or absolute-form —
    /// unused for Basic/Bearer.
    /// Forwarded reads `ctx`'s configured user header instead — see the
    /// module docs. SignedUrl reads `ctx.uri`'s own query string (`exp`/
    /// `kid`/`sig`\[/`ip`\]) instead of any header at all, and `ctx.peer_addr`
    /// when the token is IP-scoped — see [`crate::signed_url`].
    ///
    /// A `Digest` `Authorization` header with a pathological parameter count
    /// is rejected outright (see `MAX_DIGEST_FIELDS`) — this bounds
    /// the per-request allocation cost, but is not a substitute for a
    /// transport-level cap on header size, which callers should also enforce.
    pub fn verify(&self, ctx: &RequestContext<'_>) -> AuthResult {
        let ok = match &self.scheme {
            VerifierScheme::Basic {
                username, password, ..
            } => ctx
                .header("authorization")
                .is_some_and(|header| verify_basic(header, username, password)),
            VerifierScheme::Bearer { token } => ctx
                .header("authorization")
                .is_some_and(|header| verify_bearer(header, token)),
            VerifierScheme::Digest {
                username,
                password,
                realm,
                nonces,
            } => ctx.header("authorization").is_some_and(|header| {
                let now = nonces.now(self.now_secs());
                match check_digest(
                    header, username, password, realm, nonces, ctx.method, ctx.uri, now,
                ) {
                    DigestCheck::Accept { key, stamp, nc } => nonces.record(key, stamp, nc, now),
                    DigestCheck::Stale | DigestCheck::Reject => false,
                }
            }),
            VerifierScheme::Forwarded { user_header, .. } => verify_forwarded(ctx, user_header),
            VerifierScheme::SignedUrl { keys } => signed_url::verify(ctx, keys),
        };
        if ok {
            AuthResult::Ok
        } else {
            AuthResult::Unauthorized
        }
    }

    /// For a [`Self::forwarded`] verifier with a configured
    /// `forwarded_for_header`, returns that header's value from `ctx` — for
    /// tracing/observability only; this crate makes no trust decision with
    /// it (the module docs' trust assumption is what actually matters).
    /// `None` for any other verifier, or when no such header is
    /// configured/present in `ctx`.
    pub fn forwarded_for<'a>(&self, ctx: &RequestContext<'a>) -> Option<&'a str> {
        match &self.scheme {
            VerifierScheme::Forwarded {
                forwarded_for_header: Some(header_name),
                ..
            } => ctx.header(header_name),
            _ => None,
        }
    }
}

/// Manual `Debug` (rather than `#[derive(Debug)]`): every scheme carries a
/// secret (`password`/`token`) that must never render verbatim.
impl core::fmt::Debug for Verifier {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let scheme = match &self.scheme {
            VerifierScheme::Basic { .. } => "Basic",
            VerifierScheme::Digest { .. } => "Digest",
            VerifierScheme::Bearer { .. } => "Bearer",
            VerifierScheme::Forwarded { .. } => "Forwarded",
            VerifierScheme::SignedUrl { .. } => "SignedUrl",
        };
        f.debug_struct("Verifier")
            .field("scheme", &scheme)
            .finish_non_exhaustive()
    }
}

/// A realm as it can appear in a header: ASCII control characters other than
/// HTAB (CR, LF, NUL, ...) cannot appear in a header value and are dropped
/// rather than letting a realm split the response. HTAB is legal `qdtext`
/// (RFC 9110 §5.6.4) and is kept. Applied once, when the [`Verifier`] is built.
fn sanitize_realm(realm: &str) -> String {
    realm
        .chars()
        .filter(|c| !c.is_ascii_control() || *c == '\t')
        .collect()
}

/// RFC 9110 §5.6.4 `quoted-string`: `"` and `\` become quoted-pairs.
///
/// Rendering a `WWW-Authenticate` challenge stays a formatter here because no
/// crate in the workspace can produce one (`http_auth::ChallengeRef`
/// implements only `Debug`; escalation E1). `tests/challenge_render.rs` parses
/// every rendering back with `http-auth`'s `ChallengeParser`.
fn quoted(value: &str) -> String {
    let mut out = String::with_capacity(value.len() + 2);
    out.push('"');
    for c in value
        .chars()
        .filter(|c| !c.is_ascii_control() || *c == '\t')
    {
        if matches!(c, '"' | '\\') {
            out.push('\\');
        }
        out.push(c);
    }
    out.push('"');
    out
}

/// RFC 8187 §3.2.1 `value-chars` syntax: `pct-encoded` or `attr-char`.
fn is_ext_value_syntax(value: &str) -> bool {
    let b = value.as_bytes();
    let mut i = 0;
    while i < b.len() {
        match b[i] {
            b'%' => {
                if !(i + 2 < b.len()
                    && b[i + 1].is_ascii_hexdigit()
                    && b[i + 2].is_ascii_hexdigit())
                {
                    return false;
                }
                i += 3;
            }
            c if c.is_ascii_alphanumeric() || b"!#$&+-.^_`|~".contains(&c) => i += 1,
            _ => return false,
        }
    }
    true
}

/// RFC 7616 §3.4.4: `username*` is an RFC 8187 ext-value
/// (`charset "'" [language] "'" value-chars`). Only `UTF-8` is accepted;
/// syntax and UTF-8 validity are enforced, never "lossy" (`percent_decode_str`
/// alone passes a malformed `%zz` through as literal text).
fn decode_ext_value(v: &str) -> Option<String> {
    let (charset, rest) = v.split_once('\'')?;
    let (_language, value) = rest.split_once('\'')?;
    if !charset.eq_ignore_ascii_case("UTF-8") || !is_ext_value_syntax(value) {
        return None;
    }
    percent_decode_str(value)
        .decode_utf8()
        .ok()
        .map(std::borrow::Cow::into_owned)
}

/// RFC 7235 `credentials` for the Digest scheme are an `auth-param` list — the
/// same grammar `http-auth` parses for challenges — so its parser reads them
/// (verified against the RFC 7616 §3.9.1 examples in
/// `tests/http_auth_rfc7616.rs`). Names are lower-cased (RFC 7235 §2.1),
/// quoted-pairs are unescaped, and anything ambiguous is refused: more than one
/// challenge, a scheme other than `Digest`, a repeated parameter, or more than
/// [`MAX_DIGEST_FIELDS`] parameters.
fn parse_digest_fields(header: &str) -> Option<HashMap<String, String>> {
    let mut parser = ChallengeParser::new(header);
    let challenge: ChallengeRef<'_> = parser.next()?.ok()?;
    if parser.next().is_some()
        || !challenge.scheme.eq_ignore_ascii_case("Digest")
        || challenge.params.len() > MAX_DIGEST_FIELDS
    {
        return None;
    }
    let mut fields = HashMap::with_capacity(challenge.params.len());
    for (name, value) in &challenge.params {
        if fields
            .insert(name.to_ascii_lowercase(), value.to_unescaped())
            .is_some()
        {
            return None;
        }
    }
    Some(fields)
}

/// Typed read of an `Authorization` header value for one token68 scheme
/// (`Basic` or `Bearer`; `http-auth`'s parser cannot read token68). `headers`
/// matches the scheme case-insensitively and tolerates extra spaces.
fn decode<C: HeaderCredentials>(header: &str) -> Option<Authorization<C>> {
    let value = HeaderValue::from_str(header).ok()?;
    Authorization::<C>::decode(&mut std::iter::once(&value)).ok()
}

/// RFC 7617 §2: decode the base64 payload and compare, in constant time,
/// against `username`/`password`. The user-id/password split is at the FIRST
/// `:` (RFC 7617 §2: a user-id cannot contain one), so a configured username
/// containing `:` cannot match.
fn verify_basic(header: &str, username: &str, password: &str) -> bool {
    let Some(auth) = decode::<Basic>(header) else {
        return false;
    };
    // Both compared unconditionally: no short-circuit on the user-id.
    let user_ok = constant_time_eq(auth.username().as_bytes(), username.as_bytes());
    let pass_ok = constant_time_eq(auth.password().as_bytes(), password.as_bytes());
    user_ok & pass_ok
}

/// RFC 6750 §2.1: compare the bearer token, in constant time.
fn verify_bearer(header: &str, token: &str) -> bool {
    let Some(auth) = decode::<Bearer>(header) else {
        return false;
    };
    constant_time_eq(auth.token().trim().as_bytes(), token.trim().as_bytes())
}

/// A real Digest `Authorization` response (RFC 7616 §3.4.1) carries under 15
/// `key=value` fields (`username`, `realm`, `nonce`, `uri`, `response`,
/// `algorithm`, `cnonce`, `opaque`, `qop`, `nc`, plus a couple of optional
/// extensions). Capping well above that bounds [`verify_digest`]'s
/// `HashMap` allocation against a request carrying a pathologically large
/// `Authorization` header (a huge field count forcing a huge per-request
/// map) without rejecting any legitimate client.
const MAX_DIGEST_FIELDS: usize = 64;

/// RFC 7616 §3.4.1: parse the `Digest` `Authorization` header's
/// `key=value`/`key="value"` fields, check the nonce was minted by `nonces`,
/// independently recompute the expected `response`, and compare in constant
/// time — `qop=auth`/`algorithm=MD5` only (the one shape every client in this
/// workspace answers). Records nothing; the caller records an accepted `nc`.
///
/// `HA2` is computed over the client's own claimed `uri` field (the
/// `digest-uri-value` RFC 7616 §3.4.1 defines HA2 over) — not `request_uri` —
/// since that is what the client actually hashed into its `response`. The
/// client's claimed `uri` is separately checked against `request_uri` (RFC
/// 7616 §3.4.1's SHOULD) via [`digest_uri_matches`], which accepts either
/// legal RFC 7230 request-target representation of the same target
/// (origin-form or absolute-form) while still rejecting a genuinely
/// different `uri`.
///
/// Rejects outright a header carrying more than [`MAX_DIGEST_FIELDS`]
/// parameters — see that constant's docs. The parser still allocates one
/// entry per parameter, bounded by the header size the transport already caps.
#[allow(clippy::too_many_arguments)]
fn check_digest(
    header: &str,
    username: &str,
    password: &str,
    realm: &str,
    nonces: &DigestNonces,
    method: &str,
    request_uri: &str,
    now_secs: u64,
) -> DigestCheck {
    let Some(fields) = parse_digest_fields(header) else {
        return DigestCheck::Reject;
    };
    let get = |k: &str| fields.get(k).map(String::as_str).unwrap_or_default();

    if get("userhash").eq_ignore_ascii_case("true") {
        return DigestCheck::Reject;
    }
    let client_user = match (fields.get("username"), fields.get("username*")) {
        (Some(_), Some(_)) => return DigestCheck::Reject, // RFC 7616 §3.4.4
        (Some(u), None) => u.clone(),
        (None, Some(ext)) => match decode_ext_value(ext) {
            Some(u) => u,
            None => return DigestCheck::Reject,
        },
        (None, None) => return DigestCheck::Reject,
    };
    if client_user != username || get("realm") != realm {
        return DigestCheck::Reject;
    }
    let nonce = get("nonce");
    let Some(stamp) = nonces.issued_at(nonce) else {
        return DigestCheck::Reject;
    };
    let client_uri = get("uri");
    if !digest_uri_matches(client_uri, request_uri) {
        return DigestCheck::Reject;
    }
    let nc_text = get("nc");
    let cnonce = get("cnonce");
    let qop = get("qop");
    let client_response = get("response");
    if cnonce.is_empty() || client_response.is_empty() {
        return DigestCheck::Reject;
    }
    // This module doc / the rendered challenge only ever offer `qop="auth"`,
    // `algorithm=MD5` (see the module-level "Verification per scheme" doc) —
    // reject anything else outright rather than silently hashing whatever
    // the client sent through the qop=auth formula below (RFC 7616 §3.4.1
    // also defines `qop=auth-int` and `algorithm=*-sess` variants, which use
    // a *different* HA1/HA2 construction this crate does not implement).
    // `algorithm` defaults to `MD5` when absent (RFC 7616 §3.3).
    if qop != "auth" {
        return DigestCheck::Reject;
    }
    let algorithm = get("algorithm");
    if !algorithm.is_empty() && !algorithm.eq_ignore_ascii_case("MD5") {
        return DigestCheck::Reject;
    }
    let Some(nc) = parse_nc(nc_text) else {
        return DigestCheck::Reject;
    };

    let ha1 = md5_hex(format!("{username}:{realm}:{password}"));
    let ha2 = md5_hex(format!("{method}:{client_uri}"));
    let expected_response = md5_hex(format!("{ha1}:{nonce}:{nc_text}:{cnonce}:{qop}:{ha2}"));
    if !constant_time_eq(expected_response.as_bytes(), client_response.as_bytes()) {
        return DigestCheck::Reject;
    }
    let key = pair_key(nonce, cnonce);
    if DigestNonces::is_expired(stamp.time, now_secs) || nonces.below_floor(&key, stamp) {
        return DigestCheck::Stale;
    }
    DigestCheck::Accept { key, stamp, nc }
}

/// RFC 7616 §3.4: `nc` is exactly eight hex digits.
fn parse_nc(nc: &str) -> Option<u32> {
    if nc.len() != NC_HEX_LEN || !nc.bytes().all(|b| b.is_ascii_hexdigit()) {
        return None;
    }
    u32::from_str_radix(nc, 16).ok()
}

/// RFC 7616 §3.4.1's SHOULD-check: does the client's claimed Digest `uri`
/// field refer to the same request-target as `request_uri` (the actual
/// request the server is verifying against)?
///
/// RFC 7230 §5.3 permits a request-target in either **origin-form**
/// (`/path[?query]`) or **absolute-form** (`scheme://authority/path[?query]`)
/// — a legitimate client may hash either, and `request_uri` here is always
/// whatever form the caller's own request line/context uses (in this
/// workspace, always origin-form for HTTP). This accepts:
/// - `client_uri == request_uri` verbatim (the origin-form case), or
/// - `client_uri` in absolute-form that `url::Url` parses, that is ALREADY in
///   the parser's normalised spelling (`Url::as_str() == client_uri`: no
///   dot-segments, no upper-case scheme/host, no default port, a root `/`),
///   and whose path+query+fragment (`Position::BeforePath..`) is
///   byte-identical to `request_uri`.
///
/// Anything else is rejected. The normalised-spelling requirement is the
/// substitution guard: `Url::parse` removes `.`/`..` segments (also when
/// percent-encoded), so a naive "parse, then compare" would authorise `/b`
/// for a response hashed over `http://h/a/../b`. This is not a prefix/suffix
/// check either: a `client_uri` that merely contains or is suffixed by
/// `request_uri` (or vice versa) does NOT match.
fn digest_uri_matches(client_uri: &str, request_uri: &str) -> bool {
    if client_uri == request_uri {
        return true;
    }
    let Ok(parsed) = Url::parse(client_uri) else {
        return false;
    };
    parsed.as_str() == client_uri && &parsed[Position::BeforePath..] == request_uri
}

/// Reverse-proxy forwarded-auth (see the module docs): authenticated iff
/// `user_header` is present in `ctx` and non-empty (after trimming) — the
/// proxy having already verified the caller's identity. No credential/secret
/// is compared here, so no constant-time comparison is needed.
fn verify_forwarded(ctx: &RequestContext<'_>, user_header: &str) -> bool {
    ctx.header(user_header)
        .is_some_and(|v| !v.trim().is_empty())
}

/// Lowercase-hex MD5 digest of `input`.
fn md5_hex(input: String) -> String {
    let mut hasher = Md5::new();
    hasher.update(input.as_bytes());
    hex::encode(hasher.finalize())
}

/// Byte-equality that does not short-circuit on the first differing byte —
/// only the *length* check short-circuits (an equal-length requirement is
/// not itself the secret being protected). Guards against a timing
/// side-channel on the password/token/digest-response comparison.
fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
    if a.len() != b.len() {
        return false;
    }
    a.iter()
        .zip(b.iter())
        .fold(0u8, |acc, (x, y)| acc | (x ^ y))
        == 0
}

/// Decodes exactly `N` bytes of hex, or `None`.
fn unhex<const N: usize>(text: &str) -> Option<[u8; N]> {
    let mut out = [0u8; N];
    hex::decode_to_slice(text, &mut out).ok()?; // exact length, hex digits only
    Some(out)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Credentials, RequestContext, respond};

    const REALM: &str = "cameras";

    /// Eviction order is least-recently-USED, not least-recently-inserted:
    /// touching an old pair must protect it.
    #[test]
    fn recently_used_pair_survives_eviction() {
        let nonces = DigestNonces::new();
        nonces.set_capacity(2);
        let stamp = |seq| NonceStamp { time: 100, seq };
        let (a, b, c) = (
            pair_key("n1", "c"),
            pair_key("n2", "c"),
            pair_key("n3", "c"),
        );
        assert!(nonces.record(a, stamp(1), 1, 100));
        assert!(nonces.record(b, stamp(2), 1, 100));
        // Use `a` again (nc 2), making `b` the least recently used.
        assert!(nonces.record(a, stamp(1), 2, 100));
        // Inserting `c` evicts `b`, not `a`.
        assert!(nonces.record(c, stamp(3), 1, 100));
        assert!(
            !nonces.record(a, stamp(1), 2, 100),
            "a still tracked: nc 2 is a replay"
        );
        assert_eq!(nonces.table().entries.len(), 2);
        // `b` was evicted while still live, so its issue sequence is now below
        // the anti-replay floor and the pair cannot be re-admitted.
        assert!(!nonces.record(b, stamp(2), 1, 100));
    }

    #[test]
    fn nonce_is_96_lowercase_hex_and_round_trips() {
        let nonces = DigestNonces::new();
        let nonce = nonces.issue(1_000);
        assert_eq!(nonce.len(), NONCE_LEN * 2);
        assert!(
            nonce
                .bytes()
                .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
        );
        let stamp = nonces.issued_at(&nonce).expect("our own nonce verifies");
        assert_eq!(stamp.time, 1_000);
        assert!(
            nonces.issued_at(&nonce.to_uppercase()).is_some(),
            "hex is case-insensitive on read"
        );
        assert!(nonces.issued_at(&nonce[..nonce.len() - 2]).is_none());
        assert!(
            nonces
                .issued_at(&format!("{}zz", &nonce[..nonce.len() - 2]))
                .is_none()
        );
    }

    /// The infallible block-key construction in `DigestNonces::mac` must be
    /// byte-identical to the variable-length `new_from_slice` keying it
    /// replaced (RFC 2104 zero-pads a short key to the block size), so
    /// nonces issued before and after the change verify against each other.
    #[test]
    fn nonce_mac_matches_variable_length_keying() {
        let nonces = DigestNonces::new();
        let signed = b"issue-time||issue-seq";
        let reference = {
            let mut m = <Hmac<Sha256> as KeyInit>::new_from_slice(&nonces.secret).unwrap();
            m.update(signed);
            m.finalize().into_bytes()
        };
        assert_eq!(nonces.mac(signed).finalize().into_bytes(), reference);
    }

    /// Test helper: builds a [`RequestContext`] carrying `authorization` (if
    /// any) as the `Authorization` header, then verifies it — stands in for
    /// the pre-#663-extensibility-wave-1 `Verifier::verify(Option<&str>,
    /// &str, &str)` signature so the tests below read the same as before.
    fn verify_auth(
        v: &Verifier,
        authorization: Option<&str>,
        method: &str,
        uri: &str,
    ) -> AuthResult {
        let auth_header = authorization.map(|h| [("authorization", h)]);
        let headers: &[(&str, &str)] = match &auth_header {
            Some(arr) => arr,
            None => &[],
        };
        let ctx = RequestContext::new(method, uri).with_headers(headers);
        v.verify(&ctx)
    }

    // --- challenge() shape ---

    #[test]
    fn basic_challenge_names_the_realm() {
        let v = Verifier::new(
            Credentials::Basic {
                username: "admin".into(),
                password: "12345".into(),
            },
            REALM,
        );
        assert_eq!(v.challenge(), "Basic realm=\"cameras\"");
    }

    #[test]
    fn digest_challenge_carries_realm_nonce_qop_algorithm() {
        let v = Verifier::new(
            Credentials::Digest {
                username: "admin".into(),
                password: "12345".into(),
            },
            REALM,
        );
        let challenge = v.challenge();
        assert!(challenge.starts_with("Digest "), "got: {challenge}");
        for needle in [
            "realm=\"cameras\"",
            "nonce=",
            "qop=\"auth\"",
            "algorithm=MD5",
        ] {
            assert!(
                challenge.contains(needle),
                "missing {needle} in {challenge}"
            );
        }
    }

    #[test]
    fn bearer_challenge_is_bare_scheme_name() {
        let v = Verifier::new(Credentials::bearer("tok"), REALM);
        assert_eq!(v.challenge(), "Bearer");
    }

    #[test]
    fn digest_challenges_issue_distinct_nonces() {
        let v = Verifier::new(
            Credentials::Digest {
                username: "admin".into(),
                password: "12345".into(),
            },
            REALM,
        );
        assert_ne!(v.challenge(), v.challenge());
    }

    // --- round trip: a client's respond() to challenge() must verify() Ok ---

    #[test]
    fn basic_respond_to_challenge_verifies_ok() {
        let v = Verifier::new(
            Credentials::Basic {
                username: "admin".into(),
                password: "12345".into(),
            },
            REALM,
        );
        let header = respond(
            &v.challenge(),
            &RequestContext::new("GET", "/stream"),
            Credentials::new("admin", "12345"),
        )
        .unwrap();
        assert_eq!(
            verify_auth(&v, Some(&header), "GET", "/stream"),
            AuthResult::Ok
        );
    }

    #[test]
    fn digest_respond_to_challenge_verifies_ok() {
        let v = Verifier::new(
            Credentials::Digest {
                username: "admin".into(),
                password: "12345".into(),
            },
            REALM,
        );
        let ctx = RequestContext::new("DESCRIBE", "rtsp://cam/live");
        let header = respond(&v.challenge(), &ctx, Credentials::new("admin", "12345")).unwrap();
        assert_eq!(
            verify_auth(&v, Some(&header), "DESCRIBE", "rtsp://cam/live"),
            AuthResult::Ok
        );
    }

    #[test]
    fn bearer_respond_to_challenge_verifies_ok() {
        let v = Verifier::new(Credentials::bearer("mytoken123"), REALM);
        let header = respond(
            &v.challenge(),
            &RequestContext::new("GET", "/stream"),
            Credentials::bearer("mytoken123"),
        )
        .unwrap();
        assert_eq!(
            verify_auth(&v, Some(&header), "GET", "/stream"),
            AuthResult::Ok
        );
    }

    // --- wrong credentials -> Unauthorized (must BITE) ---

    #[test]
    fn basic_wrong_password_is_unauthorized() {
        let v = Verifier::new(
            Credentials::Basic {
                username: "admin".into(),
                password: "12345".into(),
            },
            REALM,
        );
        let header = respond(
            &v.challenge(),
            &RequestContext::new("GET", "/stream"),
            Credentials::new("admin", "WRONG"),
        )
        .unwrap();
        assert_eq!(
            verify_auth(&v, Some(&header), "GET", "/stream"),
            AuthResult::Unauthorized
        );
    }

    #[test]
    fn digest_wrong_password_is_unauthorized() {
        let v = Verifier::new(
            Credentials::Digest {
                username: "admin".into(),
                password: "12345".into(),
            },
            REALM,
        );
        let ctx = RequestContext::new("DESCRIBE", "rtsp://cam/live");
        let header = respond(&v.challenge(), &ctx, Credentials::new("admin", "WRONG")).unwrap();
        assert_eq!(
            verify_auth(&v, Some(&header), "DESCRIBE", "rtsp://cam/live"),
            AuthResult::Unauthorized
        );
    }

    #[test]
    fn digest_mismatched_request_uri_is_unauthorized() {
        // A digest response computed for one URI must not verify against a
        // different URI the caller passes to `verify` (RFC 7616 SHOULD-check
        // that the header's `uri` matches the actual request).
        let v = Verifier::new(
            Credentials::Digest {
                username: "admin".into(),
                password: "12345".into(),
            },
            REALM,
        );
        let ctx = RequestContext::new("DESCRIBE", "rtsp://cam/live");
        let header = respond(&v.challenge(), &ctx, Credentials::new("admin", "12345")).unwrap();
        assert_eq!(
            verify_auth(&v, Some(&header), "DESCRIBE", "rtsp://cam/OTHER"),
            AuthResult::Unauthorized
        );
    }

    /// RFC 7230 §5.3.2: a client may legally answer a Digest challenge using
    /// the absolute-form request-target instead of origin-form — e.g.
    /// multimux's outbound HTTP client (`source::http_auth::authenticated_get`,
    /// issue #724) sends the absolute URL as `uri`. The server here only ever
    /// sees the request's path (origin-form) as its own request `uri`; RFC
    /// 7616 §3.4.1 permits this because HA2 is computed over the CLIENT's
    /// claimed `uri`, and the SHOULD uri-match ([`digest_uri_matches`])
    /// accepts either representation of the same target. Built via the real
    /// `respond()` round-trip (not a rigged expected string) so this exercises
    /// the true client computation.
    #[test]
    fn digest_accepts_absolute_form_client_uri_matching_request_path() {
        let v = Verifier::new(
            Credentials::Digest {
                username: "admin".into(),
                password: "12345".into(),
            },
            REALM,
        );
        let client_ctx = RequestContext::new("GET", "http://cam.local/stream/media.m3u8");
        let header = respond(
            &v.challenge(),
            &client_ctx,
            Credentials::new("admin", "12345"),
        )
        .unwrap();
        assert!(
            header.contains("uri=\"http://cam.local/stream/media.m3u8\""),
            "expected the client to hash the absolute-form uri, got: {header}"
        );
        assert_eq!(
            verify_auth(&v, Some(&header), "GET", "/stream/media.m3u8"),
            AuthResult::Ok
        );
    }

    /// Regression/mutation guard: an absolute-form `uri` whose PATH is
    /// genuinely different from the request must still be rejected — the
    /// SHOULD uri-match is a real substitution guard, not a rubber stamp for
    /// any absolute-form uri. Note this also exercises the response-mismatch
    /// path independently of the match check: because HA2 is computed over
    /// the client's own claimed uri, the client here computes a
    /// self-consistent (but wrong-target) response, so a neutered
    /// `digest_uri_matches` (hardcoded `true`) would let this wrongly verify
    /// — this test must fail if that guard is ever dropped.
    #[test]
    fn digest_rejects_absolute_form_uri_with_wrong_path() {
        let v = Verifier::new(
            Credentials::Digest {
                username: "admin".into(),
                password: "12345".into(),
            },
            REALM,
        );
        let client_ctx = RequestContext::new("GET", "http://cam.local/other/path");
        let header = respond(
            &v.challenge(),
            &client_ctx,
            Credentials::new("admin", "12345"),
        )
        .unwrap();
        assert_eq!(
            verify_auth(&v, Some(&header), "GET", "/stream/media.m3u8"),
            AuthResult::Unauthorized
        );
    }

    /// Same substitution guard, origin-form vs. origin-form (no scheme at
    /// all): a client claiming a different path outright must be rejected.
    #[test]
    fn digest_rejects_origin_form_uri_with_wrong_path() {
        let v = Verifier::new(
            Credentials::Digest {
                username: "admin".into(),
                password: "12345".into(),
            },
            REALM,
        );
        let client_ctx = RequestContext::new("GET", "/other/path");
        let header = respond(
            &v.challenge(),
            &client_ctx,
            Credentials::new("admin", "12345"),
        )
        .unwrap();
        assert_eq!(
            verify_auth(&v, Some(&header), "GET", "/stream/media.m3u8"),
            AuthResult::Unauthorized
        );
    }

    #[test]
    fn digest_uri_matches_unit_cases() {
        // Origin-form, identical.
        assert!(digest_uri_matches("/a/b", "/a/b"));
        // Absolute-form whose path matches.
        assert!(digest_uri_matches("http://host/a/b", "/a/b"));
        assert!(digest_uri_matches("https://host:8080/a/b?q=1", "/a/b?q=1"));
        // Wrong path in either form.
        assert!(!digest_uri_matches("/a/c", "/a/b"));
        assert!(!digest_uri_matches("http://host/a/c", "/a/b"));
        // Not a suffix/prefix rubber stamp.
        assert!(!digest_uri_matches("http://host/x/a/b", "/a/b"));
        assert!(!digest_uri_matches("/a/b/extra", "/a/b"));
        // Absolute-form with no path at all never matches a non-empty path.
        assert!(!digest_uri_matches("http://host", "/a/b"));
    }

    #[test]
    fn digest_uri_match_is_not_loosened_by_url_normalisation() {
        // The client hashed a spelling that is NOT the request-target, even
        // though the url crate would normalise it to one.
        assert!(!digest_uri_matches("http://h/a/../b", "/b"));
        assert!(!digest_uri_matches("http://h/%2e%2e/b", "/b"));
        assert!(!digest_uri_matches("http://h/./b", "/b"));
        assert!(!digest_uri_matches("HTTP://H/b", "/b"));
        assert!(!digest_uri_matches("http://h:80/b", "/b"));
        assert!(!digest_uri_matches("http://h", "/"));
        assert!(!digest_uri_matches("http://h/b#frag", "/b"));
        assert!(!digest_uri_matches("http://[::1/b", "/b"));
        // Normalised absolute-form still matches.
        assert!(digest_uri_matches("http://h/b?x=1&y=2", "/b?x=1&y=2"));
        assert!(digest_uri_matches("http://[2001:db8::1]:8080/b", "/b"));
        assert!(digest_uri_matches("rtsp://cam:554/live/ch1", "/live/ch1"));
        assert!(digest_uri_matches(
            "rtsp://cam/live/ch1",
            "rtsp://cam/live/ch1"
        ));
    }

    #[test]
    fn bearer_wrong_token_is_unauthorized() {
        let v = Verifier::new(Credentials::bearer("right-token"), REALM);
        let header = respond(
            &v.challenge(),
            &RequestContext::new("GET", "/stream"),
            Credentials::bearer("wrong-token"),
        )
        .unwrap();
        assert_eq!(
            verify_auth(&v, Some(&header), "GET", "/stream"),
            AuthResult::Unauthorized
        );
    }

    #[test]
    fn missing_authorization_header_is_unauthorized() {
        let v = Verifier::new(Credentials::bearer("tok"), REALM);
        assert_eq!(
            verify_auth(&v, None, "GET", "/stream"),
            AuthResult::Unauthorized
        );
    }

    #[test]
    fn wrong_scheme_header_is_unauthorized() {
        // A Basic-configured verifier must reject a Bearer-shaped header
        // (and vice versa) rather than mis-parsing it as a match.
        let v = Verifier::new(
            Credentials::Basic {
                username: "admin".into(),
                password: "12345".into(),
            },
            REALM,
        );
        assert_eq!(
            verify_auth(&v, Some("Bearer sometoken"), "GET", "/stream"),
            AuthResult::Unauthorized
        );
    }

    // --- Forwarded (reverse-proxy forwarded-auth, issue #663 extensibility
    // wave part 1) ---

    #[test]
    fn forwarded_challenge_is_bare_scheme_name() {
        let v = Verifier::forwarded("X-Forwarded-User", Some("X-Forwarded-For".to_string()));
        assert_eq!(v.challenge(), "Forwarded");
    }

    /// Biting test: a request carrying the configured user header (non-empty)
    /// must verify `Ok` — this is the whole trust mechanism, no secret is
    /// ever compared.
    #[test]
    fn forwarded_with_user_header_present_is_ok() {
        let v = Verifier::forwarded("X-Forwarded-User", Some("X-Forwarded-For".to_string()));
        let headers: &[(&str, &str)] = &[("X-Forwarded-User", "alice")];
        let ctx = RequestContext::new("GET", "/stream").with_headers(headers);
        assert_eq!(v.verify(&ctx), AuthResult::Ok);
    }

    /// Biting test: a request with no user header at all must `Unauthorized`
    /// — the whole point of the scheme is that only a trusted proxy having
    /// authenticated the caller sets it.
    #[test]
    fn forwarded_without_user_header_is_unauthorized() {
        let v = Verifier::forwarded("X-Forwarded-User", Some("X-Forwarded-For".to_string()));
        let ctx = RequestContext::new("GET", "/stream");
        assert_eq!(v.verify(&ctx), AuthResult::Unauthorized);
    }

    /// An empty (but present) user header must not count as authenticated —
    /// otherwise a proxy bug forwarding an empty header would silently grant
    /// access.
    #[test]
    fn forwarded_with_empty_user_header_is_unauthorized() {
        let v = Verifier::forwarded("X-Forwarded-User", Some("X-Forwarded-For".to_string()));
        let headers: &[(&str, &str)] = &[("X-Forwarded-User", "")];
        let ctx = RequestContext::new("GET", "/stream").with_headers(headers);
        assert_eq!(v.verify(&ctx), AuthResult::Unauthorized);
    }

    /// The user-header lookup is case-insensitive, matching real HTTP header
    /// semantics (RFC 7230 §3.2) rather than a literal-string match.
    #[test]
    fn forwarded_user_header_lookup_is_case_insensitive() {
        let v = Verifier::forwarded("X-Forwarded-User", None);
        let headers: &[(&str, &str)] = &[("x-forwarded-user", "alice")];
        let ctx = RequestContext::new("GET", "/stream").with_headers(headers);
        assert_eq!(v.verify(&ctx), AuthResult::Ok);
    }

    /// Biting test: `forwarded_for` reads the configured header's value back
    /// out of the request context — the mechanism the origin middleware uses
    /// to surface the proxy-forwarded client IP to tracing.
    #[test]
    fn forwarded_for_reads_configured_header() {
        let v = Verifier::forwarded("X-Forwarded-User", Some("X-Forwarded-For".to_string()));
        let headers: &[(&str, &str)] = &[
            ("X-Forwarded-User", "alice"),
            ("X-Forwarded-For", "203.0.113.7"),
        ];
        let ctx = RequestContext::new("GET", "/stream").with_headers(headers);
        assert_eq!(v.forwarded_for(&ctx), Some("203.0.113.7"));
    }

    /// With no `forwarded_for_header` configured, `forwarded_for` is always
    /// `None`, even if an `X-Forwarded-For` header happens to be present.
    #[test]
    fn forwarded_for_is_none_when_not_configured() {
        let v = Verifier::forwarded("X-Forwarded-User", None);
        let headers: &[(&str, &str)] = &[("X-Forwarded-For", "203.0.113.7")];
        let ctx = RequestContext::new("GET", "/stream").with_headers(headers);
        assert_eq!(v.forwarded_for(&ctx), None);
    }

    /// `forwarded_for` is always `None` for a non-`Forwarded` verifier, even
    /// if the request happens to carry an `X-Forwarded-For` header.
    #[test]
    fn forwarded_for_is_none_for_non_forwarded_verifier() {
        let v = Verifier::new(Credentials::bearer("tok"), REALM);
        let headers: &[(&str, &str)] = &[("X-Forwarded-For", "203.0.113.7")];
        let ctx = RequestContext::new("GET", "/stream").with_headers(headers);
        assert_eq!(v.forwarded_for(&ctx), None);
    }

    /// Debug must never need to redact anything for `Forwarded` (no secret is
    /// involved), but must still not panic and must name the scheme.
    #[test]
    fn forwarded_debug_names_scheme() {
        let v = Verifier::forwarded("X-Forwarded-User", Some("X-Forwarded-For".to_string()));
        let debug = format!("{v:?}");
        assert!(debug.contains("Forwarded"), "debug: {debug}");
    }

    // --- SignedUrl (issue #747) — the scheme's own biting tests (sign/
    // verify round trip, cross-route replay, expiry, key rotation, IP
    // scoping, malformed input) live in `crate::signed_url`'s test module;
    // these just cover `Verifier`'s own surface (`challenge`/`Debug`).

    #[test]
    fn signed_url_challenge_is_bare_scheme_name() {
        let keys = SignedUrlKeySet::new([("k".to_string(), vec![0u8; 32])]).unwrap();
        let v = Verifier::signed_url(keys);
        assert_eq!(v.challenge(), "SignedUrl");
    }

    #[test]
    fn signed_url_debug_names_scheme_and_never_leaks_secret() {
        let secret = b"super-secret-32-byte-hmac-key!!!".to_vec();
        let keys = SignedUrlKeySet::new([("k".to_string(), secret.clone())]).unwrap();
        let v = Verifier::signed_url(keys);
        let debug = format!("{v:?}");
        assert!(debug.contains("SignedUrl"), "debug: {debug}");
        assert!(
            !debug.contains(std::str::from_utf8(&secret).unwrap()),
            "debug: {debug}"
        );
    }

    #[test]
    fn constant_time_eq_matches_naive_equality() {
        assert!(constant_time_eq(b"same", b"same"));
        assert!(!constant_time_eq(b"same", b"diff"));
        assert!(!constant_time_eq(b"short", b"longer-string"));
        assert!(constant_time_eq(b"", b""));
    }

    // Regression: an oversized Digest `Authorization` header (way more
    // `key=value` fields than any real client sends) must be rejected
    // outright rather than parsed into an unbounded `HashMap` — and must
    // never panic. Must FAIL if the `MAX_DIGEST_FIELDS` cap in
    // `verify_digest` is ever removed.
    #[test]
    fn oversized_digest_header_is_rejected_not_parsed() {
        let v = Verifier::new(
            Credentials::Digest {
                username: "admin".into(),
                password: "12345".into(),
            },
            REALM,
        );
        let mut huge = String::from("Digest ");
        for i in 0..(MAX_DIGEST_FIELDS + 1) {
            if i > 0 {
                huge.push(',');
            }
            huge.push_str(&format!("k{i}=\"v{i}\""));
        }
        assert_eq!(
            verify_auth(&v, Some(&huge), "DESCRIBE", "rtsp://cam/live"),
            AuthResult::Unauthorized,
            "oversized Digest header must not be accepted"
        );
    }

    fn digest_verifier_at(now: std::sync::Arc<std::sync::atomic::AtomicU64>) -> Verifier {
        Verifier::new(
            Credentials::Digest {
                username: "admin".into(),
                password: "12345".into(),
            },
            REALM,
        )
        .with_clock(move || {
            UNIX_EPOCH + Duration::from_secs(now.load(std::sync::atomic::Ordering::SeqCst))
        })
    }

    fn digest_header(challenge: &str, uri: &str) -> String {
        respond(
            challenge,
            &RequestContext::new("GET", uri),
            Credentials::new("admin", "12345"),
        )
        .unwrap()
    }

    /// Rewrites the `nc` and `response` fields of a Digest header as a client
    /// would for its `nc`-th request under the same nonce + cnonce.
    fn with_nc(header: &str, nc: u32, uri: &str) -> String {
        let field = |name: &str| {
            let start = header.find(&format!("{name}=")).unwrap() + name.len() + 1;
            let rest = &header[start..];
            let rest = rest.trim_start_matches('"');
            let end = rest.find(['"', ',']).unwrap_or(rest.len());
            rest[..end].to_string()
        };
        let (nonce, cnonce, old_nc, old_resp) = (
            field("nonce"),
            field("cnonce"),
            field("nc"),
            field("response"),
        );
        let nc = format!("{nc:08x}");
        let ha1 = md5_hex(format!("admin:{REALM}:12345"));
        let ha2 = md5_hex(format!("GET:{uri}"));
        let resp = md5_hex(format!("{ha1}:{nonce}:{nc}:{cnonce}:auth:{ha2}"));
        header
            .replace(&format!("nc={old_nc}"), &format!("nc={nc}"))
            .replace(&old_resp, &resp)
    }

    // --- r09-W2: scheme token must be matched case-insensitively (RFC 7235
    // §2.1: auth-scheme is a `token`) ---

    #[test]
    fn basic_scheme_is_matched_case_insensitively() {
        let v = Verifier::new(
            Credentials::Basic {
                username: "admin".into(),
                password: "12345".into(),
            },
            REALM,
        );
        let header = respond(
            &v.challenge(),
            &RequestContext::new("GET", "/stream"),
            Credentials::new("admin", "12345"),
        )
        .unwrap();
        assert!(header.starts_with("Basic "));
        let lower = header.replacen("Basic ", "basic ", 1);
        assert_eq!(
            verify_auth(&v, Some(&lower), "GET", "/stream"),
            AuthResult::Ok,
            "lower-case scheme token must verify identically to the canonical case"
        );
    }

    #[test]
    fn bearer_scheme_is_matched_case_insensitively() {
        let v = Verifier::new(Credentials::bearer("mytoken123"), REALM);
        let header = respond(
            &v.challenge(),
            &RequestContext::new("GET", "/stream"),
            Credentials::bearer("mytoken123"),
        )
        .unwrap();
        assert!(header.starts_with("Bearer "));
        let mixed = header.replacen("Bearer ", "BEARER ", 1);
        assert_eq!(
            verify_auth(&v, Some(&mixed), "GET", "/stream"),
            AuthResult::Ok,
            "mixed-case scheme token must verify identically to the canonical case"
        );
    }

    #[test]
    fn digest_scheme_is_matched_case_insensitively() {
        let now = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(1_000_000));
        let v = digest_verifier_at(now);
        let uri = "/stream/index.m3u8";
        let header = digest_header(&v.challenge(), uri);
        assert!(header.starts_with("Digest "));
        let lower = header.replacen("Digest ", "digest ", 1);
        assert_eq!(
            verify_auth(&v, Some(&lower), "GET", uri),
            AuthResult::Ok,
            "lower-case scheme token must verify identically to the canonical case"
        );
    }

    /// r09-W2: a quoted field value containing a literal comma must not be
    /// split into two bogus fields. Uses the `uri` field specifically (not
    /// `realm`) because `uri` is checked for exact equivalence against the
    /// request ([`digest_uri_matches`]) — the naive `header.split(',')` this
    /// replaced would truncate `uri` at the embedded comma, and the
    /// truncated value provably does NOT match the (untruncated)
    /// `request_uri`, so the defect bites rather than passing by
    /// coincidence.
    #[test]
    fn digest_field_parser_respects_quoted_commas() {
        let now = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(1_000_000));
        let v = digest_verifier_at(now);
        let uri = "/stream/a,b/index.m3u8";
        let header = digest_header(&v.challenge(), uri);
        assert!(header.contains(&format!("uri=\"{uri}\"")));
        assert_eq!(
            verify_auth(&v, Some(&header), "GET", uri),
            AuthResult::Ok,
            "a comma inside the quoted uri field must not fragment the field list"
        );
    }

    // --- r09-W3: qop/algorithm must be validated, not merely hashed ---

    /// Pre-fix, `check_digest` never inspected the `algorithm` field's
    /// value — it hashed with plain MD5 regardless, so a request that
    /// *claims* an algorithm this server does not implement (and for which
    /// the real RFC 7616 HA1 construction differs, e.g. `MD5-sess`) was
    /// silently accepted anyway. Splicing a false `algorithm=SHA-256` label
    /// onto an otherwise-valid MD5-computed header must now be rejected.
    #[test]
    fn digest_rejects_unsupported_algorithm_label() {
        let now = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(1_000_000));
        let v = digest_verifier_at(now);
        let uri = "/stream/index.m3u8";
        let header = digest_header(&v.challenge(), uri);
        assert!(header.contains("algorithm=MD5"));
        let relabeled = header.replacen("algorithm=MD5", "algorithm=SHA-256", 1);
        assert_eq!(
            verify_auth(&v, Some(&relabeled), "GET", uri),
            AuthResult::Unauthorized,
            "a header claiming an unimplemented algorithm must not verify"
        );
    }

    /// Same defect for `qop`: pre-fix, the `qop` field's value was hashed
    /// verbatim into the response formula without checking it was `auth` —
    /// this server only ever implements the `qop=auth` construction (no
    /// `auth-int` entity-body hashing). A client that labels its request
    /// `qop=auth-int` but computes `response` with this server's plain
    /// `qop=auth` formula (substituting the literal string `auth-int` for
    /// the `qop` slot, since that is all the formula does with the field)
    /// must be rejected — recomputing `response` to match is what makes
    /// this bite instead of merely observing an incidental hash mismatch.
    #[test]
    fn digest_rejects_non_auth_qop() {
        let now = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(1_000_000));
        let v = digest_verifier_at(now);
        let uri = "/stream/index.m3u8";
        let header = digest_header(&v.challenge(), uri);
        let field = |name: &str| {
            let start = header.find(&format!("{name}=")).unwrap() + name.len() + 1;
            let rest = &header[start..];
            let rest = rest.trim_start_matches('"');
            let end = rest.find(['"', ',']).unwrap_or(rest.len());
            rest[..end].to_string()
        };
        let (nonce, cnonce, nc, response) = (
            field("nonce"),
            field("cnonce"),
            field("nc"),
            field("response"),
        );
        let ha1 = md5_hex(format!("admin:{REALM}:12345"));
        let ha2 = md5_hex(format!("GET:{uri}"));
        let recomputed = md5_hex(format!("{ha1}:{nonce}:{nc}:{cnonce}:auth-int:{ha2}"));
        let relabeled = header
            .replacen("qop=auth", "qop=auth-int", 1)
            .replace(&response, &recomputed);
        assert_eq!(
            verify_auth(&v, Some(&relabeled), "GET", uri),
            AuthResult::Unauthorized,
            "a header claiming qop=auth-int must not verify even when response \
             was (mis)computed with the qop=auth formula"
        );
    }

    #[test]
    fn digest_increasing_nc_is_accepted_and_repeated_nc_rejected() {
        let now = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(1_000_000));
        let v = digest_verifier_at(now);
        let uri = "/stream/index.m3u8";
        let first = digest_header(&v.challenge(), uri);
        assert_eq!(verify_auth(&v, Some(&first), "GET", uri), AuthResult::Ok);
        let second = with_nc(&first, 2, uri);
        assert_eq!(verify_auth(&v, Some(&second), "GET", uri), AuthResult::Ok);
        let third = with_nc(&first, 3, uri);
        assert_eq!(verify_auth(&v, Some(&third), "GET", uri), AuthResult::Ok);
        assert_eq!(
            verify_auth(&v, Some(&second), "GET", uri),
            AuthResult::Unauthorized,
            "an nc already accepted must be rejected"
        );
    }

    #[test]
    fn digest_expired_nonce_is_rejected_with_stale_challenge() {
        let now = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(1_000_000));
        let v = digest_verifier_at(now.clone());
        let uri = "/stream/index.m3u8";
        let header = digest_header(&v.challenge(), uri);
        now.fetch_add(
            DIGEST_NONCE_LIFETIME.as_secs(),
            std::sync::atomic::Ordering::SeqCst,
        );
        assert_eq!(
            verify_auth(&v, Some(&header), "GET", uri),
            AuthResult::Unauthorized
        );
        let headers = [("authorization", header.as_str())];
        let ctx = RequestContext::new("GET", uri).with_headers(&headers);
        let challenge = v.challenge_for(&ctx);
        assert!(challenge.ends_with(", stale=true"), "got: {challenge}");
        // The fresh nonce from that challenge verifies.
        let retry = digest_header(&challenge, uri);
        assert_eq!(verify_auth(&v, Some(&retry), "GET", uri), AuthResult::Ok);
        // A wrong password on an expired nonce is not stale.
        let wrong = respond(
            &v.challenge(),
            &RequestContext::new("GET", uri),
            Credentials::new("admin", "WRONG"),
        )
        .unwrap();
        now.fetch_add(
            DIGEST_NONCE_LIFETIME.as_secs(),
            std::sync::atomic::Ordering::SeqCst,
        );
        let headers = [("authorization", wrong.as_str())];
        let ctx = RequestContext::new("GET", uri).with_headers(&headers);
        assert!(!v.challenge_for(&ctx).contains("stale"));
    }

    #[test]
    fn digest_nonce_with_wrong_mac_is_rejected() {
        let v = Verifier::new(
            Credentials::Digest {
                username: "admin".into(),
                password: "12345".into(),
            },
            REALM,
        );
        let uri = "/stream/index.m3u8";
        let challenge = v.challenge();
        let start = challenge.find("nonce=\"").unwrap() + "nonce=\"".len();
        let nonce = &challenge[start..start + NONCE_LEN * 2];
        // Flip the last hex digit of the MAC, keeping the timestamp + salt.
        let last = nonce.as_bytes()[nonce.len() - 1];
        let flipped = if last == b'0' { '1' } else { '0' };
        let forged_nonce = format!("{}{flipped}", &nonce[..nonce.len() - 1]);
        let forged = challenge.replace(nonce, &forged_nonce);
        let header = digest_header(&forged, uri);
        assert!(header.contains(&forged_nonce));
        assert_eq!(
            verify_auth(&v, Some(&header), "GET", uri),
            AuthResult::Unauthorized
        );
        // A nonce from a different verifier (different secret) is rejected too.
        let other = Verifier::new(
            Credentials::Digest {
                username: "admin".into(),
                password: "12345".into(),
            },
            REALM,
        );
        let header = digest_header(&other.challenge(), uri);
        assert_eq!(
            verify_auth(&v, Some(&header), "GET", uri),
            AuthResult::Unauthorized
        );
    }

    #[test]
    fn digest_out_of_order_nc_within_window_is_accepted_once() {
        let now = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(1_000_000));
        let v = digest_verifier_at(now);
        let uri = "/stream/part.m4s";
        let first = digest_header(&v.challenge(), uri);
        assert_eq!(verify_auth(&v, Some(&first), "GET", uri), AuthResult::Ok);
        let nc = |n| with_nc(&first, n, uri);
        // 6 overtakes 5 in flight: both are fresh.
        assert_eq!(verify_auth(&v, Some(&nc(6)), "GET", uri), AuthResult::Ok);
        assert_eq!(verify_auth(&v, Some(&nc(5)), "GET", uri), AuthResult::Ok);
        assert_eq!(
            verify_auth(&v, Some(&nc(5)), "GET", uri),
            AuthResult::Unauthorized,
            "nc 5 a second time is a replay"
        );
        assert_eq!(
            verify_auth(&v, Some(&nc(6)), "GET", uri),
            AuthResult::Unauthorized
        );
        // Jump ahead; the oldest value the window still holds is accepted,
        // one further below is refused.
        let top = 200;
        assert_eq!(verify_auth(&v, Some(&nc(top)), "GET", uri), AuthResult::Ok);
        assert_eq!(
            verify_auth(&v, Some(&nc(top - NC_WINDOW - 1)), "GET", uri),
            AuthResult::Unauthorized,
            "an nc 65 below the highest is outside the window"
        );
        assert_eq!(
            verify_auth(&v, Some(&nc(top - NC_WINDOW)), "GET", uri),
            AuthResult::Ok
        );
    }

    #[test]
    fn digest_nc_table_evicts_least_recently_used_pair() {
        let now = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(1_000_000));
        let v = digest_verifier_at(now).with_digest_nc_capacity(4);
        let uri = "/s";
        let headers: Vec<String> = (0..4).map(|_| digest_header(&v.challenge(), uri)).collect();
        for h in &headers {
            assert_eq!(verify_auth(&v, Some(h), "GET", uri), AuthResult::Ok);
        }
        // Pair 0 is the oldest issued but stays in use.
        assert_eq!(
            verify_auth(&v, Some(&with_nc(&headers[0], 2, uri)), "GET", uri),
            AuthResult::Ok
        );
        let newcomer = digest_header(&v.challenge(), uri);
        assert_eq!(verify_auth(&v, Some(&newcomer), "GET", uri), AuthResult::Ok);
        let VerifierScheme::Digest { nonces, .. } = &v.scheme else {
            unreachable!()
        };
        assert_eq!(nonces.table().entries.len(), 4);
        // Pair 0 was not the one dropped: its replay window is intact.
        assert_eq!(
            verify_auth(&v, Some(&with_nc(&headers[0], 2, uri)), "GET", uri),
            AuthResult::Unauthorized
        );
        assert_eq!(
            verify_auth(&v, Some(&with_nc(&headers[0], 3, uri)), "GET", uri),
            AuthResult::Ok
        );
        // Pair 1 (least recently used) was dropped: its replay is refused and
        // answered as stale so the client picks up a fresh nonce.
        let replay = with_nc(&headers[1], 2, uri);
        assert_eq!(
            verify_auth(&v, Some(&replay), "GET", uri),
            AuthResult::Unauthorized
        );
        let hdrs = [("authorization", replay.as_str())];
        let ctx = RequestContext::new("GET", uri).with_headers(&hdrs);
        let challenge = v.challenge_for(&ctx);
        assert!(challenge.ends_with(", stale=true"), "got: {challenge}");
        let retry = digest_header(&challenge, uri);
        assert_eq!(verify_auth(&v, Some(&retry), "GET", uri), AuthResult::Ok);
    }

    #[test]
    fn digest_clock_stepping_back_does_not_backdate_nonces() {
        let start = 1_000_000;
        let now = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(start));
        let v = digest_verifier_at(now.clone());
        let uri = "/s";
        let before = digest_header(&v.challenge(), uri);
        // Step the clock back by more than a nonce lifetime.
        now.store(
            start - 2 * DIGEST_NONCE_LIFETIME.as_secs(),
            std::sync::atomic::Ordering::SeqCst,
        );
        let during = digest_header(&v.challenge(), uri);
        assert_eq!(verify_auth(&v, Some(&during), "GET", uri), AuthResult::Ok);
        assert_eq!(verify_auth(&v, Some(&before), "GET", uri), AuthResult::Ok);
        // When the clock returns, the nonce issued meanwhile is still young.
        now.store(
            start + DIGEST_NONCE_LIFETIME.as_secs() - 1,
            std::sync::atomic::Ordering::SeqCst,
        );
        let again = with_nc(&during, 2, uri);
        assert_eq!(verify_auth(&v, Some(&again), "GET", uri), AuthResult::Ok);
    }

    #[test]
    fn digest_replayed_request_is_rejected() {
        let v = Verifier::new(
            Credentials::Digest {
                username: "admin".into(),
                password: "12345".into(),
            },
            REALM,
        );
        let ctx = RequestContext::new("GET", "/stream/index.m3u8");
        let header = respond(&v.challenge(), &ctx, Credentials::new("admin", "12345")).unwrap();
        assert_eq!(
            verify_auth(&v, Some(&header), "GET", "/stream/index.m3u8"),
            AuthResult::Ok
        );
        assert_eq!(
            verify_auth(&v, Some(&header), "GET", "/stream/index.m3u8"),
            AuthResult::Unauthorized,
            "same nonce + nc + cnonce must not verify twice"
        );
    }

    #[test]
    fn debug_never_leaks_password_or_token() {
        let v = Verifier::new(
            Credentials::Digest {
                username: "admin".into(),
                password: "supersecret".into(),
            },
            REALM,
        );
        let debug = format!("{v:?}");
        assert!(!debug.contains("supersecret"), "debug: {debug}");

        let v = Verifier::new(Credentials::bearer("topsecrettoken"), REALM);
        let debug = format!("{v:?}");
        assert!(!debug.contains("topsecrettoken"), "debug: {debug}");
    }

    /// RFC 2617 §3.5 worked example: pins the Digest MD5 chain.
    #[test]
    fn digest_md5_matches_rfc2617_worked_example() {
        use md5::{Digest as _, Md5};
        let ha1 = hex_of(Md5::digest(b"Mufasa:testrealm@host.com:Circle Of Life"));
        let ha2 = hex_of(Md5::digest(b"GET:/dir/index.html"));
        let resp = hex_of(Md5::digest(
            format!("{ha1}:dcd98b7102dd2f0e8b11d0f600bfb0c093:00000001:0a4f113b:auth:{ha2}")
                .as_bytes(),
        ));
        assert_eq!(resp, "6629fae49393a05397450978507c4ef1");
    }

    fn hex_of(bytes: impl AsRef<[u8]>) -> String {
        bytes.as_ref().iter().map(|b| format!("{b:02x}")).collect()
    }

    /// RFC 7617 §2 example: pins Basic base64 encode/decode incl. padding.
    #[test]
    fn basic_credentials_base64_matches_rfc7617_example() {
        use base64::Engine as _;
        let enc = base64::engine::general_purpose::STANDARD.encode(b"Aladdin:open sesame");
        assert_eq!(enc, "QWxhZGRpbjpvcGVuIHNlc2FtZQ==");
        let dec = base64::engine::general_purpose::STANDARD
            .decode("QWxhZGRpbjpvcGVuIHNlc2FtZQ==")
            .unwrap();
        assert_eq!(dec, b"Aladdin:open sesame");
    }

    /// Production-path pin: the RFC 2617 §3.5 worked example through the
    /// crate's own `md5_hex` (what `check_digest` computes HA1/HA2/response
    /// with) and `constant_time_eq` (what it compares with). `check_digest`
    /// itself also needs a nonce this `DigestNonces` minted, which the RFC's
    /// fixed nonce is not, so the chain is driven through those two
    /// production helpers instead.
    #[test]
    fn production_digest_chain_matches_rfc2617_and_rejects_altered() {
        let ha1 = md5_hex("Mufasa:testrealm@host.com:Circle Of Life".to_string());
        let ha2 = md5_hex("GET:/dir/index.html".to_string());
        let expected = md5_hex(format!(
            "{ha1}:dcd98b7102dd2f0e8b11d0f600bfb0c093:00000001:0a4f113b:auth:{ha2}"
        ));
        let rfc = "6629fae49393a05397450978507c4ef1";
        assert!(constant_time_eq(expected.as_bytes(), rfc.as_bytes()));
        // One character altered: must not compare equal.
        let altered = "6629fae49393a05397450978507c4ef2";
        assert!(!constant_time_eq(expected.as_bytes(), altered.as_bytes()));
    }

    /// Production-path pin: RFC 7617 §2 (`Aladdin:open sesame`) through
    /// `verify_basic`, the function `Verifier::verify` dispatches Basic to.
    #[test]
    fn production_basic_verify_matches_rfc7617_and_rejects_altered() {
        let ok = "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==";
        assert!(verify_basic(ok, "Aladdin", "open sesame"));
        // One character altered in the payload (`Q` -> `R`).
        let altered = "Basic RWxhZGRpbjpvcGVuIHNlc2FtZQ==";
        assert!(!verify_basic(altered, "Aladdin", "open sesame"));
        assert!(!verify_basic(ok, "Aladdin", "open sesamf"));
    }
}