oauth2-passkey 0.6.1

OAuth2 and Passkey authentication library for Rust web applications
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
use super::*;
use crate::passkey::CredentialId;
use crate::passkey::main::types::AuthenticatorAttestationResponse;
use crate::storage::{CacheKey, CachePrefix};
use ciborium::value::Value as CborValue;

/// Test parse attestation object success none fmt
///
/// This test verifies that `parse_attestation_object` successfully parses a valid
/// attestation object with "none" format. It tests CBOR decoding and validates that
/// all fields (fmt, authData, attStmt) are correctly extracted from the attestation object.
#[test]
fn test_parse_attestation_object_success_none_fmt() {
    use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};

    // Construct the expected AttestationObject fields
    let expected_fmt = "none".to_string();
    let expected_auth_data = b"authdata".to_vec();
    let expected_att_stmt_map = Vec::<(CborValue, CborValue)>::new(); // Empty map

    // Create the CBOR structure programmatically
    let cbor_map = vec![
        (
            CborValue::Text("fmt".to_string()),
            CborValue::Text(expected_fmt.clone()),
        ),
        (
            CborValue::Text("attStmt".to_string()),
            CborValue::Map(expected_att_stmt_map.clone()),
        ),
        (
            CborValue::Text("authData".to_string()),
            CborValue::Bytes(expected_auth_data.clone()),
        ),
    ];
    let cbor_value = CborValue::Map(cbor_map);

    // Serialize CBOR to bytes
    let mut cbor_bytes = Vec::new();
    ciborium::ser::into_writer(&cbor_value, &mut cbor_bytes).expect("CBOR serialization failed");

    // Encode bytes to base64url string
    let attestation_base64 = URL_SAFE_NO_PAD.encode(&cbor_bytes);

    let result = parse_attestation_object(&attestation_base64);
    assert!(
        result.is_ok(),
        "Parsing failed for input '{}': {:?}",
        attestation_base64,
        result.err()
    );
    let att_obj = result.unwrap();

    assert_eq!(att_obj.fmt, expected_fmt);
    assert_eq!(att_obj.auth_data, expected_auth_data);
    assert_eq!(
        att_obj.att_stmt, expected_att_stmt_map,
        "attStmt should be an empty map"
    );
}

/// Test parse attestation object invalid base64
///
/// This test verifies that `parse_attestation_object` returns appropriate errors when
/// given invalid base64 input that cannot be decoded. It tests the base64 validation
/// and error handling for malformed attestation data.
#[test]
fn test_parse_attestation_object_invalid_base64() {
    let attestation_base64 = "not-valid-base64!@#";

    let result = parse_attestation_object(attestation_base64);
    assert!(result.is_err());
    match result.err().unwrap() {
        PasskeyError::Format(msg) => {
            assert!(msg.contains("Failed to decode attestation object"));
        }
        e => panic!("Expected PasskeyError::Format, got {e:?}"),
    }
}

/// Test parse attestation object valid base64 invalid cbor
///
/// This test verifies that `parse_attestation_object` returns appropriate errors when
/// given valid base64 that contains invalid CBOR data. It tests the CBOR parsing
/// validation and error handling for corrupted attestation objects.
#[test]
fn test_parse_attestation_object_valid_base64_invalid_cbor() {
    use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
    // This is valid base64url for "this is not cbor"
    let attestation_base64 = URL_SAFE_NO_PAD.encode(b"this is not cbor");

    let result = parse_attestation_object(&attestation_base64);
    assert!(result.is_err());
    match result.err().unwrap() {
        PasskeyError::Format(msg) => {
            assert!(
                msg.contains("Invalid CBOR data"),
                "Error message was: {msg}"
            );
        }
        e => panic!("Expected PasskeyError::Format, got {e:?}"),
    }
}

/// Test parse attestation object cbor map missing fmt
///
/// This test verifies that `parse_attestation_object` returns appropriate errors when
/// the CBOR map is missing the required "fmt" field. It tests validation of required
/// attestation object structure and proper error reporting for incomplete data.
#[test]
fn test_parse_attestation_object_cbor_map_missing_fmt() {
    use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};

    // CBOR: { "attStmt": {}, "authData": b"authdata" } (missing "fmt")
    let cbor_map = vec![
        (
            CborValue::Text("attStmt".to_string()),
            CborValue::Map(Vec::new()),
        ),
        (
            CborValue::Text("authData".to_string()),
            CborValue::Bytes(b"authdata".to_vec()),
        ),
    ];
    let cbor_value = CborValue::Map(cbor_map);

    let mut cbor_bytes = Vec::new();
    ciborium::ser::into_writer(&cbor_value, &mut cbor_bytes).unwrap();
    let attestation_base64 = URL_SAFE_NO_PAD.encode(&cbor_bytes);

    let result = parse_attestation_object(&attestation_base64);
    assert!(result.is_err());
    match result.err().unwrap() {
        PasskeyError::Format(msg) => {
            assert_eq!(msg, "Missing required attestation data");
        }
        e => panic!("Expected PasskeyError::Format with specific message, got {e:?}"),
    }
}

/// Test parse attestation object cbor map missing auth data
///
/// This test verifies that `parse_attestation_object` returns appropriate errors when
/// the CBOR map is missing the required "authData" field. It tests validation of
/// required attestation structure and proper error handling for missing authenticator data.
#[test]
fn test_parse_attestation_object_cbor_map_missing_auth_data() {
    use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};

    // CBOR: { "fmt": "none", "attStmt": {} } (missing "authData")
    let cbor_map = vec![
        (
            CborValue::Text("fmt".to_string()),
            CborValue::Text("none".to_string()),
        ),
        (
            CborValue::Text("attStmt".to_string()),
            CborValue::Map(Vec::new()),
        ),
    ];
    let cbor_value = CborValue::Map(cbor_map);

    let mut cbor_bytes = Vec::new();
    ciborium::ser::into_writer(&cbor_value, &mut cbor_bytes).unwrap();
    let attestation_base64 = URL_SAFE_NO_PAD.encode(&cbor_bytes);

    let result = parse_attestation_object(&attestation_base64);
    assert!(result.is_err());
    match result.err().unwrap() {
        PasskeyError::Format(msg) => {
            assert_eq!(msg, "Missing required attestation data");
        }
        e => panic!("Expected PasskeyError::Format with specific message, got {e:?}"),
    }
}

/// Test parse attestation object cbor map missing att stmt
///
/// This test verifies that `parse_attestation_object` returns appropriate errors when
/// the CBOR map is missing the required "attStmt" field. It tests validation of
/// required attestation structure and proper error handling for missing attestation statements.
#[test]
fn test_parse_attestation_object_cbor_map_missing_att_stmt() {
    use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};

    // CBOR: { "fmt": "none", "authData": b"authdata" } (missing "attStmt")
    let cbor_map = vec![
        (
            CborValue::Text("fmt".to_string()),
            CborValue::Text("none".to_string()),
        ),
        (
            CborValue::Text("authData".to_string()),
            CborValue::Bytes(b"authdata".to_vec()),
        ),
    ];
    let cbor_value = CborValue::Map(cbor_map);

    let mut cbor_bytes = Vec::new();
    ciborium::ser::into_writer(&cbor_value, &mut cbor_bytes).unwrap();
    let attestation_base64 = URL_SAFE_NO_PAD.encode(&cbor_bytes);

    let result = parse_attestation_object(&attestation_base64);
    assert!(result.is_err());
    match result.err().unwrap() {
        PasskeyError::Format(msg) => {
            assert_eq!(msg, "Missing required attestation data");
        }
        e => panic!("Expected PasskeyError::Format with specific message, got {e:?}"),
    }
}

/// Test parse attestation object cbor not a map
///
/// This test verifies that `parse_attestation_object` returns appropriate errors when
/// the CBOR data is not a map structure. It tests type validation and ensures that
/// non-map CBOR structures are properly rejected with descriptive error messages.
#[test]
fn test_parse_attestation_object_cbor_not_a_map() {
    use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};

    // Create a CBOR value that is not a map (using an array instead)
    let cbor_value = CborValue::Array(vec![]);

    // Serialize CBOR to bytes
    let mut cbor_bytes = Vec::new();
    ciborium::ser::into_writer(&cbor_value, &mut cbor_bytes).expect("CBOR serialization failed");

    // Encode bytes to base64url string
    let attestation_base64 = URL_SAFE_NO_PAD.encode(&cbor_bytes);

    let result = parse_attestation_object(&attestation_base64);
    assert!(result.is_err());
    match result.err().unwrap() {
        PasskeyError::Format(msg) => {
            assert_eq!(msg, "Invalid attestation format");
        }
        e => panic!("Expected PasskeyError::Format, got {e:?}"),
    }
}

/// Test extract key coordinates success
///
/// This test verifies that `extract_key_coordinates` successfully extracts X and Y
/// coordinates from a valid CBOR key map. It tests the parsing of elliptic curve
/// public key coordinates from CBOR-encoded key data.
#[test]
fn test_extract_key_coordinates_success() {
    use ciborium::value::Integer;

    // Create a CBOR map with valid X and Y coordinates
    // COSE key format uses -2 and -3 for X and Y coordinates
    let x_coord = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]; // 16 bytes for X
    let y_coord = vec![
        17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32,
    ]; // 16 bytes for Y

    let cbor_map = vec![
        (
            CborValue::Integer(Integer::from(-2)), // X coordinate
            CborValue::Bytes(x_coord.clone()),
        ),
        (
            CborValue::Integer(Integer::from(-3)), // Y coordinate
            CborValue::Bytes(y_coord.clone()),
        ),
    ];
    let cbor_value = CborValue::Map(cbor_map);

    let mut cbor_bytes = Vec::new();
    ciborium::ser::into_writer(&cbor_value, &mut cbor_bytes).unwrap();

    let result = extract_key_coordinates(&cbor_bytes);
    assert!(result.is_ok());
    let (extracted_x, extracted_y) = result.unwrap();
    assert_eq!(extracted_x, x_coord);
    assert_eq!(extracted_y, y_coord);
}

/// Test extract key coordinates missing x
///
/// This test verifies that `extract_key_coordinates` returns appropriate errors when
/// the X coordinate is missing from the CBOR key map. It tests validation of required
/// key components and proper error handling for incomplete key data.
#[test]
fn test_extract_key_coordinates_missing_x() {
    // Create a CBOR map with only Y coordinate, missing X
    let y_coord = vec![16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1];

    let cbor_map = vec![(
        CborValue::Integer(Integer::from(-3)), // Y coordinate
        CborValue::Bytes(y_coord.clone()),
    )];

    let cbor_value = CborValue::Map(cbor_map);

    // Serialize CBOR to bytes
    let mut credential_data = Vec::new();
    ciborium::ser::into_writer(&cbor_value, &mut credential_data)
        .expect("CBOR serialization failed");

    // Call the function
    let result = extract_key_coordinates(&credential_data);

    // Verify the result is an error
    assert!(
        result.is_err(),
        "Expected error but got success: {:?}",
        result.ok()
    );

    // Check the error type and message
    match result.err().unwrap() {
        PasskeyError::Format(msg) => {
            assert_eq!(msg, "Missing or invalid key coordinates");
        }
        e => panic!("Expected PasskeyError::Format, got {e:?}"),
    }
}

/// Test extract key coordinates missing y
///
/// This test verifies that `extract_key_coordinates` returns appropriate errors when
/// the Y coordinate is missing from the CBOR key map. It tests validation of required
/// key components and proper error handling for incomplete key data.
#[test]
fn test_extract_key_coordinates_missing_y() {
    // Create a CBOR map with only X coordinate, missing Y
    let x_coord = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];

    let cbor_map = vec![(
        CborValue::Integer(Integer::from(-2)), // X coordinate
        CborValue::Bytes(x_coord.clone()),
    )];

    let cbor_value = CborValue::Map(cbor_map);

    // Serialize CBOR to bytes
    let mut credential_data = Vec::new();
    ciborium::ser::into_writer(&cbor_value, &mut credential_data)
        .expect("CBOR serialization failed");

    // Call the function
    let result = extract_key_coordinates(&credential_data);

    // Verify the result is an error
    assert!(
        result.is_err(),
        "Expected error but got success: {:?}",
        result.ok()
    );

    // Check the error type and message
    match result.err().unwrap() {
        PasskeyError::Format(msg) => {
            assert_eq!(msg, "Missing or invalid key coordinates");
        }
        e => panic!("Expected PasskeyError::Format, got {e:?}"),
    }
}

/// Test parse credential data success
///
/// This test verifies that `parse_credential_data` successfully extracts credential ID
/// and public key data from valid authenticator data. It tests the parsing of credential
/// information embedded in the authenticator data structure.
#[test]
fn test_parse_credential_data_success() {
    // Create a mock authenticator data array
    // Structure:
    // - 32 bytes RP ID hash
    // - 1 byte flags (with attested credential data flag set)
    // - 4 bytes counter
    // - 16 bytes AAGUID
    // - 2 bytes credential ID length
    // - credential ID bytes
    // - credential public key bytes

    // Create a mock auth_data with all required fields
    let mut auth_data = Vec::new();

    // 32 bytes RP ID hash (just zeros for test)
    auth_data.extend_from_slice(&[0u8; 32]);

    // 1 byte flags with attested credential data flag set (0x40 = 01000000)
    auth_data.push(0x40);

    // 4 bytes counter
    auth_data.extend_from_slice(&[0, 0, 0, 0]);

    // 16 bytes AAGUID
    auth_data.extend_from_slice(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]);

    // 2 bytes credential ID length (10 bytes)
    auth_data.extend_from_slice(&[0, 10]);

    // 10 bytes credential ID
    auth_data.extend_from_slice(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);

    // Some mock credential public key bytes
    let public_key_bytes = [20, 21, 22, 23, 24, 25, 26, 27, 28, 29];
    auth_data.extend_from_slice(&public_key_bytes);

    // Call the function
    let result = parse_credential_data(&auth_data);

    // Verify the result
    assert!(result.is_ok(), "Parsing failed: {:?}", result.err());

    // The result should be the credential public key bytes
    let credential_data = result.unwrap();
    assert_eq!(credential_data, &public_key_bytes);
}

/// Test parse credential data too short
///
/// This test verifies that `parse_credential_data` returns appropriate errors when
/// the authenticator data is too short to contain valid credential information.
/// It tests length validation and proper error handling for truncated data.
#[test]
fn test_parse_credential_data_too_short() {
    // Create a mock authenticator data array that's too short
    // Only include RP ID hash and flags, missing the rest
    let mut auth_data = Vec::new();

    // 32 bytes RP ID hash
    auth_data.extend_from_slice(&[0u8; 32]);

    // 1 byte flags with attested credential data flag set
    auth_data.push(0x40);

    // Missing counter, AAGUID, credential ID length, etc.

    // Call the function
    let result = parse_credential_data(&auth_data);

    // Verify the result is an error
    assert!(
        result.is_err(),
        "Expected error but got success: {:?}",
        result.ok()
    );

    // Check the error type and message
    match result.err().unwrap() {
        PasskeyError::Format(msg) => {
            assert_eq!(msg, "Authenticator data too short");
        }
        e => panic!("Expected PasskeyError::Format, got {e:?}"),
    }
}

/// Test parse credential data invalid length
///
/// This test verifies that `parse_credential_data` returns appropriate errors when
/// the credential ID length field contains invalid values. It tests validation of
/// length fields and proper error handling for malformed credential data.
#[test]
fn test_parse_credential_data_invalid_length() {
    // Create a mock authenticator data array with invalid credential ID length
    let mut auth_data = Vec::new();

    // 32 bytes RP ID hash
    auth_data.extend_from_slice(&[0u8; 32]);

    // 1 byte flags (with attested credential data flag set)
    auth_data.push(0x40);

    // 4 bytes counter
    auth_data.extend_from_slice(&[0, 0, 0, 0]);

    // 16 bytes AAGUID
    auth_data.extend_from_slice(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]);

    // 2 bytes credential ID length (set to 0, which is invalid)
    auth_data.extend_from_slice(&[0, 0]);

    // Call the function
    let result = parse_credential_data(&auth_data);

    // Verify the result is an error
    assert!(
        result.is_err(),
        "Expected error but got success: {:?}",
        result.ok()
    );

    // Check the error type and message
    match result.err().unwrap() {
        PasskeyError::Format(msg) => {
            assert_eq!(msg, "Invalid credential ID length");
        }
        e => panic!("Expected PasskeyError::Format, got {e:?}"),
    }
}

/// Test parse credential data too short for credential id
/// This test verifies that parsing fails when authenticator data contains
/// insufficient data for the declared credential ID length.
/// It performs the following steps:
/// 1. Creates mock authenticator data with credential ID length set to 20 bytes
/// 2. Provides only 10 bytes of credential ID data (less than declared)
/// 3. Verifies that parsing returns a "too short for credential ID" error
#[test]
fn test_parse_credential_data_too_short_for_credential_id() {
    // Create a mock authenticator data array that's too short for the credential ID
    let mut auth_data = Vec::new();

    // 32 bytes RP ID hash
    auth_data.extend_from_slice(&[0u8; 32]);

    // 1 byte flags (with attested credential data flag set)
    auth_data.push(0x40);

    // 4 bytes counter
    auth_data.extend_from_slice(&[0, 0, 0, 0]);

    // 16 bytes AAGUID
    auth_data.extend_from_slice(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]);

    // 2 bytes credential ID length (set to 20, but we'll only provide 10 bytes)
    auth_data.extend_from_slice(&[0, 20]);

    // Only 10 bytes for credential ID (less than the 20 we specified)
    auth_data.extend_from_slice(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);

    // Call the function
    let result = parse_credential_data(&auth_data);

    // Verify the result is an error
    assert!(
        result.is_err(),
        "Expected error but got success: {:?}",
        result.ok()
    );

    // Check the error type and message
    match result.err().unwrap() {
        PasskeyError::Format(msg) => {
            assert_eq!(msg, "Authenticator data too short for credential ID");
        }
        e => panic!("Expected PasskeyError::Format, got {e:?}"),
    }
}

/// Test parse credential data large credential id length
/// This test verifies that parsing fails when credential ID length exceeds the maximum allowed size.
/// It performs the following steps:
/// 1. Creates authenticator data with credential ID length set to 1025 bytes (exceeds 1024 limit)
/// 2. Calls parse_credential_data with the oversized credential ID length
/// 3. Verifies that parsing returns an "Invalid credential ID length" error
#[test]
fn test_parse_credential_data_large_credential_id_length() {
    // Create authenticator data with credential ID length > 1024 bytes
    let mut auth_data = Vec::new();

    // RP ID hash (32 bytes)
    auth_data.extend_from_slice(&[0u8; 32]);

    // Flags (1 byte) - set attested credential data flag
    auth_data.push(0x40);

    // Counter (4 bytes)
    auth_data.extend_from_slice(&[0u8; 4]);

    // AAGUID (16 bytes)
    auth_data.extend_from_slice(&[0u8; 16]);

    // Credential ID length (2 bytes) - set to 1025 (exceeds 1024 limit)
    let large_cred_id_len = 1025u16;
    auth_data.push((large_cred_id_len >> 8) as u8);
    auth_data.push((large_cred_id_len & 0xFF) as u8);

    // Add some credential ID data (we don't need all 1025 bytes for this test)
    auth_data.extend_from_slice(&[0xAAu8; 100]);

    let result = parse_credential_data(&auth_data);
    assert!(result.is_err());
    match result.err().unwrap() {
        PasskeyError::Format(msg) => {
            assert_eq!(msg, "Invalid credential ID length");
        }
        e => panic!("Expected PasskeyError::Format with 'Invalid credential ID length', got {e:?}"),
    }
}

/// Test extract key coordinates invalid cbor
/// This test verifies that key coordinate extraction fails when provided with invalid CBOR data.
/// It performs the following steps:
/// 1. Creates malformed data that cannot be parsed as valid CBOR
/// 2. Calls extract_key_coordinates with the invalid CBOR data
/// 3. Verifies that extraction returns an "Invalid public key format" error
#[test]
fn test_extract_key_coordinates_invalid_cbor() {
    // Create malformed CBOR data that cannot be parsed
    let invalid_cbor_data = b"not valid cbor data";

    let result = extract_key_coordinates(invalid_cbor_data);
    assert!(result.is_err());
    match result.err().unwrap() {
        PasskeyError::Format(msg) => {
            assert!(
                msg.contains("Invalid public key format"),
                "Error message was: {msg}"
            );
        }
        e => panic!("Expected PasskeyError::Format with public key format error, got {e:?}"),
    }
}

/// Test create registration options integration
///
/// This test verifies the complete registration options creation process in an integrated
/// environment. It tests the generation of registration challenges, options formatting,
/// and proper integration with cache and session systems.
#[tokio::test]
async fn test_create_registration_options_integration() {
    use crate::passkey::main::test_utils as passkey_test_utils;
    use crate::storage::GENERIC_CACHE_STORE;
    use crate::test_utils::init_test_environment;

    init_test_environment().await;

    // Create user info for registration
    let user_handle = "test_user_handle_456";
    let user_info = crate::passkey::types::PublicKeyCredentialUserEntity {
        user_handle: user_handle.to_string(),
        name: "test_user_456".to_string(),
        display_name: "Test User 456".to_string(),
    };

    // Call the function under test
    let options = super::create_registration_options(user_info.clone(), vec![]).await;
    assert!(options.is_ok(), "Failed to create registration options");

    let registration_options = options.unwrap();

    // Verify that the options contain the expected user information
    assert_eq!(registration_options.user.user_handle, user_handle);
    assert_eq!(registration_options.user.name, "test_user_456");
    assert_eq!(registration_options.user.display_name, "Test User 456");

    // Verify that a challenge was stored in the cache
    let challenge_type = crate::passkey::types::ChallengeType::registration();
    let challenge_id = crate::passkey::types::ChallengeId::new(user_handle.to_string()).unwrap();
    let cache_result = super::get_and_validate_options(&challenge_type, &challenge_id).await;
    assert!(
        cache_result.is_ok(),
        "Challenge was not stored in cache properly"
    );

    // Clean up cache
    let (cache_prefix, cache_key) = (
        CachePrefix::reg_challenge(),
        CacheKey::new(user_handle.to_string()).unwrap(),
    );
    let cleanup_result = passkey_test_utils::remove_from_cache(cache_prefix, cache_key).await;
    assert!(
        cleanup_result.is_ok(),
        "Failed to clean up test data from cache"
    );

    // Verify removal
    let cache_prefix = CachePrefix::new("regi_challenge".to_string()).unwrap();
    let cache_key = CacheKey::new(user_handle.to_string()).unwrap();
    let cache_get = GENERIC_CACHE_STORE
        .lock()
        .await
        .get(cache_prefix, cache_key)
        .await;
    assert!(cache_get.is_ok(), "Error checking cache");
    assert!(
        cache_get.unwrap().is_none(),
        "Cache entry should be removed"
    );
}

/// Test get or create user handle integration
///
/// This test verifies the user handle creation and retrieval functionality for both
/// anonymous and authenticated users. It tests user handle generation for new users
/// and retrieval for existing users in different session states.
#[tokio::test]
async fn test_get_or_create_user_handle() {
    use crate::passkey::main::test_utils as passkey_test_utils;
    use crate::session::User as SessionUser;
    use crate::test_utils::init_test_environment;

    init_test_environment().await;

    // Test with no user (should generate a new handle)
    let no_user_result = super::get_or_create_user_handle(&None).await;
    assert!(
        no_user_result.is_ok(),
        "Failed to create user handle with no user"
    );
    let no_user_handle = no_user_result.unwrap();
    assert!(
        !no_user_handle.is_empty(),
        "User handle should not be empty"
    );

    // Test with logged-in user
    let session_user = Some(SessionUser {
        id: "test_user_id_789".to_string(),
        account: "test_account_789".to_string(),
        label: "Test User 789".to_string(),
        is_admin: false,
        sequence_number: Some(1),
        created_at: chrono::Utc::now(),
        updated_at: chrono::Utc::now(),
    });

    // First call with this user should create a new handle
    let first_handle_result = super::get_or_create_user_handle(&session_user).await;
    assert!(
        first_handle_result.is_ok(),
        "Failed to create user handle for logged-in user"
    );
    let first_handle = first_handle_result.unwrap();

    // Insert a test credential for this user to simulate existing credentials
    let credential_id = "test_cred_id_for_user_handle";
    let credential_data = passkey_test_utils::TestCredentialData::new(
        credential_id,
        "test_user_id_789", // Same as session user ID
        &first_handle,      // Use the generated handle
        "Test User 789",
        "Test Display Name 789",
        "test_public_key",
        "test_aaguid",
        0,
    );
    let result = passkey_test_utils::insert_test_user_and_credential(credential_data).await;
    assert!(result.is_ok(), "Failed to insert test user and credential");

    // Second call with same user might reuse the handle depending on PASSKEY_USER_HANDLE_UNIQUE_FOR_EVERY_CREDENTIAL
    let second_handle_result = super::get_or_create_user_handle(&session_user).await;
    assert!(second_handle_result.is_ok());

    // Clean up
    let cleanup_result = passkey_test_utils::cleanup_test_credential(
        CredentialId::new(credential_id.to_string()).expect("Valid credential ID"),
    )
    .await;
    assert!(cleanup_result.is_ok(), "Failed to clean up test credential");
}

/// Test verify session then finish registration success
/// This test verifies the complete registration flow with valid session and challenge data.
/// It performs the following steps:
/// 1. Sets up test environment with user session and registration challenge
/// 2. Creates test credential data and stores it in the database
/// 3. Calls verify_session_then_finish_registration with valid attestation response
/// 4. Verifies that registration completes successfully with proper cleanup
#[tokio::test]
async fn test_verify_session_then_finish_registration_success() {
    use crate::passkey::main::test_utils as passkey_test_utils;
    use crate::passkey::main::types::AuthenticatorAttestationResponse;
    use crate::passkey::types::{PublicKeyCredentialUserEntity, SessionInfo};
    use crate::session::User as SessionUser;
    use crate::storage::{CacheKey, CachePrefix, get_data, remove_data, store_cache_keyed};
    use crate::test_utils::init_test_environment;

    init_test_environment().await;

    let user_id = "test_user_12345";
    let user_handle = "test_handle_12345";

    // Create session user
    let session_user = SessionUser {
        id: user_id.to_string(),
        account: "test_account".to_string(),
        label: "Test User".to_string(),
        is_admin: false,
        sequence_number: Some(1),
        created_at: chrono::Utc::now(),
        updated_at: chrono::Utc::now(),
    };

    // Store session info in cache
    let session_info = SessionInfo {
        user: session_user.clone(),
    };
    let cache_prefix = CachePrefix::session_info();
    let cache_key = CacheKey::new(user_handle.to_string()).expect("Failed to create cache key");
    let store_result =
        store_cache_keyed::<_, PasskeyError>(cache_prefix, cache_key, session_info, 3600).await;
    assert!(store_result.is_ok(), "Failed to store session info");

    // Create registration challenge in cache
    let user_entity = PublicKeyCredentialUserEntity {
        user_handle: user_handle.to_string(),
        name: "test_user".to_string(),
        display_name: "Test User".to_string(),
    };
    let stored_options = crate::passkey::types::StoredOptions {
        challenge: "test_challenge_12345".to_string(),
        user: user_entity,
        timestamp: std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs(),
        ttl: 3600,
    };
    let cache_prefix = CachePrefix::reg_challenge();
    let cache_key = CacheKey::new(user_handle.to_string()).expect("Failed to create cache key");
    let challenge_store_result =
        store_cache_keyed::<_, PasskeyError>(cache_prefix, cache_key, stored_options, 3600).await;
    assert!(challenge_store_result.is_ok(), "Failed to store challenge");

    // Create test credential for storage
    let credential_id = "test_cred_verify_session_success";
    let credential_data = passkey_test_utils::TestCredentialData::new(
        credential_id,
        user_id,
        user_handle,
        "test_user",
        "Test User",
        "test_public_key",
        "test_aaguid",
        0,
    );
    let user_creation_result =
        passkey_test_utils::insert_test_user_and_credential(credential_data).await;
    assert!(
        user_creation_result.is_ok(),
        "Failed to create test user and credential"
    );

    // Create RegisterCredential with matching client data
    let client_data = super::WebAuthnClientData {
        type_: "webauthn.create".to_string(),
        challenge: "test_challenge_12345".to_string(),
        origin: crate::passkey::config::ORIGIN.to_string(),
    };
    let client_data_json = serde_json::to_string(&client_data).unwrap();
    let client_data_b64 =
        crate::utils::base64url_encode(client_data_json.as_bytes().to_vec()).unwrap();

    // Create mock attestation object with proper structure
    let mut cbor_map = Vec::new();
    cbor_map.push((
        CborValue::Text("fmt".to_string()),
        CborValue::Text("none".to_string()),
    ));
    cbor_map.push((
        CborValue::Text("attStmt".to_string()),
        CborValue::Map(Vec::new()),
    ));

    // Create mock auth data with proper structure for registration
    let mut auth_data = Vec::new();
    // RP ID hash (32 bytes) - must match SHA-256 hash of PASSKEY_RP_ID
    use ring::digest;
    let rp_id_hash = digest::digest(
        &digest::SHA256,
        crate::passkey::config::PASSKEY_RP_ID.as_bytes(),
    );
    auth_data.extend_from_slice(rp_id_hash.as_ref());
    // Flags (1 byte) - user present (0x01) + user verified (0x04) + attested credential data (0x40) = 0x45
    auth_data.push(0x45);
    // Counter (4 bytes)
    auth_data.extend_from_slice(&[0u8; 4]);

    // Attested credential data (required for registration)
    // 16 bytes AAGUID
    auth_data.extend_from_slice(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]);
    // 2 bytes credential ID length
    let cred_id_bytes = credential_id.as_bytes();
    let cred_id_len = cred_id_bytes.len() as u16;
    auth_data.extend_from_slice(&cred_id_len.to_be_bytes());
    // Credential ID bytes
    auth_data.extend_from_slice(cred_id_bytes);
    // Mock public key (COSE format) - simplified ES256 key
    let mock_public_key = vec![
        0xa5, 0x01, 0x02, 0x03, 0x26, 0x20, 0x01, 0x21, 0x58, 0x20, 0x01, 0x02, 0x03, 0x04, 0x05,
        0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14,
        0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x22, 0x58, 0x20,
        0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
        0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e,
        0x3f, 0x40,
    ];
    auth_data.extend_from_slice(&mock_public_key);

    cbor_map.push((
        CborValue::Text("authData".to_string()),
        CborValue::Bytes(auth_data),
    ));

    let cbor_value = CborValue::Map(cbor_map);
    let mut cbor_bytes = Vec::new();
    ciborium::ser::into_writer(&cbor_value, &mut cbor_bytes).unwrap();
    let attestation_object_b64 = crate::utils::base64url_encode(cbor_bytes).unwrap();

    let reg_data = super::RegisterCredential {
        raw_id: credential_id.to_string(),
        id: credential_id.to_string(),
        type_: "public-key".to_string(),
        user_handle: Some(user_handle.to_string()),
        response: AuthenticatorAttestationResponse {
            client_data_json: client_data_b64,
            attestation_object: attestation_object_b64,
        },
    };

    // Test the function
    let result = super::verify_session_then_finish_registration(session_user, reg_data).await;
    assert!(
        result.is_ok(),
        "verify_session_then_finish_registration should succeed: {:?}",
        result.err()
    );

    // Verify session info was removed from cache
    let (cache_prefix, cache_key) = (
        CachePrefix::session_info(),
        CacheKey::new(user_handle.to_string()).unwrap(),
    );
    let session_check = get_data::<SessionInfo, PasskeyError>(cache_prefix, cache_key).await;
    assert!(session_check.is_ok());
    assert!(
        session_check.unwrap().is_none(),
        "Session info should be removed from cache"
    );

    // Cleanup
    let cleanup_result = passkey_test_utils::cleanup_test_credential(
        CredentialId::new(credential_id.to_string()).expect("Valid credential ID"),
    )
    .await;
    assert!(cleanup_result.is_ok(), "Failed to clean up test credential");
    if let Ok(cache_key) = CacheKey::new(user_handle.to_string()) {
        let cache_prefix = CachePrefix::reg_challenge();
        let _ = remove_data::<PasskeyError>(cache_prefix, cache_key).await;
    }
}

/// Test verify session then finish registration missing user handle
/// This test verifies that registration fails when user handle is missing from the request.
/// It performs the following steps:
/// 1. Initializes test environment with session user
/// 2. Creates RegisterCredential with missing user_handle field (set to None)
/// 3. Calls verify_session_then_finish_registration with incomplete data
/// 4. Verifies that it returns a "User handle is missing" error
#[tokio::test]
async fn test_verify_session_then_finish_registration_missing_user_handle() {
    use crate::passkey::main::types::AuthenticatorAttestationResponse;
    use crate::session::User as SessionUser;
    use crate::test_utils::init_test_environment;

    init_test_environment().await;

    let session_user = SessionUser {
        id: "test_user_missing_handle".to_string(),
        account: "test_account".to_string(),
        label: "Test User".to_string(),
        is_admin: false,
        sequence_number: Some(1),
        created_at: chrono::Utc::now(),
        updated_at: chrono::Utc::now(),
    };

    // Create RegisterCredential with missing user_handle
    let reg_data = super::RegisterCredential {
        raw_id: "test_cred_id".to_string(),
        id: "test_cred_id".to_string(),
        type_: "public-key".to_string(),
        user_handle: None, // Missing user handle
        response: AuthenticatorAttestationResponse {
            client_data_json: "dummy".to_string(),
            attestation_object: "dummy".to_string(),
        },
    };

    let result = super::verify_session_then_finish_registration(session_user, reg_data).await;
    assert!(result.is_err(), "Should fail when user handle is missing");

    match result.err().unwrap() {
        PasskeyError::ClientData(msg) => {
            assert_eq!(msg, "User handle is missing");
        }
        e => panic!("Expected PasskeyError::ClientData, got {e:?}"),
    }
}

/// Test verify session then finish registration session not found
/// This test verifies that registration fails when session information is not found in cache.
/// It performs the following steps:
/// 1. Initializes test environment with session user
/// 2. Creates RegisterCredential with valid user handle but no session stored in cache
/// 3. Calls verify_session_then_finish_registration with missing session data
/// 4. Verifies that it returns a "Session not found" error
#[tokio::test]
async fn test_verify_session_then_finish_registration_session_not_found() {
    use crate::passkey::main::types::AuthenticatorAttestationResponse;
    use crate::session::User as SessionUser;
    use crate::test_utils::init_test_environment;

    init_test_environment().await;

    let user_handle = "nonexistent_handle_12345";

    let session_user = SessionUser {
        id: "test_user_no_session".to_string(),
        account: "test_account".to_string(),
        label: "Test User".to_string(),
        is_admin: false,
        sequence_number: Some(1),
        created_at: chrono::Utc::now(),
        updated_at: chrono::Utc::now(),
    };

    // Create RegisterCredential without storing session info in cache
    let reg_data = super::RegisterCredential {
        raw_id: "test_cred_id".to_string(),
        id: "test_cred_id".to_string(),
        type_: "public-key".to_string(),
        user_handle: Some(user_handle.to_string()),
        response: AuthenticatorAttestationResponse {
            client_data_json: "dummy".to_string(),
            attestation_object: "dummy".to_string(),
        },
    };

    let result = super::verify_session_then_finish_registration(session_user, reg_data).await;
    assert!(result.is_err(), "Should fail when session is not found");

    match result.err().unwrap() {
        PasskeyError::NotFound(msg) => {
            assert_eq!(msg, "Session not found");
        }
        e => panic!("Expected PasskeyError::NotFound, got {e:?}"),
    }
}

/// Test verify session then finish registration user id mismatch
/// This test verifies that registration fails when session user ID doesn't match stored session.
/// It performs the following steps:
/// 1. Stores session info in cache with one user ID ("stored_user_id")
/// 2. Attempts registration with different user ID ("current_user_id")
/// 3. Calls verify_session_then_finish_registration with mismatched user data
/// 4. Verifies that it returns a "User ID mismatch" error (prevents session hijacking)
#[tokio::test]
async fn test_verify_session_then_finish_registration_user_id_mismatch() {
    use crate::passkey::main::types::AuthenticatorAttestationResponse;
    use crate::passkey::types::SessionInfo;
    use crate::session::User as SessionUser;
    use crate::storage::{CacheKey, CachePrefix, get_data, store_cache_keyed};
    use crate::test_utils::init_test_environment;

    init_test_environment().await;

    let user_handle = "test_handle_mismatch";

    // Create session user with one ID
    let stored_session_user = SessionUser {
        id: "stored_user_id".to_string(),
        account: "test_account".to_string(),
        label: "Stored User".to_string(),
        is_admin: false,
        sequence_number: Some(1),
        created_at: chrono::Utc::now(),
        updated_at: chrono::Utc::now(),
    };

    // Create different session user with different ID
    let current_session_user = SessionUser {
        id: "current_user_id".to_string(), // Different ID - security breach attempt
        account: "test_account".to_string(),
        label: "Current User".to_string(),
        is_admin: false,
        sequence_number: Some(1),
        created_at: chrono::Utc::now(),
        updated_at: chrono::Utc::now(),
    };

    // Store session info with the first user
    let session_info = SessionInfo {
        user: stored_session_user,
    };
    let cache_prefix = CachePrefix::session_info();
    let cache_key = CacheKey::new(user_handle.to_string()).expect("Failed to create cache key");
    let store_result =
        store_cache_keyed::<_, PasskeyError>(cache_prefix, cache_key, session_info, 3600).await;
    assert!(store_result.is_ok(), "Failed to store session info");

    let reg_data = super::RegisterCredential {
        raw_id: "test_cred_id".to_string(),
        id: "test_cred_id".to_string(),
        type_: "public-key".to_string(),
        user_handle: Some(user_handle.to_string()),
        response: AuthenticatorAttestationResponse {
            client_data_json: "dummy".to_string(),
            attestation_object: "dummy".to_string(),
        },
    };

    // Try to verify with different user - this should fail (security protection)
    let result =
        super::verify_session_then_finish_registration(current_session_user, reg_data).await;
    assert!(
        result.is_err(),
        "Should fail when user IDs don't match - this prevents session hijacking"
    );

    match result.err().unwrap() {
        PasskeyError::Format(msg) => {
            assert_eq!(msg, "User ID mismatch");
        }
        e => panic!("Expected PasskeyError::Format for user ID mismatch, got {e:?}"),
    }

    // Verify session info was still removed from cache (cleanup on security failure)
    let (cache_prefix, cache_key) = (
        CachePrefix::session_info(),
        CacheKey::new(user_handle.to_string()).unwrap(),
    );
    let session_check = get_data::<SessionInfo, PasskeyError>(cache_prefix, cache_key).await;
    assert!(session_check.is_ok());
    assert!(
        session_check.unwrap().is_none(),
        "Session info should be removed even on security failure"
    );
}

// Tests for verify_client_data function

// Helper function to create test RegisterCredential for verify_client_data tests
fn create_test_register_credential_for_verify_client_data(
    client_data_json: String,
    user_handle: Option<String>,
) -> RegisterCredential {
    RegisterCredential {
        raw_id: "test_cred_id".to_string(),
        id: "test_cred_id".to_string(),
        type_: "public-key".to_string(),
        user_handle,
        response: AuthenticatorAttestationResponse {
            client_data_json,
            attestation_object: "test_attestation_object".to_string(),
        },
    }
}

// Helper function to create properly formatted client data JSON
fn create_test_client_data_json(type_: &str, challenge: &str, origin: &str) -> String {
    let client_data = super::WebAuthnClientData {
        type_: type_.to_string(),
        challenge: challenge.to_string(),
        origin: origin.to_string(),
    };
    serde_json::to_string(&client_data).unwrap()
}

/// Test verify client data success
/// This test verifies that client data verification succeeds with valid registration data.
/// It performs the following steps:
/// 1. Stores registration challenge in cache with valid user and challenge data
/// 2. Creates properly formatted client data JSON with matching challenge and origin
/// 3. Calls verify_client_data with valid registration credential
/// 4. Verifies that verification succeeds and cleans up cache data
#[tokio::test]
async fn test_verify_client_data_success() {
    use crate::storage::{CacheKey, CachePrefix, store_cache_keyed};
    use crate::test_utils::init_test_environment;

    init_test_environment().await;

    let user_handle = "test_user_verify_client_data_success";
    let challenge = "test_challenge_verify_success";

    // Store challenge in cache
    let stored_options = StoredOptions {
        challenge: challenge.to_string(),
        user: PublicKeyCredentialUserEntity {
            user_handle: user_handle.to_string(),
            name: "test_user".to_string(),
            display_name: "Test User".to_string(),
        },
        timestamp: std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs(),
        ttl: 3600,
    };

    let cache_prefix = CachePrefix::reg_challenge();
    let cache_key = CacheKey::new(user_handle.to_string()).expect("Failed to create cache key");
    let store_result =
        store_cache_keyed::<_, PasskeyError>(cache_prefix, cache_key, stored_options, 3600).await;
    assert!(store_result.is_ok(), "Failed to store challenge in cache");

    // Create valid client data
    let client_data_json = create_test_client_data_json(
        "webauthn.create",
        challenge,
        &crate::passkey::config::ORIGIN,
    );
    let client_data_b64 =
        crate::utils::base64url_encode(client_data_json.as_bytes().to_vec()).unwrap();

    let reg_data = create_test_register_credential_for_verify_client_data(
        client_data_b64,
        Some(user_handle.to_string()),
    );

    // Test the function
    let result = super::verify_client_data(&reg_data).await;
    assert!(
        result.is_ok(),
        "verify_client_data should succeed with valid data: {:?}",
        result.err()
    );

    // Cleanup
    if let Ok(cache_key) = CacheKey::new(user_handle.to_string()) {
        let cache_prefix = CachePrefix::reg_challenge();
        let _ = remove_data::<PasskeyError>(cache_prefix, cache_key).await;
    }
}

/// Test verify client data invalid base64
/// This test verifies that client data verification fails with invalid base64 encoding.
/// It performs the following steps:
/// 1. Creates RegisterCredential with malformed base64 client data JSON
/// 2. Calls verify_client_data with invalid base64 data
/// 3. Verifies that verification fails with "Failed to decode client data" error
/// 4. Confirms proper error handling for base64 decoding issues
#[tokio::test]
async fn test_verify_client_data_invalid_base64() {
    use crate::test_utils::init_test_environment;

    init_test_environment().await;

    let reg_data = create_test_register_credential_for_verify_client_data(
        "invalid_base64!@#$%".to_string(),
        Some("test_user".to_string()),
    );

    let result = super::verify_client_data(&reg_data).await;
    assert!(result.is_err(), "Should fail with invalid base64");

    match result.err().unwrap() {
        PasskeyError::Format(msg) => {
            assert!(msg.contains("Failed to decode client data"));
        }
        e => panic!("Expected PasskeyError::Format for invalid base64, got {e:?}"),
    }
}

/// Test verify client data invalid utf8
/// This test verifies that client data verification fails with invalid UTF-8 encoding.
/// It performs the following steps:
/// 1. Creates invalid UTF-8 byte sequence (0xFF, 0xFE, 0xFD)
/// 2. Encodes the invalid UTF-8 data as base64 and creates RegisterCredential
/// 3. Calls verify_client_data with non-UTF-8 client data
/// 4. Verifies that verification fails with "Client data is not valid UTF-8" error
#[tokio::test]
async fn test_verify_client_data_invalid_utf8() {
    use crate::test_utils::init_test_environment;

    init_test_environment().await;

    // Create invalid UTF-8 bytes and encode as base64
    let invalid_utf8_bytes = vec![0xFF, 0xFE, 0xFD]; // Invalid UTF-8 sequence
    let invalid_utf8_b64 = crate::utils::base64url_encode(invalid_utf8_bytes).unwrap();

    let reg_data = create_test_register_credential_for_verify_client_data(
        invalid_utf8_b64,
        Some("test_user".to_string()),
    );

    let result = super::verify_client_data(&reg_data).await;
    assert!(result.is_err(), "Should fail with invalid UTF-8");

    match result.err().unwrap() {
        PasskeyError::Format(msg) => {
            assert!(msg.contains("Client data is not valid UTF-8"));
        }
        e => panic!("Expected PasskeyError::Format for invalid UTF-8, got {e:?}"),
    }
}

/// Test verify client data invalid json
/// This test verifies that client data verification fails with malformed JSON.
/// It performs the following steps:
/// 1. Creates invalid JSON structure with malformed syntax
/// 2. Encodes the invalid JSON as base64 and creates RegisterCredential
/// 3. Calls verify_client_data with malformed JSON data
/// 4. Verifies that verification fails with "Failed to parse client data JSON" error
#[tokio::test]
async fn test_verify_client_data_invalid_json() {
    use crate::test_utils::init_test_environment;

    init_test_environment().await;

    // Create invalid JSON
    let invalid_json = "{ invalid json structure }";
    let invalid_json_b64 =
        crate::utils::base64url_encode(invalid_json.as_bytes().to_vec()).unwrap();

    let reg_data = create_test_register_credential_for_verify_client_data(
        invalid_json_b64,
        Some("test_user".to_string()),
    );

    let result = super::verify_client_data(&reg_data).await;
    assert!(result.is_err(), "Should fail with invalid JSON");

    match result.err().unwrap() {
        PasskeyError::Format(msg) => {
            assert!(msg.contains("Failed to parse client data JSON"));
        }
        e => panic!("Expected PasskeyError::Format for invalid JSON, got {e:?}"),
    }
}

/// Test verify client data wrong type
/// This test verifies that client data verification fails with incorrect WebAuthn type.
/// It performs the following steps:
/// 1. Creates client data JSON with "webauthn.get" type (authentication) instead of "webauthn.create" (registration)
/// 2. Encodes the wrong-type client data as base64 and creates RegisterCredential
/// 3. Calls verify_client_data with incorrect ceremony type
/// 4. Verifies that verification fails with appropriate type validation error
#[tokio::test]
async fn test_verify_client_data_wrong_type() {
    use crate::test_utils::init_test_environment;

    init_test_environment().await;

    // Create client data with wrong type (authentication instead of registration)
    let client_data_json = create_test_client_data_json(
        "webauthn.get", // Wrong type - should be "webauthn.create"
        "test_challenge",
        &crate::passkey::config::ORIGIN,
    );
    let client_data_b64 =
        crate::utils::base64url_encode(client_data_json.as_bytes().to_vec()).unwrap();

    let reg_data = create_test_register_credential_for_verify_client_data(
        client_data_b64,
        Some("test_user".to_string()),
    );

    let result = super::verify_client_data(&reg_data).await;
    assert!(result.is_err(), "Should fail with wrong client data type");

    match result.err().unwrap() {
        PasskeyError::ClientData(msg) => {
            assert_eq!(msg, "Invalid type");
        }
        e => panic!("Expected PasskeyError::ClientData for wrong type, got {e:?}"),
    }
}

/// Test verify client data missing user handle
/// This test verifies that client data verification fails when user handle is missing.
/// It performs the following steps:
/// 1. Creates valid client data JSON with proper format and challenge
/// 2. Creates RegisterCredential with user_handle set to None
/// 3. Calls verify_client_data with missing user identification
/// 4. Verifies that verification fails with "User handle is missing" error
#[tokio::test]
async fn test_verify_client_data_missing_user_handle() {
    use crate::test_utils::init_test_environment;

    init_test_environment().await;

    let client_data_json = create_test_client_data_json(
        "webauthn.create",
        "test_challenge",
        &crate::passkey::config::ORIGIN,
    );
    let client_data_b64 =
        crate::utils::base64url_encode(client_data_json.as_bytes().to_vec()).unwrap();

    let reg_data = create_test_register_credential_for_verify_client_data(
        client_data_b64,
        None, // Missing user handle
    );

    let result = super::verify_client_data(&reg_data).await;
    assert!(result.is_err(), "Should fail with missing user handle");

    match result.err().unwrap() {
        PasskeyError::ClientData(msg) => {
            assert!(msg.contains("User handle is missing"));
        }
        e => panic!("Expected PasskeyError::ClientData for missing user handle, got {e:?}"),
    }
}

/// Test verify client data challenge not found
/// This test verifies that client data verification fails when challenge is not found in cache.
/// It performs the following steps:
/// 1. Creates valid client data JSON with challenge but doesn't store it in cache
/// 2. Calls verify_client_data without pre-storing registration challenge
/// 3. Verifies that verification fails with NotFound error
/// 4. Confirms proper handling when challenge lookup fails
#[tokio::test]
async fn test_verify_client_data_challenge_not_found() {
    use crate::test_utils::init_test_environment;

    init_test_environment().await;

    let user_handle = "test_user_challenge_not_found";

    // Don't store any challenge in cache
    let client_data_json = create_test_client_data_json(
        "webauthn.create",
        "test_challenge",
        &crate::passkey::config::ORIGIN,
    );
    let client_data_b64 =
        crate::utils::base64url_encode(client_data_json.as_bytes().to_vec()).unwrap();

    let reg_data = create_test_register_credential_for_verify_client_data(
        client_data_b64,
        Some(user_handle.to_string()),
    );

    let result = super::verify_client_data(&reg_data).await;
    assert!(
        result.is_err(),
        "Should fail when challenge not found in cache"
    );

    // The error comes from get_and_validate_options which should return NotFound
    match result.err().unwrap() {
        PasskeyError::NotFound(_) => {
            // Expected - challenge not found in cache
        }
        e => panic!("Expected PasskeyError::NotFound for missing challenge, got {e:?}"),
    }
}

/// Test verify client data challenge mismatch
/// This test verifies that client data verification fails when challenge doesn't match stored value.
/// It performs the following steps:
/// 1. Stores registration challenge "stored_challenge_123" in cache
/// 2. Creates client data JSON with different challenge "different_challenge_456"
/// 3. Calls verify_client_data with mismatched challenge values
/// 4. Verifies that verification fails with challenge validation error
#[tokio::test]
async fn test_verify_client_data_challenge_mismatch() {
    use crate::storage::{CacheKey, CachePrefix, store_cache_keyed};
    use crate::test_utils::init_test_environment;

    init_test_environment().await;

    let user_handle = "test_user_challenge_mismatch";
    let stored_challenge = "stored_challenge_123";
    let client_challenge = "different_challenge_456";

    // Store one challenge in cache
    let stored_options = StoredOptions {
        challenge: stored_challenge.to_string(),
        user: PublicKeyCredentialUserEntity {
            user_handle: user_handle.to_string(),
            name: "test_user".to_string(),
            display_name: "Test User".to_string(),
        },
        timestamp: std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs(),
        ttl: 3600,
    };

    let cache_prefix = CachePrefix::reg_challenge();
    let cache_key = CacheKey::new(user_handle.to_string()).expect("Failed to create cache key");
    let store_result =
        store_cache_keyed::<_, PasskeyError>(cache_prefix, cache_key, stored_options, 3600).await;
    assert!(store_result.is_ok(), "Failed to store challenge in cache");

    // Create client data with different challenge
    let client_data_json = create_test_client_data_json(
        "webauthn.create",
        client_challenge, // Different from stored challenge
        &crate::passkey::config::ORIGIN,
    );
    let client_data_b64 =
        crate::utils::base64url_encode(client_data_json.as_bytes().to_vec()).unwrap();

    let reg_data = create_test_register_credential_for_verify_client_data(
        client_data_b64,
        Some(user_handle.to_string()),
    );

    let result = super::verify_client_data(&reg_data).await;
    assert!(result.is_err(), "Should fail with challenge mismatch");

    match result.err().unwrap() {
        PasskeyError::Challenge(msg) => {
            assert!(msg.contains("Challenge verification failed"));
        }
        e => panic!("Expected PasskeyError::Challenge for challenge mismatch, got {e:?}"),
    }

    // Cleanup
    if let Ok(cache_key) = CacheKey::new(user_handle.to_string()) {
        let cache_prefix = CachePrefix::reg_challenge();
        let _ = remove_data::<PasskeyError>(cache_prefix, cache_key).await;
    }
}

/// Test verify client data origin mismatch
/// This test verifies that client data verification fails when origin doesn't match configuration.
/// It performs the following steps:
/// 1. Stores valid registration challenge in cache
/// 2. Creates client data JSON with malicious origin "https://evil-site.com"
/// 3. Calls verify_client_data with origin different from configured ORIGIN
/// 4. Verifies that verification fails with "Invalid origin" error (prevents origin spoofing)
#[tokio::test]
async fn test_verify_client_data_origin_mismatch() {
    use crate::storage::{CacheKey, CachePrefix, store_cache_keyed};
    use crate::test_utils::init_test_environment;

    init_test_environment().await;

    let user_handle = "test_user_origin_mismatch";
    let challenge = "test_challenge_origin";

    // Store challenge in cache
    let stored_options = StoredOptions {
        challenge: challenge.to_string(),
        user: PublicKeyCredentialUserEntity {
            user_handle: user_handle.to_string(),
            name: "test_user".to_string(),
            display_name: "Test User".to_string(),
        },
        timestamp: std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs(),
        ttl: 3600,
    };

    let cache_prefix = CachePrefix::reg_challenge();
    let cache_key = CacheKey::new(user_handle.to_string()).expect("Failed to create cache key");
    let store_result =
        store_cache_keyed::<_, PasskeyError>(cache_prefix, cache_key, stored_options, 3600).await;
    assert!(store_result.is_ok(), "Failed to store challenge in cache");

    // Create client data with wrong origin
    let client_data_json = create_test_client_data_json(
        "webauthn.create",
        challenge,
        "https://evil-site.com", // Different from configured ORIGIN
    );
    let client_data_b64 =
        crate::utils::base64url_encode(client_data_json.as_bytes().to_vec()).unwrap();

    let reg_data = create_test_register_credential_for_verify_client_data(
        client_data_b64,
        Some(user_handle.to_string()),
    );

    let result = super::verify_client_data(&reg_data).await;
    assert!(result.is_err(), "Should fail with origin mismatch");

    match result.err().unwrap() {
        PasskeyError::ClientData(msg) => {
            assert!(msg.contains("Invalid origin"));
            assert!(msg.contains("https://evil-site.com"));
        }
        e => panic!("Expected PasskeyError::ClientData for origin mismatch, got {e:?}"),
    }

    // Cleanup
    if let Ok(cache_key) = CacheKey::new(user_handle.to_string()) {
        let cache_prefix = CachePrefix::reg_challenge();
        let _ = remove_data::<PasskeyError>(cache_prefix, cache_key).await;
    }
} // ========================================
// extract_credential_public_key tests
// ========================================

/// Helper function to create a test RegisterCredential for extract_credential_public_key tests
fn create_test_register_credential_for_extract_credential_public_key() -> RegisterCredential {
    let test_origin = crate::test_utils::get_test_origin();
    let client_data_json =
        create_test_client_data_json("webauthn.create", "test-challenge", &test_origin);
    let client_data_b64 =
        crate::utils::base64url_encode(client_data_json.as_bytes().to_vec()).unwrap();

    RegisterCredential {
        id: "test-credential-id".to_string(),
        raw_id: "dGVzdC1jcmVkZW50aWFsLWlk".to_string(),
        type_: "public-key".to_string(),
        user_handle: Some("test-user-handle".to_string()),
        response: AuthenticatorAttestationResponse {
            attestation_object: create_simple_test_attestation_object().unwrap(),
            client_data_json: client_data_b64,
        },
    }
}

/// Helper function to create a simple test attestation object
fn create_simple_test_attestation_object() -> Result<String, String> {
    // Create COSE key for EC2 P-256 public key
    let mut cose_key = Vec::new();
    let mut cbor_map = Vec::new();

    // kty = 2 (EC2)
    cbor_map.push((
        CborValue::Integer(Integer::from(1)),
        CborValue::Integer(Integer::from(2)),
    ));
    // alg = -7 (ES256)
    cbor_map.push((
        CborValue::Integer(Integer::from(3)),
        CborValue::Integer(Integer::from(-7)),
    ));
    // crv = 1 (P-256)
    cbor_map.push((
        CborValue::Integer(Integer::from(-1)),
        CborValue::Integer(Integer::from(1)),
    ));
    // x coordinate (32 bytes)
    let x_coord = vec![
        0x1f, 0x2f, 0x3f, 0x4f, 0x5f, 0x6f, 0x7f, 0x8f, 0x9f, 0xaf, 0xbf, 0xcf, 0xdf, 0xef, 0xff,
        0x0f, 0x1f, 0x2f, 0x3f, 0x4f, 0x5f, 0x6f, 0x7f, 0x8f, 0x9f, 0xaf, 0xbf, 0xcf, 0xdf, 0xef,
        0xff, 0x0f,
    ];
    cbor_map.push((
        CborValue::Integer(Integer::from(-2)),
        CborValue::Bytes(x_coord),
    ));
    // y coordinate (32 bytes)
    let y_coord = vec![
        0x0f, 0xff, 0xef, 0xdf, 0xcf, 0xbf, 0xaf, 0x9f, 0x8f, 0x7f, 0x6f, 0x5f, 0x4f, 0x3f, 0x2f,
        0x1f, 0x0f, 0xff, 0xef, 0xdf, 0xcf, 0xbf, 0xaf, 0x9f, 0x8f, 0x7f, 0x6f, 0x5f, 0x4f, 0x3f,
        0x2f, 0x1f,
    ];
    cbor_map.push((
        CborValue::Integer(Integer::from(-3)),
        CborValue::Bytes(y_coord),
    ));

    let cose_key_cbor = CborValue::Map(cbor_map);
    ciborium::ser::into_writer(&cose_key_cbor, &mut cose_key)
        .map_err(|e| format!("Failed to serialize COSE key: {e}"))?;

    // Create credential ID (16 bytes)
    let credential_id = vec![
        0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
        0x10,
    ];

    // Build authenticator data
    let mut auth_data = Vec::new();

    // RP ID hash (32 bytes) - use SHA256 of the actual RP ID from test environment
    use ring::digest;
    let rp_id_hash = digest::digest(
        &digest::SHA256,
        crate::passkey::config::PASSKEY_RP_ID.as_bytes(),
    );
    auth_data.extend_from_slice(rp_id_hash.as_ref());

    // Flags (1 byte) - 0x45 = user present + user verified + attested credential data
    auth_data.push(0x45);

    // Counter (4 bytes)
    auth_data.extend_from_slice(&[0x00, 0x00, 0x00, 0x00]);

    // AAGUID (16 bytes)
    auth_data.extend_from_slice(&[
        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        0x00,
    ]);

    // Credential ID length (2 bytes, big-endian)
    let cred_id_len = credential_id.len() as u16;
    auth_data.push((cred_id_len >> 8) as u8);
    auth_data.push((cred_id_len & 0xff) as u8);

    // Credential ID
    auth_data.extend_from_slice(&credential_id);

    // Public key (COSE key)
    auth_data.extend_from_slice(&cose_key);

    // Create the full attestation object
    let attestation_cbor = vec![
        0xa3, // map with 3 pairs
        0x63, 0x66, 0x6d, 0x74, // "fmt"
        0x64, 0x6e, 0x6f, 0x6e, 0x65, // "none"
        0x67, 0x61, 0x74, 0x74, 0x53, 0x74, 0x6d, 0x74, // "attStmt"
        0xa0, // empty map
        0x68, 0x61, 0x75, 0x74, 0x68, 0x44, 0x61, 0x74, 0x61, // "authData"
    ];

    let mut full_attestation = attestation_cbor;
    // Add byte string length for auth_data
    if auth_data.len() < 24 {
        // For lengths 0-23, encode length directly in the major type byte
        full_attestation.push(0x40 + auth_data.len() as u8);
    } else if auth_data.len() < 256 {
        // For lengths 24-255, use 0x58 followed by 1-byte length
        full_attestation.push(0x58);
        full_attestation.push(auth_data.len() as u8);
    } else {
        // For lengths 256-65535, use 0x59 followed by 2-byte length
        full_attestation.push(0x59);
        full_attestation.push((auth_data.len() >> 8) as u8);
        full_attestation.push((auth_data.len() & 0xff) as u8);
    }
    full_attestation.extend_from_slice(&auth_data);

    crate::utils::base64url_encode(full_attestation).map_err(|e| e.to_string())
}

/// Test extract credential public key success
/// This test verifies that public key extraction succeeds with valid registration data.
/// It performs the following steps:
/// 1. Creates valid RegisterCredential with properly formatted attestation object
/// 2. Calls extract_credential_public_key with valid credential data
/// 3. Verifies that extraction succeeds and returns non-empty public key
/// 4. Confirms proper parsing of credential and public key data
#[tokio::test]
async fn test_extract_credential_public_key_success() {
    // Initialize test environment properly
    crate::test_utils::init_test_environment().await;

    let reg_data = create_test_register_credential_for_extract_credential_public_key();

    // Test the function (it's not async)
    let result = extract_credential_public_key(&reg_data);

    // Debug: Print the error if it failed
    match &result {
        Ok(key) => println!("Success: got public key of length {}", key.len()),
        Err(e) => println!("Error: {e}"),
    }

    // Should succeed and return a public key string
    assert!(result.is_ok());
    let public_key = result.unwrap();
    assert!(!public_key.is_empty());
}

/// Test extract credential public key invalid client data
/// This test verifies that public key extraction fails with invalid client data encoding.
/// It performs the following steps:
/// 1. Creates RegisterCredential with malformed base64 client data JSON
/// 2. Calls extract_credential_public_key with invalid client data encoding
/// 3. Verifies that extraction fails with "Failed to decode client data" error
/// 4. Confirms proper error handling for base64 decoding issues
#[test]
fn test_extract_credential_public_key_invalid_client_data() {
    let mut reg_data = create_test_register_credential_for_extract_credential_public_key();
    reg_data.response.client_data_json = "invalid-base64!@#".to_string();

    let result = extract_credential_public_key(&reg_data);

    assert!(result.is_err());
    assert!(
        result
            .unwrap_err()
            .to_string()
            .contains("Failed to decode client data")
    );
}

/// Test extract credential public key with invalid attestation object encoding
///
/// This test verifies that `extract_credential_public_key` properly handles invalid
/// base64 encoding in the attestation object. It tests error handling when the
/// attestation object contains malformed base64 data that cannot be decoded.
#[test]
fn test_extract_credential_public_key_invalid_attestation_object() {
    let mut reg_data = create_test_register_credential_for_extract_credential_public_key();
    reg_data.response.attestation_object = "invalid-base64!@#".to_string();

    let result = extract_credential_public_key(&reg_data);

    assert!(result.is_err());
    assert!(
        result
            .unwrap_err()
            .to_string()
            .contains("Failed to decode attestation object")
    );
}

/// Test extract credential public key with malformed CBOR data
///
/// This test verifies that `extract_credential_public_key` properly handles invalid
/// CBOR content in the attestation object. It tests error handling when the
/// attestation object contains valid base64 but invalid CBOR data structures.
#[test]
fn test_extract_credential_public_key_malformed_attestation_object() {
    let mut reg_data = create_test_register_credential_for_extract_credential_public_key();
    // Use valid base64 but invalid CBOR content
    reg_data.response.attestation_object = base64url_encode(b"not-valid-cbor".to_vec()).unwrap();

    let result = extract_credential_public_key(&reg_data);

    assert!(result.is_err());
    assert!(
        result
            .unwrap_err()
            .to_string()
            .contains("Invalid CBOR data")
    );
}

/// Test that multiple credentials with the same AAGUID coexist without deletion
///
/// This test verifies that `prepare_registration_storage` does NOT delete existing
/// credentials when a new credential has the same AAGUID. Previously, AAGUID-based
/// deletion would incorrectly remove credentials from same-type authenticators
/// (e.g., two Google Password Manager accounts).
#[tokio::test]
async fn test_multiple_same_aaguid_credentials_coexist() {
    use crate::passkey::main::test_utils as passkey_test_utils;
    use crate::passkey::types::CredentialSearchField;
    use crate::session::UserId;
    use crate::test_utils::init_test_environment;

    init_test_environment().await;

    let shared_aaguid = "ea9b8d66-4d01-1d21-3ce4-b6b48cb575d4";
    let user_id_str = "test_user_aaguid_coexist";
    let user_handle = "test_handle_aaguid_coexist";

    // Insert first credential with shared AAGUID
    let cred1_data = passkey_test_utils::TestCredentialData::new(
        "cred_aaguid_coexist_1",
        user_id_str,
        user_handle,
        "User AAGUID Test",
        "User AAGUID Test Display",
        "test_public_key_1",
        shared_aaguid,
        0,
    );
    passkey_test_utils::insert_test_user_and_credential(cred1_data)
        .await
        .expect("Failed to insert first credential");

    // Insert second credential with same AAGUID (different credential ID)
    let cred2_data = passkey_test_utils::TestCredentialData::new(
        "cred_aaguid_coexist_2",
        user_id_str,
        user_handle,
        "User AAGUID Test",
        "User AAGUID Test Display",
        "test_public_key_2",
        shared_aaguid,
        0,
    );
    passkey_test_utils::insert_test_credential(cred2_data)
        .await
        .expect("Failed to insert second credential");

    // Prepare a third credential with the same AAGUID via prepare_registration_storage
    let validated_data = super::ValidatedRegistrationData {
        public_key: "test_public_key_3".to_string(),
        user_handle: user_handle.to_string(),
        stored_user: crate::passkey::types::PublicKeyCredentialUserEntity {
            user_handle: user_handle.to_string(),
            name: "User AAGUID Test".to_string(),
            display_name: "User AAGUID Test Display".to_string(),
        },
        credential_id: "cred_aaguid_coexist_3".to_string(),
        aaguid: shared_aaguid.to_string(),
        rp_id: "localhost".to_string(),
    };

    let user_id = UserId::new(user_id_str.to_string()).expect("Valid user ID");
    let new_credential = super::prepare_registration_storage(user_id.clone(), validated_data)
        .await
        .expect("prepare_registration_storage should succeed");

    // Verify the new credential was created correctly
    assert_eq!(new_credential.credential_id, "cred_aaguid_coexist_3");
    assert_eq!(new_credential.aaguid, shared_aaguid);
    assert_eq!(new_credential.user_id, user_id_str);

    // Verify both original credentials still exist (no AAGUID-based deletion)
    let all_creds =
        PasskeyStore::get_credentials_by(CredentialSearchField::UserId(user_id.clone()))
            .await
            .expect("Failed to get credentials");

    let cred1_exists = all_creds
        .iter()
        .any(|c| c.credential_id == "cred_aaguid_coexist_1");
    let cred2_exists = all_creds
        .iter()
        .any(|c| c.credential_id == "cred_aaguid_coexist_2");

    assert!(
        cred1_exists,
        "First credential should still exist (not deleted by AAGUID match)"
    );
    assert!(
        cred2_exists,
        "Second credential should still exist (not deleted by AAGUID match)"
    );

    // Cleanup
    for cred_id in ["cred_aaguid_coexist_1", "cred_aaguid_coexist_2"] {
        let _ = passkey_test_utils::cleanup_test_credential(
            CredentialId::new(cred_id.to_string()).expect("Valid credential ID"),
        )
        .await;
    }
}

/// Test that start_registration populates excludeCredentials for logged-in users
///
/// When a logged-in user starts registration, the returned RegistrationOptions should
/// include all of their existing credential IDs in the excludeCredentials field.
/// This tells the authenticator to reject re-registration of credentials it already holds.
#[tokio::test]
async fn test_start_registration_populates_exclude_credentials() {
    use crate::passkey::main::test_utils as passkey_test_utils;
    use crate::session::User as SessionUser;
    use crate::test_utils::init_test_environment;

    init_test_environment().await;

    let user_id_str = "test_user_exclude_creds";
    let user_handle = "test_handle_exclude_creds";

    // Insert user with two credentials (different AAGUIDs)
    let cred1_data = passkey_test_utils::TestCredentialData::new(
        "cred_exclude_test_1",
        user_id_str,
        user_handle,
        "Exclude Creds User",
        "Exclude Creds Display",
        "test_pk_ec1",
        "aaguid-google-pm",
        0,
    );
    passkey_test_utils::insert_test_user_and_credential(cred1_data)
        .await
        .expect("Failed to insert first credential");

    let cred2_data = passkey_test_utils::TestCredentialData::new(
        "cred_exclude_test_2",
        user_id_str,
        user_handle,
        "Exclude Creds User",
        "Exclude Creds Display",
        "test_pk_ec2",
        "aaguid-yubikey-5c",
        0,
    );
    passkey_test_utils::insert_test_credential(cred2_data)
        .await
        .expect("Failed to insert second credential");

    // Call start_registration with a logged-in session user
    let session_user = Some(SessionUser {
        id: user_id_str.to_string(),
        account: "exclude_creds_account".to_string(),
        label: "Exclude Creds User".to_string(),
        is_admin: false,
        sequence_number: Some(99),
        created_at: chrono::Utc::now(),
        updated_at: chrono::Utc::now(),
    });

    let options = super::start_registration(
        session_user,
        "exclude_creds_user".to_string(),
        "Exclude Creds Display".to_string(),
    )
    .await
    .expect("start_registration should succeed");

    // Verify excludeCredentials contains both credential IDs
    let exclude_ids: Vec<&str> = options
        .exclude_credentials
        .iter()
        .map(|ec| ec.id.as_str())
        .collect();

    assert!(
        exclude_ids.contains(&"cred_exclude_test_1"),
        "excludeCredentials should contain first credential ID, got: {:?}",
        exclude_ids
    );
    assert!(
        exclude_ids.contains(&"cred_exclude_test_2"),
        "excludeCredentials should contain second credential ID, got: {:?}",
        exclude_ids
    );

    // Verify all entries have type "public-key"
    for ec in &options.exclude_credentials {
        assert_eq!(
            ec.type_, "public-key",
            "excludeCredentials type should be 'public-key'"
        );
    }

    // Cleanup credentials and challenge cache
    for cred_id in ["cred_exclude_test_1", "cred_exclude_test_2"] {
        let _ = passkey_test_utils::cleanup_test_credential(
            CredentialId::new(cred_id.to_string()).expect("Valid credential ID"),
        )
        .await;
    }

    // Cleanup registration challenge from cache
    let cache_prefix = CachePrefix::reg_challenge();
    let cache_key = CacheKey::new(options.user.user_handle.clone()).unwrap();
    let _ = passkey_test_utils::remove_from_cache(cache_prefix, cache_key).await;

    // Cleanup session info from cache
    let cache_prefix = CachePrefix::session_info();
    let cache_key = CacheKey::new(options.user.user_handle).unwrap();
    let _ = passkey_test_utils::remove_from_cache(cache_prefix, cache_key).await;
}

/// Test that start_registration returns empty excludeCredentials for anonymous users
///
/// When no user is logged in (session_user is None), excludeCredentials should be empty
/// because there are no existing credentials to exclude.
#[tokio::test]
async fn test_start_registration_anonymous_has_empty_exclude_credentials() {
    use crate::test_utils::init_test_environment;

    init_test_environment().await;

    let options =
        super::start_registration(None, "anon_user".to_string(), "Anonymous User".to_string())
            .await
            .expect("start_registration should succeed for anonymous user");

    assert!(
        options.exclude_credentials.is_empty(),
        "excludeCredentials should be empty for anonymous users, got: {:?}",
        options.exclude_credentials
    );

    // Cleanup registration challenge from cache
    let cache_prefix = CachePrefix::reg_challenge();
    let cache_key = CacheKey::new(options.user.user_handle).unwrap();
    let _ = crate::passkey::main::test_utils::remove_from_cache(cache_prefix, cache_key).await;
}