webauthn-kit 0.3.6

Standalone WebAuthn/FIDO2 passkey verification kit: CTAP2 authenticator data parsing, COSE ES256/ES384/EdDSA/RS256 signature verification via ring, enforceable credential policies (UV, backup eligibility, algorithm allowlists), challenge freshness/replay protection and sign-count clone detection.
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
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
//! CTAP2 protocol parsing and ceremony verification.
//!
//! Implements the two server-side `WebAuthn` ceremonies per the W3C
//! `WebAuthn` Level 2/3 model and CTAP2 authenticator data layout:
//!
//! - [`verify_registration`]: parse and validate an attestation object,
//!   extract the new credential (ID + COSE public key) and flags.
//! - [`verify_authentication`]: validate an assertion (challenge, origin,
//!   RP ID hash, user presence, sign-count freshness) and verify the
//!   signature over `authenticatorData || SHA-256(clientDataJSON)`.
//!
//! # Threat assumptions
//!
//! - All base64/BOR/JSON/CBOR inputs originate from the client and are
//!   hostile: parsers return `Err` instead of panicking on arbitrary bytes
//!   (fuzz-tested in `tests/fuzz.rs`).
//! - `challenge_bytes` MUST come from a single-use, server-side source (see
//!   [`crate::ChallengeStore`]); this module only checks that the client
//!   echoed them inside `clientDataJSON`.
//! - Attestation statements are verified for the `none`, `packed`, and
//!   `fido-u2f` formats ([`crate::attestation`]); unknown formats are
//!   rejected unless the caller opts out via
//!   [`AttestationPolicy::allow_unknown_formats`]. Trust conveyed by an
//!   attestation is bounded by the configured trust anchors — see
//!   [`crate::attestation::AttestationPolicy`] before relying on
//!   provenance.

use crate::attestation::{verify_attestation, AttestationPolicy};
use crate::challenge::check_sign_count;
use crate::credential::{AuthenticationResult, RegistrationResult};
use crate::crypto::{
    alg_to_name, base64_decode_urlsafe, base64_encode_urlsafe, cbor_bytes, parse_cose_key,
    verify_cose_signature,
};
use crate::error::WebauthnError;
use crate::policy::{BackupPolicy, CredentialPolicy, UserVerificationPolicy};

/// Parsed authenticator data structure (CTAP2 §6.1).
#[derive(Debug, Clone)]
struct AuthenticatorData {
    /// SHA-256 of the expected RP ID, as claimed by the authenticator.
    rp_id_hash: Vec<u8>,
    /// Flag byte (UP/UV/BE/BS/AT/ED bits).
    flags: u8,
    /// Big-endian signature counter.
    sign_count: u32,
    /// COSE-encoded credential public key (present when AT flag set).
    credential_public_key_cose: Option<Vec<u8>>,
    /// Raw credential ID (present when AT flag set).
    credential_id: Option<Vec<u8>>,
    /// 16-byte AAGUID (present when AT flag set).
    aaguid: Option<[u8; 16]>,
    /// Backup eligibility (BE): the credential may be backed up / synced
    /// (multi-device credential). Creation-time property, immutable.
    backup_eligible: bool,
    /// Backup state (BS): the credential is currently backed up. Volatile.
    backup_state: bool,
}

/// Authenticator data flag bit: User Present.
const FLAG_UP: u8 = 0x01;
/// Authenticator data flag bit: User Verified.
const FLAG_UV: u8 = 0x04;
/// Authenticator data flag bit: Backup Eligibility (WebAuthn L3 §6.1).
const FLAG_BE: u8 = 0x08;
/// Authenticator data flag bit: Backup State (WebAuthn L3 §6.1).
const FLAG_BS: u8 = 0x10;
/// Authenticator data flag bit: Attested Credential Data included.
const FLAG_AT: u8 = 0x40;
/// Authenticator data flag bit: Extension Data included (not parsed).
#[allow(dead_code)]
const FLAG_ED: u8 = 0x80;

/// Minimum authenticator data length: rpIdHash(32) + flags(1) + signCount(4) = 37.
const AUTH_DATA_MIN_LEN: usize = 37;

/// Fixed 18-byte AAGUID + credential-length prefix in attested credential data.
const ATTESTED_CREDENTIAL_PREFIX_LEN: usize = 18;

/// Parse authenticator data from raw bytes (CTAP2 §6.1).
///
/// # Security notes / threat assumptions
///
/// - `auth_data` is attacker-controlled; any truncation or malformed length
///   field yields `Err`, never a panic or out-of-bounds read.
/// - When the AT flag is set, everything after the credential ID is taken as
///   the COSE public key. If the ED flag is set, extension bytes would be
///   appended by the authenticator *after* the key; this parser does not
///   validate extensions and downstream CBOR parsing reads only the first
///   top-level map, so trailing extension data is ignored rather than
///   misinterpreted as key material.
///
/// # Requirements
/// REQ-WA-100, REQ-WA-201
fn parse_authenticator_data(auth_data: &[u8]) -> Result<AuthenticatorData, WebauthnError> {
    if auth_data.len() < AUTH_DATA_MIN_LEN {
        return Err(WebauthnError::VerificationFailed(format!(
            "Authenticator data too short: {} bytes (minimum {})",
            auth_data.len(),
            AUTH_DATA_MIN_LEN
        )));
    }

    // The length pre-check above makes these infallible, but `get` keeps
    // the parser total on any future layout change (attacker-controlled
    // input must never panic).
    let truncated =
        || WebauthnError::VerificationFailed("Authenticator data truncated".to_string());
    let rp_id_hash = auth_data.get(..32).ok_or_else(truncated)?.to_vec();
    let flags = *auth_data.get(32).ok_or_else(truncated)?;
    let sign_count = u32::from_be_bytes(
        auth_data
            .get(33..37)
            .ok_or_else(truncated)?
            .try_into()
            .map_err(|_| truncated())?,
    );

    let mut offset = 37;
    let mut credential_id = None;
    let mut credential_public_key_cose = None;
    let mut aaguid = None;

    if flags & FLAG_AT != 0 {
        if auth_data.len() < offset + ATTESTED_CREDENTIAL_PREFIX_LEN {
            return Err(WebauthnError::VerificationFailed(
                "Attested credential data truncated (AAGUID + length)".to_string(),
            ));
        }
        let aaguid_bytes = auth_data
            .get(offset..offset + 16)
            .ok_or_else(truncated)?
            .to_vec();
        let aaguid_arr: [u8; 16] = aaguid_bytes.try_into().map_err(|_| truncated())?;
        aaguid = Some(aaguid_arr);
        offset += 16;

        let len_hi = *auth_data.get(offset).ok_or_else(truncated)?;
        let len_lo = *auth_data.get(offset + 1).ok_or_else(truncated)?;
        let cred_id_len = u16::from_be_bytes([len_hi, len_lo]) as usize;
        offset += 2;

        if auth_data.len() < offset + cred_id_len {
            return Err(WebauthnError::VerificationFailed(
                "Attested credential data truncated (credential ID)".to_string(),
            ));
        }
        credential_id = Some(
            auth_data
                .get(offset..offset + cred_id_len)
                .ok_or_else(truncated)?
                .to_vec(),
        );
        offset += cred_id_len;

        if offset >= auth_data.len() {
            return Err(WebauthnError::VerificationFailed(
                "Attested credential data truncated (public key)".to_string(),
            ));
        }
        credential_public_key_cose = Some(auth_data.get(offset..).ok_or_else(truncated)?.to_vec());
    }

    Ok(AuthenticatorData {
        rp_id_hash,
        flags,
        sign_count,
        credential_public_key_cose,
        credential_id,
        aaguid,
        backup_eligible: flags & FLAG_BE != 0,
        backup_state: flags & FLAG_BS != 0,
    })
}

/// Enforce the flag-based portion of a [`CredentialPolicy`]: user
/// verification and backup eligibility.
///
/// - `UserVerificationPolicy::Required` with a clear UV flag →
///   [`WebauthnError::UserVerificationRequired`] (REQ-WA-142).
/// - `BackupPolicy::RequireDeviceBound` with BE set →
///   [`WebauthnError::PolicyViolation`] (REQ-WA-144).
///
/// Preferred/Discouraged/Allow never reject; the flags are reported by the
/// caller from the parsed data.
///
/// # Requirements
/// REQ-WA-142, REQ-WA-144
fn enforce_flag_policy(flags: u8, policy: &CredentialPolicy) -> Result<(), WebauthnError> {
    if policy.user_verification == UserVerificationPolicy::Required && flags & FLAG_UV == 0 {
        return Err(WebauthnError::UserVerificationRequired);
    }
    if policy.backup == BackupPolicy::RequireDeviceBound && flags & FLAG_BE != 0 {
        return Err(WebauthnError::PolicyViolation(
            "backup policy requires device-bound credentials, but the credential \
             is backup-eligible (BE=1)"
                .to_string(),
        ));
    }
    Ok(())
}

/// Enforce the registration algorithm allowlist (REQ-WA-143): a non-empty
/// `allowed_algorithms` rejects any credential whose parsed algorithm is
/// absent.
///
/// # Requirements
/// REQ-WA-143
fn enforce_algorithm_allowlist(alg: i32, policy: &CredentialPolicy) -> Result<(), WebauthnError> {
    if !policy.allowed_algorithms.is_empty() && !policy.allowed_algorithms.contains(&alg) {
        return Err(WebauthnError::UnsupportedAlgorithm(alg));
    }
    Ok(())
}

/// Shared `clientDataJSON` validation: parse, challenge echo, ceremony type,
/// origin allow-list, and optional `rpId` cross-check.
///
/// # Requirements
/// REQ-WA-100, REQ-WA-101, REQ-WA-102, REQ-WA-103
///
/// Returns the raw decoded client data bytes (needed for the auth signature).
fn validate_client_data(
    client_data_json_b64: &str,
    challenge_bytes: &[u8],
    expected_type: &str,
    rp_id: &str,
    rp_origins: &[String],
) -> Result<Vec<u8>, WebauthnError> {
    let client_data_bytes = base64_decode_urlsafe(client_data_json_b64)?;
    let client_data: serde_json::Value = serde_json::from_slice(&client_data_bytes)
        .map_err(|e| WebauthnError::VerificationFailed(format!("client data parse error: {e}")))?;

    let client_challenge = client_data
        .get("challenge")
        .and_then(|v| v.as_str())
        .ok_or_else(|| {
            WebauthnError::VerificationFailed("missing challenge in client data".to_string())
        })?;
    let client_challenge_bytes = base64_decode_urlsafe(client_challenge)?;
    if client_challenge_bytes != challenge_bytes {
        return Err(WebauthnError::VerificationFailed(
            "challenge mismatch".to_string(),
        ));
    }

    let typ = client_data
        .get("type")
        .and_then(|v| v.as_str())
        .ok_or_else(|| {
            WebauthnError::VerificationFailed("missing type in client data".to_string())
        })?;
    if typ != expected_type {
        return Err(WebauthnError::VerificationFailed(format!(
            "wrong type: {typ}"
        )));
    }

    let origin = client_data
        .get("origin")
        .and_then(|v| v.as_str())
        .ok_or_else(|| {
            WebauthnError::VerificationFailed("missing origin in client data".to_string())
        })?;
    if !rp_origins.iter().any(|o| o == origin) {
        return Err(WebauthnError::VerificationFailed(format!(
            "origin '{origin}' not allowed"
        )));
    }

    // Note: nested `if let` (not a let-chain) — this crate targets edition 2021.
    if let Some(rp) = client_data.get("rpId").and_then(|v| v.as_str()) {
        if rp != rp_id {
            return Err(WebauthnError::VerificationFailed(format!(
                "rpId mismatch: client sent '{rp}', expected '{rp_id}'"
            )));
        }
    }

    Ok(client_data_bytes)
}

/// Verify a registration response with full CTAP2/COSE verification and
/// attestation statement verification.
///
/// # Security notes / threat assumptions
///
/// - `challenge_bytes` must be the server-generated, single-use challenge for
///   this ceremony (obtain via [`crate::ChallengeStore::consume_registration_challenge`]
///   immediately before calling).
/// - `rp_origins` is an exact-match allow-list; `rp_id` is SHA-256-hashed and
///   compared against the authenticator's `rpIdHash`, which binds the
///   credential to this RP.
/// - The UP and AT flags are mandatory. UV is enforced per
///   `credential_policy.user_verification` ([`UserVerificationPolicy::Required`]
///   rejects UV-clear registrations); the backup-eligibility flag is enforced
///   per `credential_policy.backup`.
/// - Attestation statements are verified for the `none`, `packed`, and
///   `fido-u2f` formats; unknown formats are rejected unless
///   [`AttestationPolicy::allow_unknown_formats`] is set (trust-weakening).
///   The provenance conveyed by a verified attestation is bounded by
///   `attestation.trust_level` in the result — see
///   [`crate::attestation`]: only [`crate::attestation::TrustLevel::AttCa`]
///   (chain terminating at a configured trust anchor) attests device
///   provenance.
/// - Re-registration of an existing credential is rejected when
///   `existing_credential_id` matches the presented credential ID.
///
/// # Requirements
/// REQ-WA-001, REQ-WA-101, REQ-WA-102, REQ-WA-103, REQ-WA-104, REQ-WA-105,
/// REQ-WA-113, REQ-WA-117, REQ-WA-119, REQ-WA-120, REQ-WA-121, REQ-WA-123,
/// REQ-WA-124, REQ-WA-126, REQ-WA-142, REQ-WA-143, REQ-WA-144
///
/// Returns the verified registration data to persist.
#[allow(clippy::too_many_arguments)]
pub fn verify_registration(
    challenge_bytes: &[u8],
    client_data_json_b64: &str,
    attestation_object_b64: &str,
    existing_credential_id: &str,
    rp_id: &str,
    rp_origins: &[String],
    attestation_policy: &AttestationPolicy,
    credential_policy: &CredentialPolicy,
) -> Result<RegistrationResult, WebauthnError> {
    let client_data_bytes = validate_client_data(
        client_data_json_b64,
        challenge_bytes,
        "webauthn.create",
        rp_id,
        rp_origins,
    )?;

    let attestation_bytes = base64_decode_urlsafe(attestation_object_b64)?;
    let attestation_val: ciborium::Value = ciborium::de::from_reader(&attestation_bytes[..])
        .map_err(|e| {
            WebauthnError::AttestationError(format!("attestation object CBOR parse error: {e}"))
        })?;

    // RFC 8949 + CTAP2: the attestation object is a map with TEXT keys
    // ("fmt", "attStmt", "authData") — not the integer-keyed COSE map.
    let attestation_entries = match &attestation_val {
        ciborium::Value::Map(entries) => entries.clone(),
        other => {
            let hex = |b: &[u8]| {
                let mut out = String::new();
                for x in b.iter().take(8) {
                    use std::fmt::Write as _;
                    let _ = write!(out, "{x:02x}");
                }
                out
            };
            return Err(WebauthnError::AttestationError(format!(
                "attestation object is not a CBOR map (decoded {} bytes, first: {}, value kind: {:?})",
                attestation_bytes.len(),
                hex(attestation_bytes.get(..8).unwrap_or(&attestation_bytes)),
                match other {
                    ciborium::Value::Bytes(_) => "bytes",
                    ciborium::Value::Text(_) => "text",
                    ciborium::Value::Array(_) => "array",
                    ciborium::Value::Integer(_) => "integer",
                    ciborium::Value::Bool(_) => "bool",
                    _ => "other",
                },
            )));
        }
    };

    let mut fmt: Option<String> = None;
    let mut auth_data_bytes: Option<Vec<u8>> = None;
    let mut att_stmt: Option<ciborium::Value> = None;

    for (key, val) in &attestation_entries {
        if let ciborium::Value::Text(k) = key {
            match k.as_str() {
                "fmt" => {
                    if let ciborium::Value::Text(s) = val {
                        fmt = Some(s.clone());
                    }
                }
                "authData" => {
                    if let Some(b) = cbor_bytes(val) {
                        auth_data_bytes = Some(b);
                    }
                }
                "attStmt" => {
                    att_stmt = Some(val.clone());
                }
                _ => {}
            }
        }
    }

    let fmt = fmt.unwrap_or_else(|| "none".to_string());
    let auth_data_bytes = auth_data_bytes.ok_or_else(|| {
        WebauthnError::AttestationError("missing authData in attestation object".to_string())
    })?;

    let auth_data = parse_authenticator_data(&auth_data_bytes)?;

    use sha2::Digest;
    let computed_rp_id_hash = sha2::Sha256::digest(rp_id.as_bytes()).to_vec();
    if auth_data.rp_id_hash != computed_rp_id_hash {
        return Err(WebauthnError::VerificationFailed(format!(
            "rpId hash mismatch: computed {:x?}, got {:x?}",
            computed_rp_id_hash, auth_data.rp_id_hash
        )));
    }

    if auth_data.flags & FLAG_UP == 0 {
        return Err(WebauthnError::VerificationFailed(
            "User Present flag not set".to_string(),
        ));
    }

    if auth_data.flags & FLAG_AT == 0 {
        return Err(WebauthnError::VerificationFailed(
            "Attested Credential Data flag not set during registration".to_string(),
        ));
    }

    // Credential policy: UV requirement and backup eligibility (REQ-WA-142/144).
    enforce_flag_policy(auth_data.flags, credential_policy)?;

    let credential_id = auth_data.credential_id.ok_or_else(|| {
        WebauthnError::VerificationFailed("no credential ID in attested data".to_string())
    })?;
    let credential_id_b64 = base64_encode_urlsafe(&credential_id);

    if existing_credential_id == credential_id_b64 {
        return Err(WebauthnError::DuplicateCredential(credential_id_b64));
    }

    let public_key_cose = auth_data.credential_public_key_cose.ok_or_else(|| {
        WebauthnError::VerificationFailed("no public key in attested data".to_string())
    })?;

    let (alg, cose_key) = parse_cose_key(&public_key_cose)?;

    // Server-side algorithm allowlist (REQ-WA-143).
    enforce_algorithm_allowlist(alg, credential_policy)?;

    // Attestation verification (REQ-WA-119..): dispatch on `fmt` and verify
    // the statement per the caller's policy. Fails closed on tampered
    // signatures, unknown formats (unless opted out), and policy violations.
    let client_data_hash = sha2::Sha256::digest(&client_data_bytes).to_vec();
    let aaguid = auth_data.aaguid.unwrap_or([0u8; 16]);
    let attestation = verify_attestation(
        &fmt,
        att_stmt.as_ref(),
        &auth_data_bytes,
        &client_data_hash,
        &credential_id,
        alg,
        &cose_key,
        aaguid,
        attestation_policy,
    )?;

    let user_verified = auth_data.flags & FLAG_UV != 0;

    Ok(RegistrationResult {
        credential_id: credential_id_b64,
        device_name: format!("WebAuthn ({})", alg_to_name(alg)),
        attestation_format: fmt,
        attestation,
        user_verified,
        backup_eligible: auth_data.backup_eligible,
        backup_state: auth_data.backup_state,
    })
}

/// Parameters for verifying an authentication response.
///
/// All base64 fields are client-supplied and hostile; `public_key_cose` and
/// `current_sign_count` are the server-side stored credential state.
#[derive(Debug, Clone)]
pub struct AuthenticationParams {
    /// The raw challenge bytes that were stored server-side.
    pub challenge_bytes: Vec<u8>,
    /// Base64url-encoded client data JSON.
    pub client_data_json_b64: String,
    /// Base64url-encoded authenticator data.
    pub authenticator_data_b64: String,
    /// Base64url-encoded signature.
    pub signature_b64: String,
    /// Base64url-encoded credential ID presented by the authenticator.
    pub credential_id_b64: String,
    /// COSE-encoded public key for this credential.
    pub public_key_cose: Vec<u8>,
    /// Current sign count stored server-side for this credential.
    pub current_sign_count: u32,
    /// Allowed credential IDs for this authentication session.
    pub allowed_credential_ids: Vec<String>,
    /// Expected relying party ID.
    pub rp_id: String,
    /// Allowed origins.
    pub rp_origins: Vec<String>,
    /// Credential policy enforced on this assertion
    /// (default: [`CredentialPolicy::default`] — UV reported, not required).
    ///
    /// # Security note
    ///
    /// With [`UserVerificationPolicy::Required`], an assertion whose UV flag
    /// is clear is rejected — this is the enforcement point for step-up or
    /// high-assurance logins.
    pub policy: CredentialPolicy,
}

/// Verify an authentication response with full CTAP2/COSE signature
/// verification.
///
/// Verification steps, in order:
///
/// 1. Credential ID membership in `allowed_credential_ids`.
/// 2. `clientDataJSON` validation (challenge echo, `type == "webauthn.get"`,
///    origin allow-list, optional `rpId` cross-check).
/// 3. Authenticator data parsing and `rpIdHash` comparison.
/// 4. User Presence flag + credential-policy flag enforcement (UV, backup).
/// 5. Sign-count freshness ([`check_sign_count`]).
/// 6. `ring` signature verification over `authenticatorData || SHA-256(clientDataJSON)`.
///
/// # Security notes / threat assumptions
///
/// - `challenge_bytes` must be consumed from single-use storage before this
///   call; this module does not (and cannot) detect a challenge used twice.
/// - On success the caller MUST persist [`AuthenticationResult::new_sign_count`]
///   (ideally compare-and-swap) before considering the user logged in.
/// - UV is enforced per `params.policy.user_verification`
///   ([`UserVerificationPolicy::Required`] rejects UV-clear assertions);
///   backup eligibility per `params.policy.backup`. The BE/BS flags are
///   always reported on the result.
///
/// # Requirements
/// REQ-WA-002, REQ-WA-101, REQ-WA-102, REQ-WA-103, REQ-WA-104, REQ-WA-105,
/// REQ-WA-106, REQ-WA-111, REQ-WA-114, REQ-WA-116, REQ-WA-142, REQ-WA-144
///
/// Returns the verified authentication data.
pub fn verify_authentication(
    params: &AuthenticationParams,
) -> Result<AuthenticationResult, WebauthnError> {
    let AuthenticationParams {
        challenge_bytes,
        client_data_json_b64,
        authenticator_data_b64,
        signature_b64,
        credential_id_b64,
        public_key_cose,
        current_sign_count,
        allowed_credential_ids,
        rp_id,
        rp_origins,
        policy,
    } = params;

    if !allowed_credential_ids.contains(credential_id_b64) {
        return Err(WebauthnError::VerificationFailed(
            "credential ID not in allowed list".to_string(),
        ));
    }

    let client_data_bytes = validate_client_data(
        client_data_json_b64,
        challenge_bytes,
        "webauthn.get",
        rp_id,
        rp_origins,
    )?;

    let authenticator_data = base64_decode_urlsafe(authenticator_data_b64)?;
    let auth_data = parse_authenticator_data(&authenticator_data)?;

    use sha2::Digest;
    let computed_rp_id_hash = sha2::Sha256::digest(rp_id.as_bytes()).to_vec();
    if auth_data.rp_id_hash != computed_rp_id_hash {
        return Err(WebauthnError::VerificationFailed(format!(
            "rpId hash mismatch: computed {:x?}, got {:x?}",
            computed_rp_id_hash, auth_data.rp_id_hash
        )));
    }

    if auth_data.flags & FLAG_UP == 0 {
        return Err(WebauthnError::VerificationFailed(
            "User Present flag not set".to_string(),
        ));
    }

    // Credential policy: UV requirement and backup eligibility (REQ-WA-142/144).
    enforce_flag_policy(auth_data.flags, policy)?;

    check_sign_count(*current_sign_count, auth_data.sign_count)?;

    let client_data_hash = sha2::Sha256::digest(&client_data_bytes).to_vec();

    let mut signed_data = Vec::with_capacity(authenticator_data.len() + 32);
    signed_data.extend_from_slice(&authenticator_data);
    signed_data.extend_from_slice(&client_data_hash);

    let signature = base64_decode_urlsafe(signature_b64)?;

    let (alg, cose_key) = parse_cose_key(public_key_cose)?;
    verify_cose_signature(alg, &cose_key, &signed_data, &signature)?;

    let user_verified = auth_data.flags & FLAG_UV != 0;
    let new_sign_count = auth_data.sign_count;

    Ok(AuthenticationResult {
        credential_id: credential_id_b64.clone(),
        new_sign_count,
        user_verified,
        backup_state: auth_data.backup_state,
        backup_eligible: auth_data.backup_eligible,
    })
}

// Tests exercise failure paths and invariants directly; unwrap/expect,
// slicing, and panicking asserts are acceptable here — violations
// surface as test failures, not production panics.
#[allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::indexing_slicing,
    clippy::panic
)]
#[cfg(test)]
mod tests {
    use super::*;
    use crate::crypto::tests::{build_cose_ec2_key, build_cose_rsa_key};
    use crate::crypto::{base64_encode_urlsafe, generate_challenge_bytes, COSE_ALG_RS256};
    use ring::signature::KeyPair as _;

    fn build_attestation_object(auth_data: &[u8]) -> Vec<u8> {
        use ciborium::Value;
        // Real CTAP2 attestation objects use TEXT keys.
        let map = vec![
            (
                Value::Text("fmt".to_string()),
                Value::Text("none".to_string()),
            ),
            (Value::Text("attStmt".to_string()), Value::Map(vec![])),
            (
                Value::Text("authData".to_string()),
                Value::Bytes(auth_data.to_vec()),
            ),
        ];
        let mut buf = Vec::new();
        ciborium::ser::into_writer(&Value::Map(map), &mut buf).unwrap();
        buf
    }

    fn build_auth_data_with_credential(
        rp_id: &str,
        flags: u8,
        sign_count: u32,
        credential_id: &[u8],
        cose_key: &[u8],
    ) -> Vec<u8> {
        use sha2::Digest;
        let rp_id_hash = sha2::Sha256::digest(rp_id.as_bytes()).to_vec();
        let mut auth_data = Vec::new();
        auth_data.extend_from_slice(&rp_id_hash);
        auth_data.push(flags);
        auth_data.extend_from_slice(&sign_count.to_be_bytes());

        if flags & FLAG_AT != 0 {
            auth_data.extend_from_slice(&[0u8; 16]);
            auth_data.extend_from_slice(&(credential_id.len() as u16).to_be_bytes());
            auth_data.extend_from_slice(credential_id);
            auth_data.extend_from_slice(cose_key);
        }

        auth_data
    }

    #[test]
    fn test_parse_authenticator_data_minimal() {
        let mut auth_data = vec![0u8; 37];
        auth_data[..32].copy_from_slice(&[0xAA; 32]);
        auth_data[32] = FLAG_UP;
        auth_data[33..37].copy_from_slice(&1u32.to_be_bytes());

        let parsed = parse_authenticator_data(&auth_data).unwrap();
        assert_eq!(parsed.rp_id_hash, vec![0xAA; 32]);
        assert_eq!(parsed.flags, FLAG_UP);
        assert_eq!(parsed.sign_count, 1);
        assert!(parsed.credential_public_key_cose.is_none());
        assert!(parsed.credential_id.is_none());
    }

    #[test]
    fn test_parse_authenticator_data_with_attested_credential() {
        let credential_id = vec![0x01, 0x02, 0x03, 0x04];
        let public_key_cose = vec![0x10, 0x20, 0x30];

        let total_len = 37 + 16 + 2 + credential_id.len() + public_key_cose.len();
        let mut auth_data = vec![0u8; total_len];
        auth_data[32] = FLAG_UP | FLAG_AT;
        auth_data[33..37].copy_from_slice(&5u32.to_be_bytes());

        let offset = 37 + 16;
        auth_data[offset..offset + 2].copy_from_slice(&(credential_id.len() as u16).to_be_bytes());
        auth_data[offset + 2..offset + 2 + credential_id.len()].copy_from_slice(&credential_id);
        let pk_offset = offset + 2 + credential_id.len();
        auth_data[pk_offset..].copy_from_slice(&public_key_cose);

        let parsed = parse_authenticator_data(&auth_data).unwrap();
        assert_eq!(parsed.flags, FLAG_UP | FLAG_AT);
        assert_eq!(parsed.sign_count, 5);
        assert_eq!(parsed.credential_id, Some(credential_id));
        assert_eq!(parsed.credential_public_key_cose, Some(public_key_cose));
    }

    #[test]
    fn test_parse_authenticator_data_too_short() {
        let auth_data = vec![0u8; 10];
        let result = parse_authenticator_data(&auth_data);
        assert!(result.is_err());
    }

    #[test]
    fn test_verify_registration_valid_es256() {
        use ring::signature::EcdsaKeyPair;

        let rng = ring::rand::SystemRandom::new();
        let pkcs8 =
            EcdsaKeyPair::generate_pkcs8(&ring::signature::ECDSA_P256_SHA256_FIXED_SIGNING, &rng)
                .unwrap();
        let key_pair = EcdsaKeyPair::from_pkcs8(
            &ring::signature::ECDSA_P256_SHA256_FIXED_SIGNING,
            pkcs8.as_ref(),
            &rng,
        )
        .unwrap();

        let pub_bytes = key_pair.public_key().as_ref().to_vec();
        let x = pub_bytes[1..33].to_vec();
        let y = pub_bytes[33..65].to_vec();
        let cose_key = build_cose_ec2_key(&x, &y);

        let credential_id = vec![0x01, 0x02, 0x03, 0x04];
        let auth_data = build_auth_data_with_credential(
            "localhost",
            FLAG_UP | FLAG_AT,
            0,
            &credential_id,
            &cose_key,
        );
        let att_obj = build_attestation_object(&auth_data);

        let challenge = generate_challenge_bytes();
        let challenge_b64 = base64_encode_urlsafe(&challenge);

        let client_data = serde_json::json!({
            "type": "webauthn.create",
            "challenge": challenge_b64,
            "origin": "http://localhost:8080",
        });
        let client_data_b64 = base64_encode_urlsafe(&serde_json::to_vec(&client_data).unwrap());
        let att_obj_b64 = base64_encode_urlsafe(&att_obj);

        let result = verify_registration(
            &challenge,
            &client_data_b64,
            &att_obj_b64,
            "different-id",
            "localhost",
            &["http://localhost:8080".to_string()],
            &AttestationPolicy::default(),
            &CredentialPolicy::default(),
        )
        .unwrap();

        assert_eq!(result.credential_id, base64_encode_urlsafe(&credential_id));
        assert!(result.attestation_format == "none");
    }

    #[test]
    fn test_verify_registration_challenge_mismatch() {
        let auth_data = build_auth_data_with_credential(
            "localhost",
            FLAG_UP | FLAG_AT,
            0,
            &[0x01],
            &build_cose_ec2_key(&[0xAA; 32], &[0xBB; 32]),
        );
        let att_obj = build_attestation_object(&auth_data);

        let challenge = generate_challenge_bytes();
        let _challenge_b64 = base64_encode_urlsafe(&challenge);

        let client_data = serde_json::json!({
            "type": "webauthn.create",
            "challenge": base64_encode_urlsafe(&[1u8; 32]),
            "origin": "http://localhost:8080",
        });
        let client_data_b64 = base64_encode_urlsafe(&serde_json::to_vec(&client_data).unwrap());
        let att_obj_b64 = base64_encode_urlsafe(&att_obj);

        let result = verify_registration(
            &challenge,
            &client_data_b64,
            &att_obj_b64,
            "different",
            "localhost",
            &["http://localhost:8080".to_string()],
            &AttestationPolicy::default(),
            &CredentialPolicy::default(),
        );
        assert!(matches!(result, Err(WebauthnError::VerificationFailed(_))));
    }

    #[test]
    fn test_verify_registration_wrong_type() {
        let auth_data = build_auth_data_with_credential(
            "localhost",
            FLAG_UP | FLAG_AT,
            0,
            &[0x01],
            &build_cose_ec2_key(&[0xAA; 32], &[0xBB; 32]),
        );
        let att_obj = build_attestation_object(&auth_data);

        let challenge = generate_challenge_bytes();
        let challenge_b64 = base64_encode_urlsafe(&challenge);

        let client_data = serde_json::json!({
            "type": "webauthn.get",
            "challenge": challenge_b64,
            "origin": "http://localhost:8080",
        });
        let client_data_b64 = base64_encode_urlsafe(&serde_json::to_vec(&client_data).unwrap());
        let att_obj_b64 = base64_encode_urlsafe(&att_obj);

        let result = verify_registration(
            &challenge,
            &client_data_b64,
            &att_obj_b64,
            "different",
            "localhost",
            &["http://localhost:8080".to_string()],
            &AttestationPolicy::default(),
            &CredentialPolicy::default(),
        );
        assert!(matches!(result, Err(WebauthnError::VerificationFailed(_))));
    }

    #[test]
    fn test_verify_registration_wrong_origin() {
        let auth_data = build_auth_data_with_credential(
            "localhost",
            FLAG_UP | FLAG_AT,
            0,
            &[0x01],
            &build_cose_ec2_key(&[0xAA; 32], &[0xBB; 32]),
        );
        let att_obj = build_attestation_object(&auth_data);

        let challenge = generate_challenge_bytes();
        let challenge_b64 = base64_encode_urlsafe(&challenge);

        let client_data = serde_json::json!({
            "type": "webauthn.create",
            "challenge": challenge_b64,
            "origin": "http://evil.com",
        });
        let client_data_b64 = base64_encode_urlsafe(&serde_json::to_vec(&client_data).unwrap());
        let att_obj_b64 = base64_encode_urlsafe(&att_obj);

        let result = verify_registration(
            &challenge,
            &client_data_b64,
            &att_obj_b64,
            "different",
            "localhost",
            &["http://localhost:8080".to_string()],
            &AttestationPolicy::default(),
            &CredentialPolicy::default(),
        );
        assert!(matches!(result, Err(WebauthnError::VerificationFailed(_))));
    }

    #[test]
    fn test_verify_registration_duplicate() {
        let auth_data = build_auth_data_with_credential(
            "localhost",
            FLAG_UP | FLAG_AT,
            0,
            &[0x01, 0x02, 0x03],
            &build_cose_ec2_key(&[0xAA; 32], &[0xBB; 32]),
        );
        let att_obj = build_attestation_object(&auth_data);

        let challenge = generate_challenge_bytes();
        let challenge_b64 = base64_encode_urlsafe(&challenge);

        let client_data = serde_json::json!({
            "type": "webauthn.create",
            "challenge": challenge_b64,
            "origin": "http://localhost:8080",
        });
        let client_data_b64 = base64_encode_urlsafe(&serde_json::to_vec(&client_data).unwrap());
        let att_obj_b64 = base64_encode_urlsafe(&att_obj);
        let cred_id_b64 = base64_encode_urlsafe(&[0x01, 0x02, 0x03]);

        let result = verify_registration(
            &challenge,
            &client_data_b64,
            &att_obj_b64,
            &cred_id_b64,
            "localhost",
            &["http://localhost:8080".to_string()],
            &AttestationPolicy::default(),
            &CredentialPolicy::default(),
        );
        assert!(matches!(result, Err(WebauthnError::DuplicateCredential(_))));
    }

    #[test]
    fn test_verify_registration_wrong_rp_id_hash() {
        let credential_id = vec![0x01];
        let cose_key = build_cose_ec2_key(&[0xAA; 32], &[0xBB; 32]);
        let auth_data = build_auth_data_with_credential(
            "evil.com",
            FLAG_UP | FLAG_AT,
            0,
            &credential_id,
            &cose_key,
        );
        let att_obj = build_attestation_object(&auth_data);

        let challenge = generate_challenge_bytes();
        let challenge_b64 = base64_encode_urlsafe(&challenge);

        let client_data = serde_json::json!({
            "type": "webauthn.create",
            "challenge": challenge_b64,
            "origin": "http://localhost:8080",
        });
        let client_data_b64 = base64_encode_urlsafe(&serde_json::to_vec(&client_data).unwrap());
        let att_obj_b64 = base64_encode_urlsafe(&att_obj);

        let result = verify_registration(
            &challenge,
            &client_data_b64,
            &att_obj_b64,
            "different",
            "localhost",
            &["http://localhost:8080".to_string()],
            &AttestationPolicy::default(),
            &CredentialPolicy::default(),
        );
        assert!(matches!(result, Err(WebauthnError::VerificationFailed(_))));
    }

    #[test]
    fn test_verify_registration_missing_up_flag() {
        let credential_id = vec![0x01];
        let cose_key = build_cose_ec2_key(&[0xAA; 32], &[0xBB; 32]);
        let auth_data =
            build_auth_data_with_credential("localhost", FLAG_AT, 0, &credential_id, &cose_key);
        let att_obj = build_attestation_object(&auth_data);

        let challenge = generate_challenge_bytes();
        let challenge_b64 = base64_encode_urlsafe(&challenge);

        let client_data = serde_json::json!({
            "type": "webauthn.create",
            "challenge": challenge_b64,
            "origin": "http://localhost:8080",
        });
        let client_data_b64 = base64_encode_urlsafe(&serde_json::to_vec(&client_data).unwrap());
        let att_obj_b64 = base64_encode_urlsafe(&att_obj);

        let result = verify_registration(
            &challenge,
            &client_data_b64,
            &att_obj_b64,
            "different",
            "localhost",
            &["http://localhost:8080".to_string()],
            &AttestationPolicy::default(),
            &CredentialPolicy::default(),
        );
        assert!(matches!(result, Err(WebauthnError::VerificationFailed(_))));
    }

    /// REQ-WA-117: registration with UP set but the AT flag clear (no
    /// attested credential data) must be rejected — a credential cannot be
    /// registered without attested key material.
    #[test]
    fn registration_rejects_missing_at_flag() {
        let auth_data = build_auth_data_with_credential(
            "localhost",
            FLAG_UP, // UP set, AT clear
            0,
            &[0x01],
            &build_cose_ec2_key(&[0xAA; 32], &[0xBB; 32]),
        );
        let att_obj = build_attestation_object(&auth_data);

        let challenge = generate_challenge_bytes();
        let challenge_b64 = base64_encode_urlsafe(&challenge);

        let client_data = serde_json::json!({
            "type": "webauthn.create",
            "challenge": challenge_b64,
            "origin": "http://localhost:8080",
        });
        let client_data_b64 = base64_encode_urlsafe(&serde_json::to_vec(&client_data).unwrap());
        let att_obj_b64 = base64_encode_urlsafe(&att_obj);

        let result = verify_registration(
            &challenge,
            &client_data_b64,
            &att_obj_b64,
            "different",
            "localhost",
            &["http://localhost:8080".to_string()],
            &AttestationPolicy::default(),
            &CredentialPolicy::default(),
        );
        assert!(matches!(result, Err(WebauthnError::VerificationFailed(_))));
    }

    #[test]
    fn test_verify_authentication_valid_es256() {
        use ring::signature::EcdsaKeyPair;

        let rng = ring::rand::SystemRandom::new();
        let pkcs8 =
            EcdsaKeyPair::generate_pkcs8(&ring::signature::ECDSA_P256_SHA256_FIXED_SIGNING, &rng)
                .unwrap();
        let key_pair = EcdsaKeyPair::from_pkcs8(
            &ring::signature::ECDSA_P256_SHA256_FIXED_SIGNING,
            pkcs8.as_ref(),
            &rng,
        )
        .unwrap();

        let pub_bytes = key_pair.public_key().as_ref().to_vec();
        let x = pub_bytes[1..33].to_vec();
        let y = pub_bytes[33..65].to_vec();
        let cose_key = build_cose_ec2_key(&x, &y);

        let challenge = generate_challenge_bytes();
        let challenge_b64 = base64_encode_urlsafe(&challenge);

        use sha2::Digest;
        let rp_id_hash = sha2::Sha256::digest(b"localhost").to_vec();
        let mut auth_data = Vec::new();
        auth_data.extend_from_slice(&rp_id_hash);
        auth_data.push(FLAG_UP);
        auth_data.extend_from_slice(&1u32.to_be_bytes());

        let client_data = serde_json::json!({
            "type": "webauthn.get",
            "challenge": challenge_b64,
            "origin": "http://localhost:8080",
        });
        let client_data_bytes = serde_json::to_vec(&client_data).unwrap();
        let client_data_b64 = base64_encode_urlsafe(&client_data_bytes);
        let client_data_hash = sha2::Sha256::digest(&client_data_bytes).to_vec();

        let mut signed_data = Vec::new();
        signed_data.extend_from_slice(&auth_data);
        signed_data.extend_from_slice(&client_data_hash);

        let signature = key_pair.sign(&rng, &signed_data).unwrap();

        let auth_data_b64 = base64_encode_urlsafe(&auth_data);
        let sig_b64 = base64_encode_urlsafe(signature.as_ref());
        let cred_id_b64 = base64_encode_urlsafe(&[0x01, 0x02]);

        let result = verify_authentication(&AuthenticationParams {
            challenge_bytes: challenge.clone(),
            client_data_json_b64: client_data_b64,
            authenticator_data_b64: auth_data_b64,
            signature_b64: sig_b64,
            credential_id_b64: cred_id_b64.clone(),
            public_key_cose: cose_key,
            current_sign_count: 0,
            allowed_credential_ids: vec![cred_id_b64.clone()],
            rp_id: "localhost".to_string(),
            rp_origins: vec!["http://localhost:8080".to_string()],
            policy: CredentialPolicy::default(),
        })
        .unwrap();

        assert_eq!(result.credential_id, cred_id_b64);
        assert_eq!(result.new_sign_count, 1);
    }

    #[test]
    fn test_verify_authentication_wrong_signature() {
        use ring::signature::EcdsaKeyPair;

        let rng = ring::rand::SystemRandom::new();
        let pkcs8 =
            EcdsaKeyPair::generate_pkcs8(&ring::signature::ECDSA_P256_SHA256_FIXED_SIGNING, &rng)
                .unwrap();
        let key_pair = EcdsaKeyPair::from_pkcs8(
            &ring::signature::ECDSA_P256_SHA256_FIXED_SIGNING,
            pkcs8.as_ref(),
            &rng,
        )
        .unwrap();

        let pub_bytes = key_pair.public_key().as_ref().to_vec();
        let x = pub_bytes[1..33].to_vec();
        let y = pub_bytes[33..65].to_vec();
        let cose_key = build_cose_ec2_key(&x, &y);

        let challenge = generate_challenge_bytes();
        let challenge_b64 = base64_encode_urlsafe(&challenge);

        use sha2::Digest;
        let rp_id_hash = sha2::Sha256::digest(b"localhost").to_vec();
        let mut auth_data = Vec::new();
        auth_data.extend_from_slice(&rp_id_hash);
        auth_data.push(FLAG_UP);
        auth_data.extend_from_slice(&1u32.to_be_bytes());

        let client_data = serde_json::json!({
            "type": "webauthn.get",
            "challenge": challenge_b64,
            "origin": "http://localhost:8080",
        });
        let client_data_bytes = serde_json::to_vec(&client_data).unwrap();
        let client_data_b64 = base64_encode_urlsafe(&client_data_bytes);
        let client_data_hash = sha2::Sha256::digest(&client_data_bytes).to_vec();

        let mut signed_data = Vec::new();
        signed_data.extend_from_slice(&auth_data);
        signed_data.extend_from_slice(&client_data_hash);

        let mut wrong_sig = vec![0u8; 64];
        wrong_sig[0] = 0xFF;

        let auth_data_b64 = base64_encode_urlsafe(&auth_data);
        let sig_b64 = base64_encode_urlsafe(&wrong_sig);
        let cred_id_b64 = base64_encode_urlsafe(&[0x01]);

        let result = verify_authentication(&AuthenticationParams {
            challenge_bytes: challenge.clone(),
            client_data_json_b64: client_data_b64,
            authenticator_data_b64: auth_data_b64,
            signature_b64: sig_b64,
            credential_id_b64: cred_id_b64.clone(),
            public_key_cose: cose_key,
            current_sign_count: 0,
            allowed_credential_ids: vec![cred_id_b64],
            rp_id: "localhost".to_string(),
            rp_origins: vec!["http://localhost:8080".to_string()],
            policy: CredentialPolicy::default(),
        });
        assert!(matches!(
            result,
            Err(WebauthnError::SignatureVerificationFailed)
        ));
    }

    #[test]
    fn test_verify_authentication_credential_not_allowed() {
        let challenge = generate_challenge_bytes();
        let challenge_b64 = base64_encode_urlsafe(&challenge);

        let client_data = serde_json::json!({
            "type": "webauthn.get",
            "challenge": challenge_b64,
            "origin": "http://localhost:8080",
        });
        let client_data_b64 = base64_encode_urlsafe(&serde_json::to_vec(&client_data).unwrap());

        use sha2::Digest;
        let rp_id_hash = sha2::Sha256::digest(b"localhost").to_vec();
        let mut auth_data = Vec::new();
        auth_data.extend_from_slice(&rp_id_hash);
        auth_data.push(FLAG_UP);
        auth_data.extend_from_slice(&0u32.to_be_bytes());
        let auth_data_b64 = base64_encode_urlsafe(&auth_data);

        let result = verify_authentication(&AuthenticationParams {
            challenge_bytes: challenge.clone(),
            client_data_json_b64: client_data_b64,
            authenticator_data_b64: auth_data_b64,
            signature_b64: "sig".to_string(),
            credential_id_b64: "unauthorized-cred".to_string(),
            public_key_cose: vec![0x10, 0x20],
            current_sign_count: 0,
            allowed_credential_ids: vec!["allowed-cred".to_string()],
            rp_id: "localhost".to_string(),
            rp_origins: vec!["http://localhost:8080".to_string()],
            policy: CredentialPolicy::default(),
        });
        assert!(matches!(result, Err(WebauthnError::VerificationFailed(_))));
    }

    #[test]
    fn test_verify_authentication_wrong_origin() {
        let challenge = generate_challenge_bytes();
        let challenge_b64 = base64_encode_urlsafe(&challenge);

        let client_data = serde_json::json!({
            "type": "webauthn.get",
            "challenge": challenge_b64,
            "origin": "http://evil.com",
        });
        let client_data_b64 = base64_encode_urlsafe(&serde_json::to_vec(&client_data).unwrap());

        use sha2::Digest;
        let rp_id_hash = sha2::Sha256::digest(b"localhost").to_vec();
        let mut auth_data = Vec::new();
        auth_data.extend_from_slice(&rp_id_hash);
        auth_data.push(FLAG_UP);
        auth_data.extend_from_slice(&0u32.to_be_bytes());
        let auth_data_b64 = base64_encode_urlsafe(&auth_data);

        let result = verify_authentication(&AuthenticationParams {
            challenge_bytes: challenge.clone(),
            client_data_json_b64: client_data_b64,
            authenticator_data_b64: auth_data_b64,
            signature_b64: "sig".to_string(),
            credential_id_b64: "cred".to_string(),
            public_key_cose: vec![0x10],
            current_sign_count: 0,
            allowed_credential_ids: vec!["cred".to_string()],
            rp_id: "localhost".to_string(),
            rp_origins: vec!["http://localhost:8080".to_string()],
            policy: CredentialPolicy::default(),
        });
        assert!(matches!(result, Err(WebauthnError::VerificationFailed(_))));
    }

    #[test]
    fn test_verify_authentication_wrong_type() {
        let challenge = generate_challenge_bytes();
        let challenge_b64 = base64_encode_urlsafe(&challenge);

        let client_data = serde_json::json!({
            "type": "webauthn.create",
            "challenge": challenge_b64,
            "origin": "http://localhost:8080",
        });
        let client_data_b64 = base64_encode_urlsafe(&serde_json::to_vec(&client_data).unwrap());

        use sha2::Digest;
        let rp_id_hash = sha2::Sha256::digest(b"localhost").to_vec();
        let mut auth_data = Vec::new();
        auth_data.extend_from_slice(&rp_id_hash);
        auth_data.push(FLAG_UP);
        auth_data.extend_from_slice(&0u32.to_be_bytes());
        let auth_data_b64 = base64_encode_urlsafe(&auth_data);

        let result = verify_authentication(&AuthenticationParams {
            challenge_bytes: challenge.clone(),
            client_data_json_b64: client_data_b64,
            authenticator_data_b64: auth_data_b64,
            signature_b64: "sig".to_string(),
            credential_id_b64: "cred".to_string(),
            public_key_cose: vec![0x10],
            current_sign_count: 0,
            allowed_credential_ids: vec!["cred".to_string()],
            rp_id: "localhost".to_string(),
            rp_origins: vec!["http://localhost:8080".to_string()],
            policy: CredentialPolicy::default(),
        });
        assert!(matches!(result, Err(WebauthnError::VerificationFailed(_))));
    }

    #[test]
    fn test_verify_authentication_sign_count_decrease() {
        use ring::signature::EcdsaKeyPair;

        let rng = ring::rand::SystemRandom::new();
        let pkcs8 =
            EcdsaKeyPair::generate_pkcs8(&ring::signature::ECDSA_P256_SHA256_FIXED_SIGNING, &rng)
                .unwrap();
        let key_pair = EcdsaKeyPair::from_pkcs8(
            &ring::signature::ECDSA_P256_SHA256_FIXED_SIGNING,
            pkcs8.as_ref(),
            &rng,
        )
        .unwrap();

        let pub_bytes = key_pair.public_key().as_ref().to_vec();
        let x = pub_bytes[1..33].to_vec();
        let y = pub_bytes[33..65].to_vec();
        let cose_key = build_cose_ec2_key(&x, &y);

        let challenge = generate_challenge_bytes();
        let challenge_b64 = base64_encode_urlsafe(&challenge);

        use sha2::Digest;
        let rp_id_hash = sha2::Sha256::digest(b"localhost").to_vec();
        let mut auth_data = Vec::new();
        auth_data.extend_from_slice(&rp_id_hash);
        auth_data.push(FLAG_UP);
        auth_data.extend_from_slice(&5u32.to_be_bytes());

        let client_data = serde_json::json!({
            "type": "webauthn.get",
            "challenge": challenge_b64,
            "origin": "http://localhost:8080",
        });
        let client_data_bytes = serde_json::to_vec(&client_data).unwrap();
        let client_data_b64 = base64_encode_urlsafe(&client_data_bytes);
        let client_data_hash = sha2::Sha256::digest(&client_data_bytes).to_vec();

        let mut signed_data = Vec::new();
        signed_data.extend_from_slice(&auth_data);
        signed_data.extend_from_slice(&client_data_hash);

        let signature = key_pair.sign(&rng, &signed_data).unwrap();

        let auth_data_b64 = base64_encode_urlsafe(&auth_data);
        let sig_b64 = base64_encode_urlsafe(signature.as_ref());
        let cred_id_b64 = base64_encode_urlsafe(&[0x01]);

        let result = verify_authentication(&AuthenticationParams {
            challenge_bytes: challenge.clone(),
            client_data_json_b64: client_data_b64,
            authenticator_data_b64: auth_data_b64,
            signature_b64: sig_b64,
            credential_id_b64: cred_id_b64.clone(),
            public_key_cose: cose_key,
            current_sign_count: 10,
            allowed_credential_ids: vec![cred_id_b64],
            rp_id: "localhost".to_string(),
            rp_origins: vec!["http://localhost:8080".to_string()],
            policy: CredentialPolicy::default(),
        });
        assert!(matches!(result, Err(WebauthnError::VerificationFailed(_))));
    }

    #[test]
    fn test_verify_authentication_wrong_rp_id_hash() {
        let challenge = generate_challenge_bytes();
        let challenge_b64 = base64_encode_urlsafe(&challenge);

        let client_data = serde_json::json!({
            "type": "webauthn.get",
            "challenge": challenge_b64,
            "origin": "http://localhost:8080",
        });
        let client_data_b64 = base64_encode_urlsafe(&serde_json::to_vec(&client_data).unwrap());

        use sha2::Digest;
        let rp_id_hash = sha2::Sha256::digest(b"evil.com").to_vec();
        let mut auth_data = Vec::new();
        auth_data.extend_from_slice(&rp_id_hash);
        auth_data.push(FLAG_UP);
        auth_data.extend_from_slice(&0u32.to_be_bytes());
        let auth_data_b64 = base64_encode_urlsafe(&auth_data);

        let result = verify_authentication(&AuthenticationParams {
            challenge_bytes: challenge.clone(),
            client_data_json_b64: client_data_b64,
            authenticator_data_b64: auth_data_b64,
            signature_b64: "sig".to_string(),
            credential_id_b64: "cred".to_string(),
            public_key_cose: vec![0x10],
            current_sign_count: 0,
            allowed_credential_ids: vec!["cred".to_string()],
            rp_id: "localhost".to_string(),
            rp_origins: vec!["http://localhost:8080".to_string()],
            policy: CredentialPolicy::default(),
        });
        assert!(matches!(result, Err(WebauthnError::VerificationFailed(_))));
    }

    #[test]
    fn test_verify_authentication_missing_up_flag() {
        use ring::signature::EcdsaKeyPair;

        let rng = ring::rand::SystemRandom::new();
        let pkcs8 =
            EcdsaKeyPair::generate_pkcs8(&ring::signature::ECDSA_P256_SHA256_FIXED_SIGNING, &rng)
                .unwrap();
        let key_pair = EcdsaKeyPair::from_pkcs8(
            &ring::signature::ECDSA_P256_SHA256_FIXED_SIGNING,
            pkcs8.as_ref(),
            &rng,
        )
        .unwrap();

        let pub_bytes = key_pair.public_key().as_ref().to_vec();
        let x = pub_bytes[1..33].to_vec();
        let y = pub_bytes[33..65].to_vec();
        let cose_key = build_cose_ec2_key(&x, &y);

        let challenge = generate_challenge_bytes();
        let challenge_b64 = base64_encode_urlsafe(&challenge);

        use sha2::Digest;
        let rp_id_hash = sha2::Sha256::digest(b"localhost").to_vec();
        let mut auth_data = Vec::new();
        auth_data.extend_from_slice(&rp_id_hash);
        auth_data.push(0);
        auth_data.extend_from_slice(&1u32.to_be_bytes());

        let client_data = serde_json::json!({
            "type": "webauthn.get",
            "challenge": challenge_b64,
            "origin": "http://localhost:8080",
        });
        let client_data_bytes = serde_json::to_vec(&client_data).unwrap();
        let client_data_b64 = base64_encode_urlsafe(&client_data_bytes);
        let client_data_hash = sha2::Sha256::digest(&client_data_bytes).to_vec();

        let mut signed_data = Vec::new();
        signed_data.extend_from_slice(&auth_data);
        signed_data.extend_from_slice(&client_data_hash);

        let signature = key_pair.sign(&rng, &signed_data).unwrap();

        let auth_data_b64 = base64_encode_urlsafe(&auth_data);
        let sig_b64 = base64_encode_urlsafe(signature.as_ref());
        let cred_id_b64 = base64_encode_urlsafe(&[0x01]);

        let result = verify_authentication(&AuthenticationParams {
            challenge_bytes: challenge.clone(),
            client_data_json_b64: client_data_b64,
            authenticator_data_b64: auth_data_b64,
            signature_b64: sig_b64,
            credential_id_b64: cred_id_b64.clone(),
            public_key_cose: cose_key,
            current_sign_count: 0,
            allowed_credential_ids: vec![cred_id_b64],
            rp_id: "localhost".to_string(),
            rp_origins: vec!["http://localhost:8080".to_string()],
            policy: CredentialPolicy::default(),
        });
        assert!(matches!(result, Err(WebauthnError::VerificationFailed(_))));
    }

    #[test]
    fn test_verify_authentication_wrong_rp_id_in_client_data() {
        use ring::signature::EcdsaKeyPair;

        let rng = ring::rand::SystemRandom::new();
        let pkcs8 =
            EcdsaKeyPair::generate_pkcs8(&ring::signature::ECDSA_P256_SHA256_FIXED_SIGNING, &rng)
                .unwrap();
        let key_pair = EcdsaKeyPair::from_pkcs8(
            &ring::signature::ECDSA_P256_SHA256_FIXED_SIGNING,
            pkcs8.as_ref(),
            &rng,
        )
        .unwrap();

        let pub_bytes = key_pair.public_key().as_ref().to_vec();
        let x = pub_bytes[1..33].to_vec();
        let y = pub_bytes[33..65].to_vec();
        let cose_key = build_cose_ec2_key(&x, &y);

        let challenge = generate_challenge_bytes();
        let challenge_b64 = base64_encode_urlsafe(&challenge);

        let client_data = serde_json::json!({
            "type": "webauthn.get",
            "challenge": challenge_b64,
            "origin": "http://localhost:8080",
            "rpId": "evil.com",
        });
        let client_data_bytes = serde_json::to_vec(&client_data).unwrap();
        let client_data_b64 = base64_encode_urlsafe(&client_data_bytes);

        use sha2::Digest;
        let rp_id_hash = sha2::Sha256::digest(b"localhost").to_vec();
        let mut auth_data = Vec::new();
        auth_data.extend_from_slice(&rp_id_hash);
        auth_data.push(FLAG_UP);
        auth_data.extend_from_slice(&1u32.to_be_bytes());

        let client_data_hash = sha2::Sha256::digest(&client_data_bytes).to_vec();
        let mut signed_data = Vec::new();
        signed_data.extend_from_slice(&auth_data);
        signed_data.extend_from_slice(&client_data_hash);

        let signature = key_pair.sign(&rng, &signed_data).unwrap();

        let auth_data_b64 = base64_encode_urlsafe(&auth_data);
        let sig_b64 = base64_encode_urlsafe(signature.as_ref());
        let cred_id_b64 = base64_encode_urlsafe(&[0x01]);

        let result = verify_authentication(&AuthenticationParams {
            challenge_bytes: challenge.clone(),
            client_data_json_b64: client_data_b64,
            authenticator_data_b64: auth_data_b64,
            signature_b64: sig_b64,
            credential_id_b64: cred_id_b64.clone(),
            public_key_cose: cose_key,
            current_sign_count: 0,
            allowed_credential_ids: vec![cred_id_b64],
            rp_id: "localhost".to_string(),
            rp_origins: vec!["http://localhost:8080".to_string()],
            policy: CredentialPolicy::default(),
        });
        assert!(matches!(result, Err(WebauthnError::VerificationFailed(_))));
    }

    #[test]
    fn test_verify_authentication_challenge_mismatch() {
        let challenge = generate_challenge_bytes();
        let _challenge_b64 = base64_encode_urlsafe(&challenge);

        let client_data = serde_json::json!({
            "type": "webauthn.get",
            "challenge": base64_encode_urlsafe(&[99u8; 32]),
            "origin": "http://localhost:8080",
        });
        let client_data_b64 = base64_encode_urlsafe(&serde_json::to_vec(&client_data).unwrap());

        use sha2::Digest;
        let rp_id_hash = sha2::Sha256::digest(b"localhost").to_vec();
        let mut auth_data = Vec::new();
        auth_data.extend_from_slice(&rp_id_hash);
        auth_data.push(FLAG_UP);
        auth_data.extend_from_slice(&0u32.to_be_bytes());
        let auth_data_b64 = base64_encode_urlsafe(&auth_data);

        let result = verify_authentication(&AuthenticationParams {
            challenge_bytes: challenge.clone(),
            client_data_json_b64: client_data_b64,
            authenticator_data_b64: auth_data_b64,
            signature_b64: "sig".to_string(),
            credential_id_b64: "cred".to_string(),
            public_key_cose: vec![0x10],
            current_sign_count: 0,
            allowed_credential_ids: vec!["cred".to_string()],
            rp_id: "localhost".to_string(),
            rp_origins: vec!["http://localhost:8080".to_string()],
            policy: CredentialPolicy::default(),
        });
        assert!(matches!(result, Err(WebauthnError::VerificationFailed(_))));
    }

    #[test]
    fn test_verify_authentication_rs256_roundtrip() {
        // Synthetic fixed-size RSA test key is impractical here; verify the
        // RS256 *dispatch* path instead: an ES256 key claiming RS256 is
        // rejected (key type/algorithm cross-check), proving the RS256 arm
        // requires RSA material.
        let cose_key = build_cose_rsa_key(&[0xAA; 256], &[0x01, 0x00, 0x01]);
        let (alg, key) = crate::crypto::parse_cose_key(&cose_key).unwrap();
        assert_eq!(alg, COSE_ALG_RS256);
        let result = verify_cose_signature(COSE_ALG_RS256, &key, b"data", &[0u8; 256]);
        assert!(matches!(
            result,
            Err(WebauthnError::SignatureVerificationFailed)
        ));
    }

    /// Build a fully valid ES256 registration response. `rp_id_field`
    /// injects a matching `rpId` into clientDataJSON; `extra_att_key`
    /// appends an unknown key to the attestation object (must be ignored).
    fn valid_registration(rp_id_field: bool, extra_att_key: bool) -> (Vec<u8>, String, String) {
        use ring::signature::EcdsaKeyPair;

        let rng = ring::rand::SystemRandom::new();
        let pkcs8 =
            EcdsaKeyPair::generate_pkcs8(&ring::signature::ECDSA_P256_SHA256_FIXED_SIGNING, &rng)
                .unwrap();
        let key_pair = EcdsaKeyPair::from_pkcs8(
            &ring::signature::ECDSA_P256_SHA256_FIXED_SIGNING,
            pkcs8.as_ref(),
            &rng,
        )
        .unwrap();
        let pub_bytes = key_pair.public_key().as_ref().to_vec();
        let cose_key = build_cose_ec2_key(&pub_bytes[1..33], &pub_bytes[33..65]);

        let credential_id = vec![0x42u8; 8];
        let auth_data = build_auth_data_with_credential(
            "localhost",
            FLAG_UP | FLAG_AT,
            0,
            &credential_id,
            &cose_key,
        );

        let challenge = generate_challenge_bytes();
        let challenge_b64 = base64_encode_urlsafe(&challenge);

        let mut client_data = serde_json::json!({
            "type": "webauthn.create",
            "challenge": challenge_b64,
            "origin": "http://localhost:8080",
        });
        if rp_id_field {
            client_data["rpId"] = serde_json::json!("localhost");
        }
        let client_data_b64 = base64_encode_urlsafe(&serde_json::to_vec(&client_data).unwrap());

        let mut entries = vec![
            (
                ciborium::Value::Integer(1.into()),
                ciborium::Value::Text("none".to_string()),
            ),
            (
                ciborium::Value::Text("authData".to_string()),
                ciborium::Value::Bytes(auth_data),
            ),
        ];
        if extra_att_key {
            entries.push((
                ciborium::Value::Text("unknownKey".to_string()),
                ciborium::Value::Bool(true),
            ));
        }
        entries.push((
            ciborium::Value::Text("attStmt".to_string()),
            ciborium::Value::Map(vec![]),
        ));
        let mut buf = Vec::new();
        ciborium::ser::into_writer(&ciborium::Value::Map(entries), &mut buf).unwrap();

        (challenge, client_data_b64, base64_encode_urlsafe(&buf))
    }

    /// An explicit `rpId` field matching the RP must be accepted, and
    /// unknown attestation-object keys must be ignored.
    #[test]
    fn registration_accepts_rpid_field_and_unknown_keys() {
        let (challenge, client_data_b64, att_obj_b64) = valid_registration(true, true);
        let result = verify_registration(
            &challenge,
            &client_data_b64,
            &att_obj_b64,
            "",
            "localhost",
            &["http://localhost:8080".to_string()],
            &AttestationPolicy::default(),
            &CredentialPolicy::default(),
        )
        .unwrap();
        assert_eq!(result.attestation_format, "none");
        assert_eq!(result.credential_id, base64_encode_urlsafe(&[0x42u8; 8]));
    }

    #[test]
    fn registration_rejects_missing_type_in_client_data() {
        let challenge = generate_challenge_bytes();
        let client_data = serde_json::json!({
            "challenge": base64_encode_urlsafe(&challenge),
            "origin": "http://localhost:8080",
        });
        let result = verify_registration(
            &challenge,
            &base64_encode_urlsafe(&serde_json::to_vec(&client_data).unwrap()),
            &base64_encode_urlsafe(&[0xFF; 8]),
            "",
            "localhost",
            &["http://localhost:8080".to_string()],
            &AttestationPolicy::default(),
            &CredentialPolicy::default(),
        );
        assert!(matches!(result, Err(WebauthnError::VerificationFailed(_))));
    }

    #[test]
    fn registration_rejects_missing_origin_in_client_data() {
        let challenge = generate_challenge_bytes();
        let client_data = serde_json::json!({
            "type": "webauthn.create",
            "challenge": base64_encode_urlsafe(&challenge),
        });
        let result = verify_registration(
            &challenge,
            &base64_encode_urlsafe(&serde_json::to_vec(&client_data).unwrap()),
            &base64_encode_urlsafe(&[0xFF; 8]),
            "",
            "localhost",
            &["http://localhost:8080".to_string()],
            &AttestationPolicy::default(),
            &CredentialPolicy::default(),
        );
        assert!(matches!(result, Err(WebauthnError::VerificationFailed(_))));
    }

    /// Attested credential data that ends right after the credential ID
    /// (no COSE key bytes) must be rejected as truncated, never sliced
    /// out of bounds.
    #[test]
    fn parse_auth_data_rejects_truncated_public_key() {
        let mut auth_data = vec![0u8; 37 + 16 + 2 + 2];
        auth_data[32] = FLAG_UP | FLAG_AT;
        auth_data[53..55].copy_from_slice(&2u16.to_be_bytes());
        let result = parse_authenticator_data(&auth_data);
        assert!(matches!(result, Err(WebauthnError::VerificationFailed(_))));
    }

    // ---- ES384 / EdDSA ceremonies (REQ-WA-140, REQ-WA-141) ----

    use crate::crypto::tests::{build_cose_ec2_key_alg, build_cose_okp_key};
    use crate::crypto::{COSE_ALG_ES256, COSE_ALG_ES384};

    /// Full ES384 registration roundtrip with a synthetic P-384 keypair.
    #[test]
    fn registration_roundtrip_es384() {
        use ring::signature::{EcdsaKeyPair, KeyPair as _, ECDSA_P384_SHA384_FIXED_SIGNING};

        let rng = ring::rand::SystemRandom::new();
        let pkcs8 = EcdsaKeyPair::generate_pkcs8(&ECDSA_P384_SHA384_FIXED_SIGNING, &rng).unwrap();
        let key_pair =
            EcdsaKeyPair::from_pkcs8(&ECDSA_P384_SHA384_FIXED_SIGNING, pkcs8.as_ref(), &rng)
                .unwrap();
        let pub_bytes = key_pair.public_key().as_ref();
        let cose_key = build_cose_ec2_key_alg(2, -35, &pub_bytes[1..49], &pub_bytes[49..97]);

        let credential_id = vec![0xE3u8; 8];
        let auth_data = build_auth_data_with_credential(
            "localhost",
            FLAG_UP | FLAG_AT | FLAG_UV | FLAG_BE | FLAG_BS,
            0,
            &credential_id,
            &cose_key,
        );
        let att_obj = build_attestation_object(&auth_data);

        let challenge = generate_challenge_bytes();
        let client_data = serde_json::json!({
            "type": "webauthn.create",
            "challenge": base64_encode_urlsafe(&challenge),
            "origin": "http://localhost:8080",
        });
        let result = verify_registration(
            &challenge,
            &base64_encode_urlsafe(&serde_json::to_vec(&client_data).unwrap()),
            &base64_encode_urlsafe(&att_obj),
            "",
            "localhost",
            &["http://localhost:8080".to_string()],
            &AttestationPolicy::default(),
            &CredentialPolicy::default(),
        )
        .unwrap();

        assert!(result.device_name.contains("ES384"));
        assert!(result.user_verified);
        assert!(result.backup_eligible);
        assert!(result.backup_state);
    }

    /// Full EdDSA registration → authentication roundtrip.
    #[test]
    fn registration_authentication_roundtrip_eddsa() {
        use ring::signature::{Ed25519KeyPair, KeyPair as _};

        let rng = ring::rand::SystemRandom::new();
        let pkcs8 = Ed25519KeyPair::generate_pkcs8(&rng).unwrap();
        let key_pair = Ed25519KeyPair::from_pkcs8(pkcs8.as_ref()).unwrap();
        let cose_key = build_cose_okp_key(key_pair.public_key().as_ref());

        // -- registration --
        let credential_id = vec![0xEDu8; 8];
        let auth_data = build_auth_data_with_credential(
            "localhost",
            FLAG_UP | FLAG_AT,
            0,
            &credential_id,
            &cose_key,
        );
        let att_obj = build_attestation_object(&auth_data);
        let challenge = generate_challenge_bytes();
        let client_data = serde_json::json!({
            "type": "webauthn.create",
            "challenge": base64_encode_urlsafe(&challenge),
            "origin": "http://localhost:8080",
        });
        let registration = verify_registration(
            &challenge,
            &base64_encode_urlsafe(&serde_json::to_vec(&client_data).unwrap()),
            &base64_encode_urlsafe(&att_obj),
            "",
            "localhost",
            &["http://localhost:8080".to_string()],
            &AttestationPolicy::default(),
            &CredentialPolicy::default(),
        )
        .unwrap();
        assert!(registration.device_name.contains("EdDSA"));
        assert!(!registration.backup_eligible);

        // -- authentication --
        let auth_challenge = generate_challenge_bytes();
        let assertion_client_data = serde_json::json!({
            "type": "webauthn.get",
            "challenge": base64_encode_urlsafe(&auth_challenge),
            "origin": "http://localhost:8080",
        });
        let assertion_client_data_bytes = serde_json::to_vec(&assertion_client_data).unwrap();
        let rp_id_hash = sha2::Sha256::digest(b"localhost").to_vec();
        let mut assertion_auth_data = rp_id_hash;
        assertion_auth_data.push(FLAG_UP | FLAG_BS);
        assertion_auth_data.extend_from_slice(&1u32.to_be_bytes());

        use sha2::Digest as _;
        let mut signed_data = assertion_auth_data.clone();
        signed_data.extend_from_slice(&sha2::Sha256::digest(&assertion_client_data_bytes));
        let signature = key_pair.sign(&signed_data);

        let cred_b64 = base64_encode_urlsafe(&credential_id);
        let result = verify_authentication(&AuthenticationParams {
            challenge_bytes: auth_challenge,
            client_data_json_b64: base64_encode_urlsafe(&assertion_client_data_bytes),
            authenticator_data_b64: base64_encode_urlsafe(&assertion_auth_data),
            signature_b64: base64_encode_urlsafe(signature.as_ref()),
            credential_id_b64: cred_b64.clone(),
            public_key_cose: cose_key,
            current_sign_count: 0,
            allowed_credential_ids: vec![cred_b64],
            rp_id: "localhost".to_string(),
            rp_origins: vec!["http://localhost:8080".to_string()],
            policy: CredentialPolicy::default(),
        })
        .unwrap();
        assert_eq!(result.new_sign_count, 1);
        assert!(result.backup_state);
        assert!(!result.backup_eligible);
    }

    /// Algorithm-confusion via the ceremony entry point: attested credential
    /// data carrying a P-256 key that claims `alg = -35` (ES384) must be
    /// rejected (the RS256 bug class, replayed against ES384).
    #[test]
    fn registration_rejects_p256_key_claiming_es384() {
        let cose_key = build_cose_ec2_key_alg(1, -35, &[0xAA; 32], &[0xBB; 32]); // crv 1 = P-256
        let auth_data =
            build_auth_data_with_credential("localhost", FLAG_UP | FLAG_AT, 0, &[0x01], &cose_key);
        let att_obj = build_attestation_object(&auth_data);
        let challenge = generate_challenge_bytes();
        let client_data = serde_json::json!({
            "type": "webauthn.create",
            "challenge": base64_encode_urlsafe(&challenge),
            "origin": "http://localhost:8080",
        });
        let result = verify_registration(
            &challenge,
            &base64_encode_urlsafe(&serde_json::to_vec(&client_data).unwrap()),
            &base64_encode_urlsafe(&att_obj),
            "",
            "localhost",
            &["http://localhost:8080".to_string()],
            &AttestationPolicy::default(),
            &CredentialPolicy::default(),
        );
        assert!(matches!(
            result,
            Err(WebauthnError::UnsupportedAlgorithm(COSE_ALG_ES384))
        ));
    }

    // ---- UV enforcement matrix (REQ-WA-142) ----

    /// Build a minimal valid registration for the given flags; returns the
    /// ceremony inputs.
    fn registration_inputs(flags: u8) -> (Vec<u8>, String, String) {
        let cose_key = build_cose_ec2_key(&[0xAA; 32], &[0xBB; 32]);
        let auth_data =
            build_auth_data_with_credential("localhost", flags, 0, &[0x01, 0x02], &cose_key);
        let challenge = generate_challenge_bytes();
        let client_data = serde_json::json!({
            "type": "webauthn.create",
            "challenge": base64_encode_urlsafe(&challenge),
            "origin": "http://localhost:8080",
        });
        (
            challenge,
            base64_encode_urlsafe(&serde_json::to_vec(&client_data).unwrap()),
            base64_encode_urlsafe(&build_attestation_object(&auth_data)),
        )
    }

    #[test]
    fn uv_required_rejects_clear_flag_and_accepts_set() {
        use crate::policy::UserVerificationPolicy;
        let uv_required = CredentialPolicy {
            user_verification: UserVerificationPolicy::Required,
            ..CredentialPolicy::default()
        };

        // Required + UV clear → rejected.
        let (challenge, cd, ao) = registration_inputs(FLAG_UP | FLAG_AT);
        let result = verify_registration(
            &challenge,
            &cd,
            &ao,
            "",
            "localhost",
            &["http://localhost:8080".to_string()],
            &AttestationPolicy::default(),
            &uv_required,
        );
        assert!(matches!(
            result,
            Err(WebauthnError::UserVerificationRequired)
        ));

        // Required + UV set → accepted.
        let (challenge, cd, ao) = registration_inputs(FLAG_UP | FLAG_AT | FLAG_UV);
        let result = verify_registration(
            &challenge,
            &cd,
            &ao,
            "",
            "localhost",
            &["http://localhost:8080".to_string()],
            &AttestationPolicy::default(),
            &uv_required,
        );
        assert!(result.is_ok());
    }

    /// Preferred/Discouraged never reject on UV; the flag is only reported.
    #[test]
    fn uv_preferred_and_discouraged_report_only() {
        use crate::policy::UserVerificationPolicy;
        // UP set, UV clear.
        let (challenge, cd, ao) = registration_inputs(FLAG_UP | FLAG_AT);

        for uv in [
            UserVerificationPolicy::Preferred,
            UserVerificationPolicy::Discouraged,
        ] {
            let policy = CredentialPolicy {
                user_verification: uv,
                ..CredentialPolicy::default()
            };
            let result = verify_registration(
                &challenge,
                &cd,
                &ao,
                "",
                "localhost",
                &["http://localhost:8080".to_string()],
                &AttestationPolicy::default(),
                &policy,
            )
            .unwrap();
            assert!(!result.user_verified, "{uv:?} must report, not reject");
        }
    }

    // ---- algorithm allowlist (REQ-WA-143) ----

    /// A credential whose algorithm is outside the configured allowlist is
    /// rejected at registration, even though the kit could verify it.
    #[test]
    fn registration_rejects_algorithm_outside_allowlist() {
        // P-384/ES384 credential with an ES256-only allowlist.
        use ring::signature::{EcdsaKeyPair, KeyPair as _, ECDSA_P384_SHA384_FIXED_SIGNING};
        let rng = ring::rand::SystemRandom::new();
        let pkcs8 = EcdsaKeyPair::generate_pkcs8(&ECDSA_P384_SHA384_FIXED_SIGNING, &rng).unwrap();
        let key_pair =
            EcdsaKeyPair::from_pkcs8(&ECDSA_P384_SHA384_FIXED_SIGNING, pkcs8.as_ref(), &rng)
                .unwrap();
        let pub_bytes = key_pair.public_key().as_ref();
        let cose_key = build_cose_ec2_key_alg(2, -35, &pub_bytes[1..49], &pub_bytes[49..97]);

        let auth_data =
            build_auth_data_with_credential("localhost", FLAG_UP | FLAG_AT, 0, &[0x01], &cose_key);
        let att_obj = build_attestation_object(&auth_data);
        let challenge = generate_challenge_bytes();
        let client_data = serde_json::json!({
            "type": "webauthn.create",
            "challenge": base64_encode_urlsafe(&challenge),
            "origin": "http://localhost:8080",
        });
        let common = (
            challenge,
            base64_encode_urlsafe(&serde_json::to_vec(&client_data).unwrap()),
            base64_encode_urlsafe(&att_obj),
        );

        // Disallowed: ES384 not on the ES256-only list.
        let es256_only = CredentialPolicy {
            allowed_algorithms: vec![COSE_ALG_ES256],
            ..CredentialPolicy::default()
        };
        let result = verify_registration(
            &common.0,
            &common.1,
            &common.2,
            "",
            "localhost",
            &["http://localhost:8080".to_string()],
            &AttestationPolicy::default(),
            &es256_only,
        );
        assert!(matches!(
            result,
            Err(WebauthnError::UnsupportedAlgorithm(COSE_ALG_ES384))
        ));

        // Allowed once ES384 is listed.
        let with_es384 = CredentialPolicy {
            allowed_algorithms: vec![COSE_ALG_ES256, COSE_ALG_ES384],
            ..CredentialPolicy::default()
        };
        let result = verify_registration(
            &common.0,
            &common.1,
            &common.2,
            "",
            "localhost",
            &["http://localhost:8080".to_string()],
            &AttestationPolicy::default(),
            &with_es384,
        );
        assert!(result.is_ok());

        // Empty allowlist = accept everything supported.
        let result = verify_registration(
            &common.0,
            &common.1,
            &common.2,
            "",
            "localhost",
            &["http://localhost:8080".to_string()],
            &AttestationPolicy::default(),
            &CredentialPolicy::default(),
        );
        assert!(result.is_ok());
    }

    // ---- backup eligibility / backup state policy (REQ-WA-144) ----

    /// `RequireDeviceBound` rejects synced (BE=1) credentials at
    /// registration; device-bound (BE=0) registrations pass.
    #[test]
    fn backup_policy_device_bound_enforced_at_registration() {
        use crate::policy::BackupPolicy;
        let device_bound = CredentialPolicy {
            backup: BackupPolicy::RequireDeviceBound,
            ..CredentialPolicy::default()
        };

        // BE=1 (synced) → rejected.
        let (challenge, cd, ao) = registration_inputs(FLAG_UP | FLAG_AT | FLAG_BE);
        let result = verify_registration(
            &challenge,
            &cd,
            &ao,
            "",
            "localhost",
            &["http://localhost:8080".to_string()],
            &AttestationPolicy::default(),
            &device_bound,
        );
        assert!(matches!(result, Err(WebauthnError::PolicyViolation(_))));

        // BE=0 (device-bound) → accepted; BS reported as-is.
        let (challenge, cd, ao) = registration_inputs(FLAG_UP | FLAG_AT);
        let result = verify_registration(
            &challenge,
            &cd,
            &ao,
            "",
            "localhost",
            &["http://localhost:8080".to_string()],
            &AttestationPolicy::default(),
            &device_bound,
        );
        let registration = result.unwrap();
        assert!(!registration.backup_eligible);
        assert!(!registration.backup_state);
    }

    /// `Allow` (default) accepts synced credentials and reports both flags.
    #[test]
    fn backup_policy_allow_reports_flags() {
        let (challenge, cd, ao) = registration_inputs(FLAG_UP | FLAG_AT | FLAG_BE | FLAG_BS);
        let registration = verify_registration(
            &challenge,
            &cd,
            &ao,
            "",
            "localhost",
            &["http://localhost:8080".to_string()],
            &AttestationPolicy::default(),
            &CredentialPolicy::default(),
        )
        .unwrap();
        assert!(registration.backup_eligible);
        assert!(registration.backup_state);
    }

    /// `RequireDeviceBound` also rejects BE=1 assertions at authentication.
    #[test]
    fn backup_policy_device_bound_enforced_at_authentication() {
        use crate::policy::BackupPolicy;
        use ring::signature::{EcdsaKeyPair, KeyPair as _};

        let rng = ring::rand::SystemRandom::new();
        let pkcs8 =
            EcdsaKeyPair::generate_pkcs8(&ring::signature::ECDSA_P256_SHA256_FIXED_SIGNING, &rng)
                .unwrap();
        let key_pair = EcdsaKeyPair::from_pkcs8(
            &ring::signature::ECDSA_P256_SHA256_FIXED_SIGNING,
            pkcs8.as_ref(),
            &rng,
        )
        .unwrap();
        let pub_bytes = key_pair.public_key().as_ref();
        let cose_key = build_cose_ec2_key(&pub_bytes[1..33], &pub_bytes[33..65]);

        let challenge = generate_challenge_bytes();
        let client_data = serde_json::json!({
            "type": "webauthn.get",
            "challenge": base64_encode_urlsafe(&challenge),
            "origin": "http://localhost:8080",
        });
        let client_data_bytes = serde_json::to_vec(&client_data).unwrap();
        let rp_id_hash = sha2::Sha256::digest(b"localhost").to_vec();
        let mut auth_data = rp_id_hash;
        auth_data.push(FLAG_UP | FLAG_BE); // synced credential assertion
        auth_data.extend_from_slice(&1u32.to_be_bytes());

        use sha2::Digest as _;
        let mut signed_data = auth_data.clone();
        signed_data.extend_from_slice(&sha2::Sha256::digest(&client_data_bytes));
        let signature = key_pair.sign(&rng, &signed_data).unwrap();

        let cred_b64 = base64_encode_urlsafe(&[0x01]);
        let params = AuthenticationParams {
            challenge_bytes: challenge,
            client_data_json_b64: base64_encode_urlsafe(&client_data_bytes),
            authenticator_data_b64: base64_encode_urlsafe(&auth_data),
            signature_b64: base64_encode_urlsafe(signature.as_ref()),
            credential_id_b64: cred_b64.clone(),
            public_key_cose: cose_key,
            current_sign_count: 0,
            allowed_credential_ids: vec![cred_b64],
            rp_id: "localhost".to_string(),
            rp_origins: vec!["http://localhost:8080".to_string()],
            policy: CredentialPolicy {
                backup: BackupPolicy::RequireDeviceBound,
                ..CredentialPolicy::default()
            },
        };
        assert!(matches!(
            verify_authentication(&params),
            Err(WebauthnError::PolicyViolation(_))
        ));
    }

    /// UV Required is enforced at authentication: a validly signed
    /// assertion with a clear UV flag fails with
    /// `UserVerificationRequired`.
    #[test]
    fn uv_required_enforced_at_authentication() {
        use crate::policy::UserVerificationPolicy;
        use ring::signature::{EcdsaKeyPair, KeyPair as _};

        let rng = ring::rand::SystemRandom::new();
        let pkcs8 =
            EcdsaKeyPair::generate_pkcs8(&ring::signature::ECDSA_P256_SHA256_FIXED_SIGNING, &rng)
                .unwrap();
        let key_pair = EcdsaKeyPair::from_pkcs8(
            &ring::signature::ECDSA_P256_SHA256_FIXED_SIGNING,
            pkcs8.as_ref(),
            &rng,
        )
        .unwrap();
        let pub_bytes = key_pair.public_key().as_ref();
        let cose_key = build_cose_ec2_key(&pub_bytes[1..33], &pub_bytes[33..65]);

        let challenge = generate_challenge_bytes();
        let client_data = serde_json::json!({
            "type": "webauthn.get",
            "challenge": base64_encode_urlsafe(&challenge),
            "origin": "http://localhost:8080",
        });
        let client_data_bytes = serde_json::to_vec(&client_data).unwrap();
        let rp_id_hash = sha2::Sha256::digest(b"localhost").to_vec();
        let mut auth_data = rp_id_hash;
        auth_data.push(FLAG_UP); // UV clear
        auth_data.extend_from_slice(&1u32.to_be_bytes());

        use sha2::Digest as _;
        let mut signed_data = auth_data.clone();
        signed_data.extend_from_slice(&sha2::Sha256::digest(&client_data_bytes));
        let signature = key_pair.sign(&rng, &signed_data).unwrap();

        let cred_b64 = base64_encode_urlsafe(&[0x01]);
        let params = AuthenticationParams {
            challenge_bytes: challenge,
            client_data_json_b64: base64_encode_urlsafe(&client_data_bytes),
            authenticator_data_b64: base64_encode_urlsafe(&auth_data),
            signature_b64: base64_encode_urlsafe(signature.as_ref()),
            credential_id_b64: cred_b64.clone(),
            public_key_cose: cose_key,
            current_sign_count: 0,
            allowed_credential_ids: vec![cred_b64],
            rp_id: "localhost".to_string(),
            rp_origins: vec!["http://localhost:8080".to_string()],
            policy: CredentialPolicy {
                user_verification: UserVerificationPolicy::Required,
                ..CredentialPolicy::default()
            },
        };
        assert!(matches!(
            verify_authentication(&params),
            Err(WebauthnError::UserVerificationRequired)
        ));

        // The identical assertion under the default policy is accepted.
        let mut default_params = params.clone();
        default_params.policy = CredentialPolicy::default();
        assert!(verify_authentication(&default_params).is_ok());
    }

    /// A malformed attestation *statement* (packed without `alg`) surfaces
    /// as an `AttestationError` through the registration entry point.
    #[test]
    fn registration_propagates_attestation_statement_errors() {
        let auth_data = build_auth_data_with_credential(
            "localhost",
            FLAG_UP | FLAG_AT,
            0,
            &[0x01],
            &build_cose_ec2_key(&[0xAA; 32], &[0xBB; 32]),
        );
        let entries = vec![
            (
                ciborium::Value::Integer(1.into()),
                ciborium::Value::Text("packed".to_string()),
            ),
            (
                ciborium::Value::Integer(2.into()),
                ciborium::Value::Bytes(auth_data),
            ),
            (
                ciborium::Value::Integer(3.into()),
                ciborium::Value::Map(vec![]), // packed attStmt without alg/sig
            ),
        ];
        let mut buf = Vec::new();
        ciborium::ser::into_writer(&ciborium::Value::Map(entries), &mut buf).unwrap();

        let challenge = generate_challenge_bytes();
        let client_data = serde_json::json!({
            "type": "webauthn.create",
            "challenge": base64_encode_urlsafe(&challenge),
            "origin": "http://localhost:8080",
        });
        let result = verify_registration(
            &challenge,
            &base64_encode_urlsafe(&serde_json::to_vec(&client_data).unwrap()),
            &base64_encode_urlsafe(&buf),
            "",
            "localhost",
            &["http://localhost:8080".to_string()],
            &AttestationPolicy::default(),
            &CredentialPolicy::default(),
        );
        assert!(matches!(result, Err(WebauthnError::AttestationError(_))));
    }

    /// Truncation checks in `parse_authenticator_data` are exact and
    /// stage-specific: a blob at the minimum length passes the prefix
    /// bound and fails at the *next* stage, and a blob below the real
    /// bound (but above any mutated one) is rejected at the prefix stage.
    #[test]
    fn authenticator_data_truncation_boundaries_are_exact() {
        // 37 header + 16 AAGUID + 2 credential-length = 55 bytes: passes
        // the prefix check exactly, then fails at the public-key stage.
        let at_minimum = build_auth_data_with_credential("localhost", FLAG_AT, 0, &[], &[]);
        assert_eq!(at_minimum.len(), 55);
        let err = parse_authenticator_data(&at_minimum)
            .unwrap_err()
            .to_string();
        assert!(
            err.contains("public key"),
            "exact-prefix blob must reach the public-key stage: {err}"
        );

        // 40 bytes with AT: below the real prefix bound (55) but above the
        // header bound (37) — must be rejected at the AAGUID+length stage.
        let mut short = vec![0u8; 32];
        short.push(FLAG_AT);
        short.extend_from_slice(&[0u8; 7]);
        let err = parse_authenticator_data(&short).unwrap_err().to_string();
        assert!(
            err.contains("AAGUID + length"),
            "40-byte AT blob must fail at the prefix stage: {err}"
        );

        // Exact-fit credential ID: 37 + 16 + 2 + 2 = 57 bytes, credential
        // id fully present, public-key stage reached.
        let cred_exact =
            build_auth_data_with_credential("localhost", FLAG_AT, 0, &[0x01, 0x02], &[]);
        assert_eq!(cred_exact.len(), 57);
        let err = parse_authenticator_data(&cred_exact)
            .unwrap_err()
            .to_string();
        assert!(
            err.contains("public key"),
            "exact-fit credential id must reach the public-key stage: {err}"
        );
    }

    /// Registration auth data without the AT flag must be rejected with
    /// the specific attested-credential error — not by a downstream,
    /// looser check. Pins the FLAG_AT gate itself.
    #[test]
    fn registration_without_attested_credential_flag_names_the_missing_flag() {
        let auth_data = build_auth_data_with_credential(
            "localhost",
            FLAG_UP, // no FLAG_AT
            0,
            &[],
            &[],
        );
        let att_obj = build_attestation_object(&auth_data);

        let challenge = generate_challenge_bytes();
        let client_data = serde_json::json!({
            "type": "webauthn.create",
            "challenge": base64_encode_urlsafe(&challenge),
            "origin": "http://localhost:8080",
        });
        let client_data_b64 = base64_encode_urlsafe(&serde_json::to_vec(&client_data).unwrap());

        let result = verify_registration(
            &challenge,
            &client_data_b64,
            &base64_encode_urlsafe(&att_obj),
            "",
            "localhost",
            &["http://localhost:8080".to_string()],
            &AttestationPolicy::default(),
            &CredentialPolicy::default(),
        );
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("Attested Credential Data flag not set"),
            "AT-less registration must be rejected at the flag gate: {err}"
        );
    }
}