webauthn-kit 0.2.2

Standalone WebAuthn/FIDO2 passkey verification kit: CTAP2 authenticator data parsing, COSE ES256/RS256 signature verification via ring, 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
//! 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, cbor_map_entries,
    parse_cose_key, verify_cose_signature,
};
use crate::error::WebauthnError;

/// 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/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]>,
}

/// 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: 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,
    })
}

/// 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; the UV flag is reported (not
///   required) so the caller can enforce its own user-verification policy.
/// - 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
///
/// 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,
) -> 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}"))
        })?;

    let attestation_entries = cbor_map_entries(&attestation_val).ok_or_else(|| {
        WebauthnError::AttestationError("attestation object is not a CBOR map".to_string())
    })?;

    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 {
        match *key {
            1 => {
                if let ciborium::Value::Text(s) = val {
                    fmt = Some(s.clone());
                }
            }
            2 => {
                if let Some(b) = cbor_bytes(val) {
                    auth_data_bytes = Some(b);
                }
            }
            3 => {
                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(),
        ));
    }

    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)?;

    // 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,
    })
}

/// 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>,
}

/// 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.
/// 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.
/// - The UV flag is reported, not required; enforce your own policy on
///   [`AuthenticationResult::user_verified`].
///
/// # 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
///
/// 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,
    } = 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(),
        ));
    }

    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,
    })
}

// 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;
        let map = vec![
            (Value::Integer(1.into()), Value::Text("none".to_string())),
            (Value::Integer(2.into()), Value::Bytes(auth_data.to_vec())),
            (Value::Integer(3.into()), Value::Map(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(),
        )
        .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(),
        );
        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(),
        );
        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(),
        );
        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(),
        );
        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(),
        );
        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(),
        );
        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(),
        );
        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()],
        })
        .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()],
        });
        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()],
        });
        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()],
        });
        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()],
        });
        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()],
        });
        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()],
        });
        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()],
        });
        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()],
        });
        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()],
        });
        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::Integer(2.into()),
                ciborium::Value::Bytes(auth_data),
            ),
        ];
        if extra_att_key {
            entries.push((
                ciborium::Value::Integer(9.into()),
                ciborium::Value::Bool(true),
            ));
        }
        entries.push((
            ciborium::Value::Integer(3.into()),
            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(),
        )
        .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(),
        );
        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(),
        );
        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(_))));
    }

    /// 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(),
        );
        assert!(matches!(result, Err(WebauthnError::AttestationError(_))));
    }
}