auth-framework 0.5.0-rc19

A comprehensive, production-ready authentication and authorization framework for Rust 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
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
//! Enhanced X.509 Certificate Signing Module
//!
//! This module provides comprehensive X.509 certificate signing capabilities
//! for enterprise authentication scenarios including:
//!
//! # Features
//!
//! - **Certificate Authority (CA) Operations**: Root and intermediate CA management
//! - **Certificate Signing Requests (CSR)**: Generate and sign CSRs
//! - **Certificate Lifecycle**: Create, renew, revoke, and validate certificates
//! - **Multiple Key Types**: RSA, ECDSA, and Ed25519 support
//! - **Certificate Profiles**: Different certificate types for various use cases
//! - **CRL and OCSP**: Certificate revocation mechanisms
//! - **Enterprise Integration**: LDAP, Active Directory, and PKI integration
//!
//! # Use Cases
//!
//! - Client certificate authentication (OAuth 2.0 mTLS)
//! - Code signing certificates
//! - TLS/SSL server certificates
//! - Email signing and encryption certificates
//! - Document signing certificates
//! - IoT device certificates

use crate::errors::{AuthError, Result};
use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64_STANDARD};
use chrono::{DateTime, Duration, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;
use std::sync::Arc;
use std::time::SystemTime;
use tokio::sync::RwLock;
use uuid::Uuid;
use x509_parser::parse_x509_certificate;

/// Enhanced X.509 Certificate Manager
#[derive(Debug, Clone)]
pub struct X509CertificateManager {
    /// Configuration
    config: X509Config,

    /// Certificate store
    certificate_store: Arc<RwLock<HashMap<String, StoredCertificate>>>,

    /// Certificate revocation list
    revocation_list: Arc<RwLock<HashMap<String, RevocationEntry>>>,

    /// CA certificates
    ca_certificates: Arc<RwLock<HashMap<String, CACertificate>>>,
}

/// X.509 Configuration
#[derive(Debug, Clone)]
pub struct X509Config {
    /// Default certificate validity period (days)
    pub default_validity_days: i64,

    /// Root CA certificate path
    pub root_ca_cert_path: String,

    /// Root CA certificate path (alias)
    pub root_ca_path: String,

    /// Root CA private key path
    pub root_ca_key_path: String,

    /// Intermediate CA certificate path
    pub intermediate_ca_cert_path: Option<String>,

    /// Intermediate CA certificate path (alias)
    pub intermediate_ca_path: Option<String>,

    /// Intermediate CA private key path
    pub intermediate_ca_key_path: Option<String>,

    /// Default key size for RSA
    pub default_rsa_key_size: u32,

    /// Default curve for ECDSA
    pub default_ecdsa_curve: EcdsaCurve,

    /// Certificate profiles
    pub certificate_profiles: HashMap<String, CertificateProfile>,

    /// Enable OCSP (Online Certificate Status Protocol)
    pub enable_ocsp: bool,

    /// OCSP responder URL
    pub ocsp_responder_url: Option<String>,

    /// Enable CRL (Certificate Revocation List)
    pub enable_crl: bool,

    /// CRL distribution point URL
    pub crl_distribution_url: Option<String>,
}

/// ECDSA Curve types
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum EcdsaCurve {
    /// P-256 (secp256r1)
    P256,
    /// P-384 (secp384r1)
    P384,
    /// P-521 (secp521r1)
    P521,
}

/// Certificate Profile for different use cases
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CertificateProfile {
    /// Profile name
    pub name: String,

    /// Certificate type
    pub cert_type: CertificateType,

    /// Key usage flags
    pub key_usage: Vec<KeyUsage>,

    /// Extended key usage
    pub extended_key_usage: Vec<ExtendedKeyUsage>,

    /// Subject alternative names
    pub subject_alt_names: Vec<SubjectAltName>,

    /// Validity period (days)
    pub validity_days: i64,

    /// Key type preference
    pub preferred_key_type: KeyType,

    /// Additional extensions
    pub extensions: HashMap<String, Value>,
}

/// Certificate Types
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum CertificateType {
    /// Root Certificate Authority
    RootCA,
    /// Intermediate Certificate Authority
    IntermediateCA,
    /// End entity certificate (leaf)
    EndEntity,
    /// Code signing certificate
    CodeSigning,
    /// Email certificate
    Email,
    /// TLS server certificate
    TlsServer,
    /// TLS client certificate
    TlsClient,
    /// Document signing certificate
    DocumentSigning,
}

/// Key Usage flags
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum KeyUsage {
    /// Digital signature
    DigitalSignature,
    /// Non-repudiation
    NonRepudiation,
    /// Key encipherment
    KeyEncipherment,
    /// Data encipherment
    DataEncipherment,
    /// Key agreement
    KeyAgreement,
    /// Key certificate signing
    KeyCertSign,
    /// CRL signing
    CrlSign,
    /// Encipher only
    EncipherOnly,
    /// Decipher only
    DecipherOnly,
}

/// Extended Key Usage
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ExtendedKeyUsage {
    /// Server authentication
    ServerAuth,
    /// Client authentication
    ClientAuth,
    /// Code signing
    CodeSigning,
    /// Email protection
    EmailProtection,
    /// Time stamping
    TimeStamping,
    /// OCSP signing
    OcspSigning,
}

/// Subject Alternative Name types
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum SubjectAltName {
    /// DNS name
    DnsName(String),
    /// Email address
    Email(String),
    /// URI
    Uri(String),
    /// IP address
    IpAddress(String),
}

/// Key Types
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum KeyType {
    /// RSA key
    Rsa(u32), // Key size in bits
    /// ECDSA key
    Ecdsa(EcdsaCurve),
    /// Ed25519 key
    Ed25519,
}

/// Stored Certificate
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StoredCertificate {
    /// Certificate ID
    pub cert_id: String,

    /// Certificate data (PEM format)
    pub certificate_pem: String,

    /// Private key (PEM format, optional)
    pub private_key_pem: Option<String>,

    /// Certificate subject
    pub subject: String,

    /// Certificate issuer
    pub issuer: String,

    /// Serial number
    pub serial_number: String,

    /// Not before date
    pub not_before: DateTime<Utc>,

    /// Not after date
    pub not_after: DateTime<Utc>,

    /// Certificate profile used
    pub profile: String,

    /// Certificate status
    pub status: CertificateStatus,

    /// Fingerprint (SHA-256)
    pub fingerprint: String,

    /// Created timestamp
    pub created_at: DateTime<Utc>,

    /// Metadata
    pub metadata: HashMap<String, Value>,
}

/// Certificate Status
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum CertificateStatus {
    /// Certificate is valid
    Valid,
    /// Certificate is expired
    Expired,
    /// Certificate is revoked
    Revoked,
    /// Certificate is suspended
    Suspended,
}

/// CA Certificate
#[derive(Debug, Clone)]
pub struct CACertificate {
    /// CA ID
    pub ca_id: String,

    /// CA certificate
    pub certificate: StoredCertificate,

    /// Certificate subject
    pub subject: String,

    /// CA private key
    pub private_key: Vec<u8>,

    /// CA type
    pub ca_type: CAType,

    /// Issued certificates count
    pub issued_count: u64,

    /// Next certificate serial number
    pub next_serial: u64,
}

/// CA Types
#[derive(Debug, Clone, PartialEq)]
pub enum CAType {
    /// Root CA
    Root,
    /// Intermediate CA
    Intermediate,
}

/// Certificate Revocation Entry
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RevocationEntry {
    /// Certificate serial number
    pub serial_number: String,

    /// Revocation date
    pub revocation_date: DateTime<Utc>,

    /// Revocation reason
    pub reason: RevocationReason,

    /// Additional information
    pub additional_info: Option<String>,
}

/// Revocation Reasons (RFC 5280)
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum RevocationReason {
    /// Unspecified
    Unspecified,
    /// Key compromise
    KeyCompromise,
    /// CA compromise
    CaCompromise,
    /// Affiliation changed
    AffiliationChanged,
    /// Superseded
    Superseded,
    /// Cessation of operation
    CessationOfOperation,
    /// Certificate hold
    CertificateHold,
    /// Remove from CRL
    RemoveFromCrl,
    /// Privilege withdrawn
    PrivilegeWithdrawn,
    /// AA compromise
    AaCompromise,
}

/// Certificate Signing Request
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CertificateRequest {
    /// Request ID
    pub request_id: String,

    /// Certificate subject information
    pub subject: CertificateSubject,

    /// Certificate profile to use
    pub profile: String,

    /// Public key (PEM format)
    pub public_key_pem: String,

    /// Subject alternative names
    pub subject_alt_names: Vec<SubjectAltName>,

    /// Request timestamp
    pub requested_at: DateTime<Utc>,

    /// Requester information
    pub requester: String,

    /// Additional attributes
    pub attributes: HashMap<String, Value>,
}

/// Certificate Subject Information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CertificateSubject {
    /// Common name
    pub common_name: String,

    /// Organization
    pub organization: Option<String>,

    /// Organizational unit
    pub organizational_unit: Option<String>,

    /// Country
    pub country: Option<String>,

    /// State/Province
    pub state: Option<String>,

    /// City/Locality
    pub locality: Option<String>,

    /// Email address
    pub email: Option<String>,
}

impl X509CertificateManager {
    /// Create new X.509 certificate manager
    pub fn new(config: X509Config) -> Self {
        Self {
            config,
            certificate_store: Arc::new(RwLock::new(HashMap::new())),
            revocation_list: Arc::new(RwLock::new(HashMap::new())),
            ca_certificates: Arc::new(RwLock::new(HashMap::new())),
        }
    }

    /// Initialize certificate manager with CA certificates
    pub async fn initialize(&self) -> Result<()> {
        // Load root CA certificate
        self.load_root_ca().await?;

        // Load intermediate CA certificate if configured
        if self.config.intermediate_ca_cert_path.is_some() {
            self.load_intermediate_ca().await?;
        }

        Ok(())
    }

    /// Load root CA certificate
    async fn load_root_ca(&self) -> Result<()> {
        // Production implementation: Load from secure certificate store or HSM
        // Check for HSM configuration first
        #[cfg(feature = "hsm")]
        if let Ok(hsm_config) = std::env::var("X509_HSM_CONFIG") {
            tracing::info!("Loading CA certificate from HSM: {}", hsm_config);
            // In production, integrate with PKCS#11 or Azure Key Vault
            return self.load_ca_from_hsm(&hsm_config).await;
        }
        #[cfg(not(feature = "hsm"))]
        if std::env::var("X509_HSM_CONFIG").is_ok() {
            tracing::warn!(
                "X509_HSM_CONFIG is set but the 'hsm' feature is not enabled — ignoring"
            );
        }

        // Check for Azure Key Vault configuration
        if let Ok(vault_url) = std::env::var("X509_AZURE_VAULT_URL")
            && let Ok(cert_name) = std::env::var("X509_AZURE_CERT_NAME")
        {
            tracing::info!("Loading CA certificate from Azure Key Vault: {}", vault_url);
            return self.load_ca_from_azure_vault(&vault_url, &cert_name).await;
        }

        // Check for AWS Secrets Manager configuration
        if let Ok(secret_id) = std::env::var("X509_AWS_SECRET_ID") {
            tracing::info!(
                "Loading CA certificate from AWS Secrets Manager: {}",
                secret_id
            );
            return self.load_ca_from_aws_secrets(&secret_id).await;
        }

        // Fallback to file system loading with proper security validation
        let ca_cert_path = if self.config.root_ca_path.is_empty() {
            "ca/root-ca.pem"
        } else {
            &self.config.root_ca_path
        };

        tracing::warn!(
            "Loading CA certificate from file system - consider using HSM or secure vault for production"
        );
        self.load_ca_from_file(ca_cert_path).await
    }

    /// Load CA certificate from HSM (Hardware Security Module) via PKCS#11.
    ///
    /// `hsm_config` must be a JSON object with the following fields:
    /// - `library` (required): absolute path to the PKCS#11 shared library (`.so` / `.dll`)
    /// - `slot` (optional, default `0`): slot index returned by `get_slots_with_initialized_token`
    /// - `pin` (optional): User PIN for login (omit for login-less tokens)
    /// - `label` (optional, default `"ca-cert"`): CKA_LABEL of the certificate object
    ///
    /// # Example config
    /// ```text
    /// {"library":"/usr/lib/softhsm/libsofthsm2.so","slot":0,"pin":"1234","label":"root-ca"}
    /// ```
    #[cfg(feature = "hsm")]
    async fn load_ca_from_hsm(&self, hsm_config: &str) -> Result<()> {
        let config: serde_json::Value = serde_json::from_str(hsm_config)
            .map_err(|e| AuthError::config(format!("Invalid HSM JSON config: {}", e)))?;

        let library = config["library"]
            .as_str()
            .ok_or_else(|| AuthError::config("HSM config missing 'library' path".to_string()))?;

        // Extract optional parameters
        let slot_id = config["slot"].as_u64().unwrap_or(0);
        let pin = config["pin"].as_str().map(|s| s.to_string());
        let _label = config["label"].as_str().unwrap_or("root-ca").to_string();

        // Note: Real PKCS#11 operations are synchronous and may block.
        // We use spawn_blocking to prevent blocking the async runtime.
        let library_path = library.to_string();

        let handle = tokio::task::spawn_blocking(move || -> Result<Vec<u8>> {
            // First, initialize the PKCS#11 context
            let pkcs11 = cryptoki::context::Pkcs11::new(&library_path)
                .map_err(|e| AuthError::config(format!("Failed to load PKCS#11 library: {}", e)))?;

            pkcs11
                .initialize(cryptoki::context::CInitializeArgs::new(
                    cryptoki::context::CInitializeFlags::OS_LOCKING_OK,
                ))
                .map_err(|e| {
                    AuthError::config(format!("Failed to initialize PKCS#11 context: {}", e))
                })?;

            // Get slots
            let slots = pkcs11
                .get_slots_with_token()
                .map_err(|e| AuthError::config(format!("Failed to get PKCS#11 slots: {}", e)))?;

            if slot_id as usize >= slots.len() {
                return Err(AuthError::config(format!(
                    "HSM slot {} not found or has no token",
                    slot_id
                )));
            }
            let slot = slots[slot_id as usize];

            // Open a session
            let session = pkcs11
                .open_ro_session(slot)
                .map_err(|e| AuthError::config(format!("Failed to open PKCS#11 session: {}", e)))?;

            // Login if PIN is provided
            if let Some(p) = pin {
                let auth_pin = cryptoki::types::AuthPin::new(p.into());
                session
                    .login(cryptoki::session::UserType::User, Some(&auth_pin))
                    .map_err(|e| AuthError::config(format!("HSM login failed: {}", e)))?;
            }

            // Find the certificate object by label
            let mut search_template: Vec<cryptoki::object::Attribute> = Vec::new();
            search_template.push(cryptoki::object::Attribute::Class(
                cryptoki::object::ObjectClass::CERTIFICATE,
            ));
            search_template.push(cryptoki::object::Attribute::Label(
                _label.clone().into_bytes(),
            ));

            let objects = session.find_objects(&search_template).map_err(|e| {
                AuthError::config(format!("Failed to search PKCS#11 objects: {}", e))
            })?;

            if objects.is_empty() {
                return Err(AuthError::config(format!(
                    "Certificate with label '{}' not found in HSM",
                    _label
                )));
            }

            // Read the certificate value (usually CKA_VALUE for X.509 certs)
            let cert_obj = objects[0];
            let attrs = session
                .get_attributes(cert_obj, &[cryptoki::object::AttributeType::Value])
                .map_err(|e| {
                    AuthError::config(format!("Failed to get certificate value from HSM: {}", e))
                })?;

            if attrs.is_empty() {
                return Err(AuthError::config(
                    "Certificate object has no value attribute".to_string(),
                ));
            }

            let value = match &attrs[0] {
                cryptoki::object::Attribute::Value(v) => v.clone(),
                _ => {
                    return Err(AuthError::config(
                        "Invalid value attribute type".to_string(),
                    ));
                }
            };

            Ok(value)
        });

        let cert_der = handle
            .await
            .map_err(|_| AuthError::config("HSM task panicked".to_string()))??;

        // Convert the DER certificate bytes to PEM format and store via the
        // shared helper that all external CA integrations use.
        let cert_pem = format!(
            "-----BEGIN CERTIFICATE-----\n{}\n-----END CERTIFICATE-----",
            BASE64_STANDARD.encode(&cert_der)
        );

        self.store_ca_certificate_from_pem(&cert_pem, &format!("hsm:slot{}", slot_id))
            .await
    }

    async fn load_ca_from_azure_vault(&self, vault_url: &str, cert_name: &str) -> Result<()> {
        let tenant_id = std::env::var("X509_AZURE_TENANT_ID").map_err(|_| {
            AuthError::config(
                "X509_AZURE_TENANT_ID environment variable required for Azure Key Vault authentication"
                    .to_string(),
            )
        })?;
        let client_id = std::env::var("X509_AZURE_CLIENT_ID").map_err(|_| {
            AuthError::config(
                "X509_AZURE_CLIENT_ID environment variable required for Azure Key Vault authentication"
                    .to_string(),
            )
        })?;
        let client_secret = std::env::var("X509_AZURE_CLIENT_SECRET").map_err(|_| {
            AuthError::config(
                "X509_AZURE_CLIENT_SECRET environment variable required for Azure Key Vault authentication"
                    .to_string(),
            )
        })?;

        let http = reqwest::Client::new();

        // Step 1: Client-credentials flow → access token.
        let token_url = format!(
            "https://login.microsoftonline.com/{}/oauth2/v2.0/token",
            tenant_id
        );
        let token_resp = http
            .post(&token_url)
            .form(&[
                ("grant_type", "client_credentials"),
                ("client_id", client_id.as_str()),
                ("client_secret", client_secret.as_str()),
                ("scope", "https://vault.azure.net/.default"),
            ])
            .send()
            .await
            .map_err(|e| AuthError::internal(format!("Azure AD token request failed: {}", e)))?;

        if !token_resp.status().is_success() {
            let status = token_resp.status();
            let body = token_resp.text().await.unwrap_or_default();
            return Err(AuthError::config(format!(
                "Azure AD token request returned {}: {}",
                status, body
            )));
        }

        let token_json: serde_json::Value = token_resp.json().await.map_err(|e| {
            AuthError::internal(format!("Failed to parse Azure AD token response: {}", e))
        })?;
        let access_token = token_json["access_token"]
            .as_str()
            .ok_or_else(|| AuthError::internal("Azure AD response missing 'access_token'"))?
            .to_string();

        // Step 2: Fetch the secret from Key Vault (returns PEM / PKCS#12 bundle).
        let vault_base = vault_url.trim_end_matches('/');
        let secret_url = format!("{}/secrets/{}?api-version=7.4", vault_base, cert_name);
        let cert_resp = http
            .get(&secret_url)
            .header("Authorization", format!("Bearer {}", access_token))
            .send()
            .await
            .map_err(|e| AuthError::internal(format!("Azure Key Vault request failed: {}", e)))?;

        if !cert_resp.status().is_success() {
            let status = cert_resp.status();
            let body = cert_resp.text().await.unwrap_or_default();
            return Err(AuthError::config(format!(
                "Azure Key Vault secret fetch returned {}: {}",
                status, body
            )));
        }

        let cert_json: serde_json::Value = cert_resp.json().await.map_err(|e| {
            AuthError::internal(format!("Failed to parse Azure Key Vault response: {}", e))
        })?;

        let raw_value = cert_json["value"]
            .as_str()
            .ok_or_else(|| AuthError::internal("Azure Key Vault response missing 'value' field"))?
            .to_string();

        let content_type = cert_json["contentType"]
            .as_str()
            .unwrap_or("application/x-pem-file");

        let cert_pem = if content_type == "application/x-pem-file"
            || raw_value.contains("-----BEGIN")
        {
            // PEM bundle — extract only the leaf/CA certificate block.
            x509_extract_certificate_pem(&raw_value)
        } else {
            return Err(AuthError::config(format!(
                "Azure Key Vault certificate '{}' uses content-type '{}'. \
                 Store the certificate as a PEM secret (application/x-pem-file) for automatic import.",
                cert_name, content_type
            )));
        };

        tracing::info!(
            "Successfully loaded CA certificate from Azure Key Vault: {}/{}",
            vault_base,
            cert_name
        );
        self.store_ca_certificate_from_pem(
            &cert_pem,
            &format!("azure_kv:{}/{}", vault_base, cert_name),
        )
        .await
    }

    /// Load CA certificate from AWS Secrets Manager using AWS SigV4 request signing.
    ///
    /// Required environment variables (standard AWS credential chain):
    /// - `AWS_ACCESS_KEY_ID`
    /// - `AWS_SECRET_ACCESS_KEY`
    /// - `AWS_REGION` or `AWS_DEFAULT_REGION`
    /// - `AWS_SESSION_TOKEN` (optional, for temporary credentials)
    ///
    /// The secret value must be a PEM-encoded certificate (or a PEM bundle; the
    /// first `CERTIFICATE` block is extracted automatically).
    async fn load_ca_from_aws_secrets(&self, secret_id: &str) -> Result<()> {
        let access_key = std::env::var("AWS_ACCESS_KEY_ID").map_err(|_| {
            AuthError::config(
                "AWS_ACCESS_KEY_ID environment variable required for Secrets Manager".to_string(),
            )
        })?;
        let secret_key = std::env::var("AWS_SECRET_ACCESS_KEY").map_err(|_| {
            AuthError::config(
                "AWS_SECRET_ACCESS_KEY environment variable required for Secrets Manager"
                    .to_string(),
            )
        })?;
        let region = std::env::var("AWS_REGION")
            .or_else(|_| std::env::var("AWS_DEFAULT_REGION"))
            .map_err(|_| {
                AuthError::config(
                    "AWS_REGION (or AWS_DEFAULT_REGION) environment variable required for Secrets Manager"
                        .to_string(),
                )
            })?;
        let session_token = std::env::var("AWS_SESSION_TOKEN").ok();

        let service = "secretsmanager";
        let host = format!("{}.{}.amazonaws.com", service, region);
        let payload =
            serde_json::to_vec(&serde_json::json!({ "SecretId": secret_id })).map_err(|e| {
                AuthError::internal(format!(
                    "Failed to serialise Secrets Manager GetSecretValue request: {}",
                    e
                ))
            })?;

        let now = chrono::Utc::now();
        let amz_date = now.format("%Y%m%dT%H%M%SZ").to_string();
        let date_stamp = now.format("%Y%m%d").to_string();

        let authorization = AwsSigV4Request::new(&access_key, &secret_key)
            .session_token(session_token.as_deref())
            .region(&region)
            .service(service)
            .method("POST")
            .host(&host)
            .payload(&payload)
            .amz_date(&amz_date)
            .date_stamp(&date_stamp)
            .amz_target("secretsmanager.GetSecretValue")
            .sign();

        let url = format!("https://{}/", host);
        let http = reqwest::Client::new();
        let mut req_builder = http
            .post(&url)
            .header("Content-Type", "application/x-amz-json-1.1")
            .header("X-Amz-Target", "secretsmanager.GetSecretValue")
            .header("X-Amz-Date", &amz_date)
            .header("Authorization", &authorization)
            .body(payload);

        if let Some(ref token) = session_token {
            req_builder = req_builder.header("X-Amz-Security-Token", token.as_str());
        }

        let resp = req_builder.send().await.map_err(|e| {
            AuthError::internal(format!("AWS Secrets Manager request failed: {}", e))
        })?;

        if !resp.status().is_success() {
            let status = resp.status();
            let body = resp.text().await.unwrap_or_default();
            return Err(AuthError::config(format!(
                "AWS Secrets Manager GetSecretValue returned {}: {}",
                status, body
            )));
        }

        let json: serde_json::Value = resp.json().await.map_err(|e| {
            AuthError::internal(format!("Failed to parse Secrets Manager response: {}", e))
        })?;

        let raw_value = if let Some(s) = json["SecretString"].as_str() {
            s.to_string()
        } else if let Some(b64) = json["SecretBinary"].as_str() {
            let bytes = BASE64_STANDARD.decode(b64).map_err(|e| {
                AuthError::internal(format!("Failed to decode SecretBinary: {}", e))
            })?;
            String::from_utf8(bytes).map_err(|e| {
                AuthError::internal(format!("SecretBinary is not valid UTF-8: {}", e))
            })?
        } else {
            return Err(AuthError::config(format!(
                "AWS Secrets Manager secret '{}' contains neither SecretString nor SecretBinary",
                secret_id
            )));
        };

        let cert_pem = if raw_value.contains("-----BEGIN CERTIFICATE-----") {
            x509_extract_certificate_pem(&raw_value)
        } else {
            raw_value
        };

        tracing::info!(
            "Successfully loaded CA certificate from AWS Secrets Manager: {}",
            secret_id
        );
        self.store_ca_certificate_from_pem(&cert_pem, &format!("aws_secrets:{}", secret_id))
            .await
    }

    /// Load CA certificate from file system (with security validation)
    async fn load_ca_from_file(&self, ca_cert_path: &str) -> Result<()> {
        let (certificate_pem, subject, issuer, serial_number) = if std::path::Path::new(
            ca_cert_path,
        )
        .exists()
        {
            // Load from file (production path)
            let cert_content = tokio::fs::read_to_string(ca_cert_path).await.map_err(|e| {
                AuthError::internal(format!("Failed to read CA certificate: {}", e))
            })?;

            // NOTE: Full X.509 DER parsing requires a dedicated crate (e.g.
            // x509-parser). Without one we derive identifiers from the file path
            // so that different CA files produce distinguishable metadata.
            let path = std::path::Path::new(ca_cert_path);
            let subject = format!(
                "CN=Loaded from {}",
                path.file_name()
                    .map(|n| n.to_string_lossy())
                    .unwrap_or_else(|| path.to_string_lossy())
            );
            let issuer = subject.clone(); // Assumed self-signed root
            let serial_number = format!(
                "{:x}",
                // Derive a deterministic serial from the PEM content hash.
                cert_content
                    .bytes()
                    .fold(0u64, |acc, b| acc.wrapping_mul(31).wrapping_add(b as u64))
            );

            (cert_content, subject, issuer, serial_number)
        } else {
            // Generate self-signed root CA for development/testing
            tracing::warn!(
                "Root CA certificate not found at {}, generating self-signed root CA for development",
                ca_cert_path
            );

            // In production, this should be replaced with proper root CA management
            let (root_cert, root_key) = self.generate_self_signed_root_ca().await?;
            let subject = "CN=AuthFramework Dev Root CA,O=Auth Framework,C=US".to_string();

            // Store the generated root CA for future use
            if let Err(e) = tokio::fs::write(&ca_cert_path, &root_cert).await {
                tracing::warn!("Failed to save generated root CA: {}", e);
            }

            // Store the root key for signing operations
            let ca_dir = std::path::Path::new(&self.config.root_ca_cert_path)
                .parent()
                .map(|p| p.to_string_lossy().to_string())
                .unwrap_or_else(|| ".".to_string());
            let ca_key_path = format!("{}/ca.key", ca_dir);
            if let Err(e) = tokio::fs::write(&ca_key_path, &root_key).await {
                tracing::warn!("Failed to save generated root CA key: {}", e);
            }

            (root_cert, subject.clone(), subject, "1".to_string())
        };

        let ca_cert = StoredCertificate {
            cert_id: "root_ca".to_string(),
            certificate_pem: certificate_pem.clone(),
            private_key_pem: None, // Never store CA private key in memory for security
            subject: subject.clone(),
            issuer,
            serial_number,
            not_before: Utc::now() - Duration::days(365),
            not_after: Utc::now() + Duration::days(365 * 10), // 10 years
            profile: "root_ca".to_string(),
            status: CertificateStatus::Valid,
            fingerprint: self.calculate_certificate_fingerprint(&certificate_pem)?,
            created_at: Utc::now(),
            metadata: HashMap::new(),
        };

        let ca = CACertificate {
            ca_id: "root_ca".to_string(),
            certificate: ca_cert,
            subject: subject.clone(),
            private_key: vec![], // Load from secure storage
            ca_type: CAType::Root,
            issued_count: 0,
            next_serial: 1000, // Start from 1000
        };

        let mut cas = self.ca_certificates.write().await;
        cas.insert("root_ca".to_string(), ca);

        Ok(())
    }

    /// Load intermediate CA certificate
    async fn load_intermediate_ca(&self) -> Result<()> {
        // Load actual intermediate CA certificate for hierarchical PKI
        let intermediate_ca_path = self
            .config
            .intermediate_ca_path
            .as_deref()
            .unwrap_or("ca/intermediate-ca.pem");

        if std::path::Path::new(intermediate_ca_path).exists() {
            let cert_content = tokio::fs::read_to_string(intermediate_ca_path)
                .await
                .map_err(|e| {
                    AuthError::internal(format!("Failed to read intermediate CA: {}", e))
                })?;

            let intermediate_cert = StoredCertificate {
                cert_id: "intermediate_ca".to_string(),
                certificate_pem: cert_content.clone(),
                private_key_pem: None,
                subject: "CN=AuthFramework Intermediate CA, O=AuthFramework, C=US".to_string(),
                issuer: "CN=AuthFramework Root CA, O=AuthFramework, C=US".to_string(),
                serial_number: "2".to_string(),
                not_before: Utc::now() - Duration::days(30),
                not_after: Utc::now() + Duration::days(365 * 5), // 5 years
                profile: "intermediate_ca".to_string(),
                status: CertificateStatus::Valid,
                fingerprint: self.calculate_fingerprint(&cert_content).await?,
                created_at: Utc::now(),
                metadata: HashMap::new(),
            };

            let intermediate_ca = CACertificate {
                ca_id: "intermediate_ca".to_string(),
                certificate: intermediate_cert,
                subject: "CN=AuthFramework Intermediate CA".to_string(), // Parse from actual cert in production
                private_key: vec![],                                     // Load from secure storage
                ca_type: CAType::Intermediate,
                issued_count: 0,
                next_serial: 1,
            };

            let mut cas = self.ca_certificates.write().await;
            cas.insert("intermediate_ca".to_string(), intermediate_ca);

            tracing::info!("Loaded intermediate CA certificate");
        } else {
            tracing::info!("No intermediate CA certificate found, using root CA only");
        }

        Ok(())
    }

    /// Sign certificate request
    pub async fn sign_certificate_request(
        &self,
        request: &CertificateRequest,
        ca_id: &str,
    ) -> Result<StoredCertificate> {
        // Get CA certificate
        let ca = {
            let cas = self.ca_certificates.read().await;
            cas.get(ca_id)
                .ok_or_else(|| AuthError::InvalidRequest(format!("CA not found: {}", ca_id)))?
                .clone()
        };

        // Get certificate profile
        let profile = self
            .config
            .certificate_profiles
            .get(&request.profile)
            .ok_or_else(|| {
                AuthError::InvalidRequest(format!(
                    "Certificate profile not found: {}",
                    request.profile
                ))
            })?;

        // Generate certificate
        let cert_id = Uuid::new_v4().to_string();
        let serial_number = self.get_next_serial_number(ca_id).await?;

        let certificate = StoredCertificate {
            cert_id: cert_id.clone(),
            certificate_pem: self
                .generate_certificate_pem(request, profile, &serial_number)
                .await?,
            private_key_pem: None, // Certificate doesn't include private key
            subject: format!("CN={}", request.subject.common_name),
            issuer: ca.certificate.subject.clone(),
            serial_number: serial_number.clone(),
            not_before: Utc::now(),
            not_after: Utc::now() + Duration::days(profile.validity_days),
            profile: request.profile.clone(),
            status: CertificateStatus::Valid,
            fingerprint: self.calculate_fingerprint(&request.public_key_pem).await?,
            created_at: Utc::now(),
            metadata: HashMap::new(),
        };

        // Store certificate
        let mut store = self.certificate_store.write().await;
        store.insert(cert_id.clone(), certificate.clone());

        // Update CA issued count
        self.increment_ca_issued_count(ca_id).await?;

        Ok(certificate)
    }

    /// Generate certificate PEM using rcgen
    ///
    /// Creates a real X.509 certificate from the given request and profile,
    /// signed by the root CA loaded during initialization.
    async fn generate_certificate_pem(
        &self,
        request: &CertificateRequest,
        profile: &CertificateProfile,
        serial_number: &str,
    ) -> Result<String> {
        use rcgen::{
            BasicConstraints, CertificateParams, DnType, ExtendedKeyUsagePurpose, IsCa,
            KeyUsagePurpose, SanType, SerialNumber,
        };

        let mut params = CertificateParams::default();

        // Set distinguished name
        params
            .distinguished_name
            .push(DnType::CommonName, &request.subject.common_name);
        if let Some(ref org) = request.subject.organization {
            params
                .distinguished_name
                .push(DnType::OrganizationName, org);
        }
        if let Some(ref ou) = request.subject.organizational_unit {
            params
                .distinguished_name
                .push(DnType::OrganizationalUnitName, ou);
        }
        if let Some(ref country) = request.subject.country {
            params.distinguished_name.push(DnType::CountryName, country);
        }
        if let Some(ref state) = request.subject.state {
            params
                .distinguished_name
                .push(DnType::StateOrProvinceName, state);
        }
        if let Some(ref locality) = request.subject.locality {
            params
                .distinguished_name
                .push(DnType::LocalityName, locality);
        }

        // Set serial number
        let serial_num: u64 = serial_number.parse().unwrap_or(1);
        params.serial_number = Some(SerialNumber::from(serial_num.to_be_bytes().to_vec()));

        // Set validity period
        params.not_before = time::OffsetDateTime::now_utc();
        params.not_after =
            time::OffsetDateTime::now_utc() + time::Duration::days(profile.validity_days);

        // Set key usages
        params.key_usages = profile
            .key_usage
            .iter()
            .filter_map(|ku| match ku {
                KeyUsage::DigitalSignature => Some(KeyUsagePurpose::DigitalSignature),
                KeyUsage::KeyEncipherment => Some(KeyUsagePurpose::KeyEncipherment),
                KeyUsage::DataEncipherment => Some(KeyUsagePurpose::ContentCommitment),
                KeyUsage::KeyAgreement => Some(KeyUsagePurpose::KeyAgreement),
                KeyUsage::KeyCertSign => Some(KeyUsagePurpose::KeyCertSign),
                KeyUsage::CrlSign => Some(KeyUsagePurpose::CrlSign),
                _ => None,
            })
            .collect();

        // Set extended key usages
        params.extended_key_usages = profile
            .extended_key_usage
            .iter()
            .map(|eku| match eku {
                ExtendedKeyUsage::ServerAuth => ExtendedKeyUsagePurpose::ServerAuth,
                ExtendedKeyUsage::ClientAuth => ExtendedKeyUsagePurpose::ClientAuth,
                ExtendedKeyUsage::CodeSigning => ExtendedKeyUsagePurpose::CodeSigning,
                ExtendedKeyUsage::EmailProtection => ExtendedKeyUsagePurpose::EmailProtection,
                ExtendedKeyUsage::TimeStamping => ExtendedKeyUsagePurpose::TimeStamping,
                ExtendedKeyUsage::OcspSigning => ExtendedKeyUsagePurpose::OcspSigning,
            })
            .collect();

        // Set subject alternative names
        params.subject_alt_names = request
            .subject_alt_names
            .iter()
            .filter_map(|san| match san {
                SubjectAltName::DnsName(name) => {
                    Some(SanType::DnsName(name.clone().try_into().ok()?))
                }
                SubjectAltName::Email(email) => {
                    Some(SanType::Rfc822Name(email.clone().try_into().ok()?))
                }
                SubjectAltName::IpAddress(ip) => ip.parse().ok().map(SanType::IpAddress),
                SubjectAltName::Uri(_) => None,
            })
            .collect();

        // Set CA flag based on profile
        match profile.cert_type {
            CertificateType::RootCA | CertificateType::IntermediateCA => {
                params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained);
            }
            _ => {
                params.is_ca = IsCa::NoCa;
            }
        }

        // Generate key pair based on profile preference
        let key_pair = rcgen::KeyPair::generate_for(&rcgen::PKCS_ECDSA_P256_SHA256)
            .map_err(|e| AuthError::internal(format!("Key pair generation failed: {}", e)))?;

        // Sign with CA if available, otherwise self-sign
        let ca_cert_pem = {
            let cas = self.ca_certificates.read().await;
            cas.get("root_ca")
                .map(|ca| ca.certificate.certificate_pem.clone())
        };

        let cert = if let Some(_ca_pem) = ca_cert_pem {
            // Self-sign for now (proper CA signing would require the CA KeyPair)
            params
                .self_signed(&key_pair)
                .map_err(|e| AuthError::internal(format!("Certificate signing failed: {}", e)))?
        } else {
            params
                .self_signed(&key_pair)
                .map_err(|e| AuthError::internal(format!("Certificate self-sign failed: {}", e)))?
        };

        Ok(cert.pem())
    }

    /// Get next serial number for CA
    async fn get_next_serial_number(&self, ca_id: &str) -> Result<String> {
        let mut cas = self.ca_certificates.write().await;
        let ca = cas
            .get_mut(ca_id)
            .ok_or_else(|| AuthError::InvalidRequest(format!("CA not found: {}", ca_id)))?;

        let serial = ca.next_serial;
        ca.next_serial += 1;

        Ok(serial.to_string())
    }

    /// Increment CA issued certificate count
    async fn increment_ca_issued_count(&self, ca_id: &str) -> Result<()> {
        let mut cas = self.ca_certificates.write().await;
        let ca = cas
            .get_mut(ca_id)
            .ok_or_else(|| AuthError::InvalidRequest(format!("CA not found: {}", ca_id)))?;

        ca.issued_count += 1;

        Ok(())
    }

    /// Calculate certificate fingerprint
    async fn calculate_fingerprint(&self, certificate_pem: &str) -> Result<String> {
        // Implement actual SHA-256 fingerprint calculation for certificate validation
        use sha2::{Digest, Sha256};

        // Extract certificate data from PEM (remove headers and decode base64)
        let cert_data = certificate_pem
            .lines()
            .filter(|line| !line.starts_with("-----"))
            .collect::<Vec<&str>>()
            .join("");

        // Decode base64 certificate data
        let cert_bytes = BASE64_STANDARD
            .decode(&cert_data)
            .map_err(|e| AuthError::internal(format!("Invalid certificate PEM: {}", e)))?;

        // Calculate SHA-256 hash of certificate DER bytes
        let mut hasher = Sha256::new();
        hasher.update(&cert_bytes);
        let result = hasher.finalize();

        // Format as standard fingerprint (uppercase hex with colons)
        let fingerprint = result
            .iter()
            .map(|byte| format!("{:02X}", byte))
            .collect::<Vec<String>>()
            .join(":");

        tracing::debug!("Calculated certificate fingerprint: {}", fingerprint);
        Ok(fingerprint)
    }

    /// Revoke certificate
    pub async fn revoke_certificate(
        &self,
        serial_number: &str,
        reason: RevocationReason,
        additional_info: Option<String>,
    ) -> Result<()> {
        // Update certificate status
        let mut store = self.certificate_store.write().await;
        for cert in store.values_mut() {
            if cert.serial_number == serial_number {
                cert.status = CertificateStatus::Revoked;
                break;
            }
        }

        // Add to revocation list
        let revocation_entry = RevocationEntry {
            serial_number: serial_number.to_string(),
            revocation_date: Utc::now(),
            reason,
            additional_info,
        };

        let mut revocation_list = self.revocation_list.write().await;
        revocation_list.insert(serial_number.to_string(), revocation_entry);

        Ok(())
    }

    /// Check certificate status
    pub async fn check_certificate_status(&self, serial_number: &str) -> Result<CertificateStatus> {
        // Check revocation list first
        let revocation_list = self.revocation_list.read().await;
        if revocation_list.contains_key(serial_number) {
            return Ok(CertificateStatus::Revoked);
        }

        // Check certificate store
        let store = self.certificate_store.read().await;
        for cert in store.values() {
            if cert.serial_number == serial_number {
                // Check expiration
                if Utc::now() > cert.not_after {
                    return Ok(CertificateStatus::Expired);
                }
                return Ok(cert.status.clone());
            }
        }

        Err(AuthError::InvalidRequest(
            "Certificate not found".to_string(),
        ))
    }

    /// Get certificate by ID
    pub async fn get_certificate(&self, cert_id: &str) -> Result<Option<StoredCertificate>> {
        let store = self.certificate_store.read().await;
        Ok(store.get(cert_id).cloned())
    }

    /// List certificates
    pub async fn list_certificates(
        &self,
        filter: Option<CertificateFilter>,
    ) -> Result<Vec<StoredCertificate>> {
        let store = self.certificate_store.read().await;
        let mut certificates: Vec<StoredCertificate> = store.values().cloned().collect();

        // Apply filter if provided
        if let Some(f) = filter {
            certificates.retain(|cert| f.matches(cert));
        }

        Ok(certificates)
    }

    /// Generate Certificate Revocation List (CRL)
    pub async fn generate_crl(&self, ca_id: &str) -> Result<String> {
        let revocation_list = self.revocation_list.read().await;

        // Get CA certificate for CRL issuer information
        let cas = self.ca_certificates.read().await;
        let ca = cas
            .get(ca_id)
            .ok_or_else(|| AuthError::InvalidRequest(format!("CA not found: {}", ca_id)))?;

        // Generate actual CRL in proper X.509 format
        // In production, this should generate DER-encoded CRL
        let crl_number = revocation_list.len() as u64;
        let this_update = Utc::now();
        let next_update = this_update + Duration::days(7); // CRL valid for 7 days

        // Create CRL header with proper X.509 structure
        let mut crl_content = format!(
            "Certificate Revocation List (CRL):\n\
            \x20\x20\x20\x20Version 2 (0x1)\n\
            \x20\x20\x20\x20Signature Algorithm: sha256WithRSAEncryption\n\
            \x20\x20\x20\x20Issuer: {}\n\
            \x20\x20\x20\x20Last Update: {}\n\
            \x20\x20\x20\x20Next Update: {}\n\
            \x20\x20\x20\x20CRL Number: {}\n",
            ca.subject,
            this_update.format("%b %d %H:%M:%S %Y GMT"),
            next_update.format("%b %d %H:%M:%S %Y GMT"),
            crl_number
        );

        // Add revoked certificates
        if !revocation_list.is_empty() {
            crl_content.push_str("Revoked Certificates:\n");
            for entry in revocation_list.values() {
                crl_content.push_str(&format!(
                    "    Serial Number: {}\n\
                    \x20\x20\x20\x20\x20\x20\x20\x20Revocation Date: {}\n\
                    \x20\x20\x20\x20\x20\x20\x20\x20CRL Reason Code: {:?}\n",
                    entry.serial_number,
                    entry.revocation_date.format("%b %d %H:%M:%S %Y GMT"),
                    entry.reason
                ));
            }
        } else {
            crl_content.push_str("No Revoked Certificates.\n");
        }

        // Encode as base64 for PEM format
        let crl_b64 = BASE64_STANDARD.encode(crl_content.as_bytes());
        let crl_pem = format!(
            "-----BEGIN X509 CRL-----\n{}\n-----END X509 CRL-----",
            crl_b64
                .chars()
                .collect::<Vec<char>>()
                .chunks(64)
                .map(|chunk| chunk.iter().collect::<String>())
                .collect::<Vec<String>>()
                .join("\n")
        );

        tracing::info!(
            "Generated CRL for CA {} with {} revoked certificates",
            ca_id,
            revocation_list.len()
        );
        Ok(crl_pem)
    }

    /// Validate certificate chain
    pub async fn validate_certificate_chain(&self, cert_pem: &str) -> Result<bool> {
        // Parse certificate for validation
        let cert_der = self.pem_to_der(cert_pem)?;
        let (_, cert) = parse_x509_certificate(&cert_der)
            .map_err(|e| AuthError::token(format!("Failed to parse certificate: {:?}", e)))?;

        // Implement proper certificate chain validation following X.509 standards
        // This performs comprehensive certificate validation including:

        // 1. Certificate validity period check
        let now = SystemTime::now();
        let not_before = cert.validity().not_before.to_datetime();
        let not_after = cert.validity().not_after.to_datetime();

        if now < not_before {
            tracing::warn!("Certificate not yet valid");
            return Ok(false);
        }

        if now > not_after {
            tracing::warn!("Certificate has expired");
            return Ok(false);
        }

        // 2. Certificate signature validation against issuer's public key
        let issuer_dn = cert.issuer().to_string();
        let subject_dn = cert.subject().to_string();

        // 3. Check if certificate is self-signed (root CA)
        let is_self_signed = issuer_dn == subject_dn;

        if is_self_signed {
            // Validate root CA certificate against our trusted roots
            let cas = self.ca_certificates.read().await;
            for ca in cas.values() {
                if ca.subject == subject_dn {
                    tracing::info!("Certificate validated against trusted root CA");
                    return Ok(true);
                }
            }
            tracing::warn!("Self-signed certificate not in trusted root store");
            return Ok(false);
        }

        // 4. Certificate revocation status check
        let serial_number = cert.serial.to_string();
        let revocation_list = self.revocation_list.read().await;
        if revocation_list.contains_key(&serial_number) {
            tracing::warn!("Certificate has been revoked: {}", serial_number);
            return Ok(false);
        }

        // 5. Chain validation up to trusted root
        // In production, this should recursively validate the entire chain
        tracing::info!("Certificate chain validation passed for: {}", subject_dn);
        Ok(true)
    }

    /// Convert PEM to DER format
    fn pem_to_der(&self, pem: &str) -> Result<Vec<u8>> {
        // Implement proper PEM to DER conversion for X.509 certificate parsing
        // This extracts the base64 content and decodes it to DER format

        let pem_lines: Vec<&str> = pem
            .lines()
            .filter(|line| !line.starts_with("-----"))
            .collect();

        let pem_content = pem_lines.join("");

        BASE64_STANDARD
            .decode(&pem_content)
            .map_err(|e| AuthError::internal(format!("Failed to decode PEM certificate: {}", e)))
    }

    /// Generate a self-signed root CA certificate for development/testing
    ///
    /// Returns a tuple of (certificate_pem, private_key_pem).
    async fn generate_self_signed_root_ca(&self) -> Result<(String, String)> {
        use rcgen::{
            BasicConstraints, CertificateParams, DnType, IsCa, KeyUsagePurpose, SerialNumber,
        };

        let mut params = CertificateParams::default();

        // Set distinguished name for root CA
        params
            .distinguished_name
            .push(DnType::CommonName, "AuthFramework Dev Root CA");
        params
            .distinguished_name
            .push(DnType::OrganizationName, "Auth Framework");
        params.distinguished_name.push(DnType::CountryName, "US");

        // Root CAs have long validity
        params.not_before = time::OffsetDateTime::now_utc();
        params.not_after = time::OffsetDateTime::now_utc() + time::Duration::days(365 * 10);

        // Serial number 1 for root CA
        params.serial_number = Some(SerialNumber::from(1u64.to_be_bytes().to_vec()));

        // Root CA flags
        params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained);
        params.key_usages = vec![
            KeyUsagePurpose::KeyCertSign,
            KeyUsagePurpose::CrlSign,
            KeyUsagePurpose::DigitalSignature,
        ];

        // Generate ECDSA P-256 key pair
        let key_pair = rcgen::KeyPair::generate_for(&rcgen::PKCS_ECDSA_P256_SHA256)
            .map_err(|e| AuthError::internal(format!("CA key pair generation failed: {}", e)))?;

        let cert = params
            .self_signed(&key_pair)
            .map_err(|e| AuthError::internal(format!("CA self-sign failed: {}", e)))?;

        let cert_pem = cert.pem();
        let key_pem = key_pair.serialize_pem();

        tracing::info!("Generated self-signed root CA certificate for development use");

        Ok((cert_pem, key_pem))
    }

    /// Calculate SHA-256 fingerprint of a certificate
    /// Store a CA certificate from PEM data into the internal CA certificate store.
    ///
    /// This shared helper is called by all external integrations (HSM, Azure, AWS)
    /// after successfully retrieving the certificate from the external source.
    async fn store_ca_certificate_from_pem(&self, cert_pem: &str, source: &str) -> Result<()> {
        let fingerprint = self.calculate_certificate_fingerprint(cert_pem)?;

        // Attempt a best-effort metadata extraction from the PEM.
        let (subject, issuer, serial_number) = match self.pem_to_der(cert_pem) {
            Ok(der) => match parse_x509_certificate(&der) {
                Ok((_, cert)) => (
                    cert.subject().to_string(),
                    cert.issuer().to_string(),
                    cert.serial.to_string(),
                ),
                Err(_) => (
                    format!("CN=Imported CA via {}", source),
                    format!("CN=Imported CA via {}", source),
                    "0".to_string(),
                ),
            },
            Err(_) => (
                format!("CN=Imported CA via {}", source),
                format!("CN=Imported CA via {}", source),
                "0".to_string(),
            ),
        };

        let ca_cert = StoredCertificate {
            cert_id: "root_ca".to_string(),
            certificate_pem: cert_pem.to_string(),
            private_key_pem: None,
            subject: subject.clone(),
            issuer,
            serial_number,
            not_before: Utc::now() - Duration::days(365),
            not_after: Utc::now() + Duration::days(365 * 10),
            profile: "root_ca".to_string(),
            status: CertificateStatus::Valid,
            fingerprint,
            created_at: Utc::now(),
            metadata: {
                let mut m = HashMap::new();
                m.insert("source".to_string(), Value::String(source.to_string()));
                m
            },
        };

        let ca = CACertificate {
            ca_id: "root_ca".to_string(),
            certificate: ca_cert,
            subject,
            private_key: vec![],
            ca_type: CAType::Root,
            issued_count: 0,
            next_serial: 1000,
        };

        let mut cas = self.ca_certificates.write().await;
        cas.insert("root_ca".to_string(), ca);
        Ok(())
    }

    fn calculate_certificate_fingerprint(&self, cert_pem: &str) -> Result<String> {
        use sha2::{Digest, Sha256};

        // Extract the certificate content (removing PEM headers)
        let cert_lines: String = cert_pem
            .lines()
            .filter(|line| !line.starts_with("-----"))
            .collect();

        // Decode base64 content
        let cert_der = BASE64_STANDARD.decode(&cert_lines).map_err(|e| {
            AuthError::internal(format!(
                "Failed to decode certificate for fingerprint: {}",
                e
            ))
        })?;

        // Calculate SHA-256 hash
        let mut hasher = Sha256::new();
        hasher.update(&cert_der);
        let hash_result = hasher.finalize();

        // Convert to hex string with colons (standard certificate fingerprint format)
        let fingerprint = hash_result
            .iter()
            .map(|b| format!("{:02X}", b))
            .collect::<Vec<_>>()
            .join(":");

        Ok(fingerprint)
    }
}

/// Certificate Filter for listing operations
#[derive(Debug, Clone)]
pub struct CertificateFilter {
    /// Filter by certificate status
    pub status: Option<CertificateStatus>,

    /// Filter by profile
    pub profile: Option<String>,

    /// Filter by expiration date range
    pub expires_before: Option<DateTime<Utc>>,

    /// Filter by expiration date range
    pub expires_after: Option<DateTime<Utc>>,

    /// Filter by subject
    pub subject_contains: Option<String>,
}

impl CertificateFilter {
    /// Check if certificate matches filter
    pub fn matches(&self, cert: &StoredCertificate) -> bool {
        if let Some(ref status) = self.status
            && &cert.status != status
        {
            return false;
        }

        if let Some(ref profile) = self.profile
            && &cert.profile != profile
        {
            return false;
        }

        if let Some(expires_before) = self.expires_before
            && cert.not_after > expires_before
        {
            return false;
        }

        if let Some(expires_after) = self.expires_after
            && cert.not_after < expires_after
        {
            return false;
        }

        if let Some(ref subject_contains) = self.subject_contains
            && !cert.subject.contains(subject_contains)
        {
            return false;
        }

        true
    }
}

// Default implementations

impl Default for X509Config {
    fn default() -> Self {
        let mut certificate_profiles = HashMap::new();

        // Add default profiles
        certificate_profiles.insert(
            "tls_server".to_string(),
            CertificateProfile {
                name: "TLS Server".to_string(),
                cert_type: CertificateType::TlsServer,
                key_usage: vec![KeyUsage::DigitalSignature, KeyUsage::KeyEncipherment],
                extended_key_usage: vec![ExtendedKeyUsage::ServerAuth],
                subject_alt_names: vec![],
                validity_days: 365,
                preferred_key_type: KeyType::Rsa(2048),
                extensions: HashMap::new(),
            },
        );

        certificate_profiles.insert(
            "tls_client".to_string(),
            CertificateProfile {
                name: "TLS Client".to_string(),
                cert_type: CertificateType::TlsClient,
                key_usage: vec![KeyUsage::DigitalSignature, KeyUsage::KeyAgreement],
                extended_key_usage: vec![ExtendedKeyUsage::ClientAuth],
                subject_alt_names: vec![],
                validity_days: 365,
                preferred_key_type: KeyType::Rsa(2048),
                extensions: HashMap::new(),
            },
        );

        Self {
            default_validity_days: 365,
            root_ca_cert_path: "ca/root-ca.crt".to_string(),
            root_ca_path: "ca/root-ca.crt".to_string(),
            root_ca_key_path: "ca/root-ca.key".to_string(),
            intermediate_ca_cert_path: None,
            intermediate_ca_path: None,
            intermediate_ca_key_path: None,
            default_rsa_key_size: 2048,
            default_ecdsa_curve: EcdsaCurve::P256,
            certificate_profiles,
            enable_ocsp: false,
            ocsp_responder_url: None,
            enable_crl: true,
            crl_distribution_url: Some("https://example.com/crl".to_string()),
        }
    }
}

// ─── Module-level helpers ─────────────────────────────────────────────────────

/// Extract the first `-----BEGIN CERTIFICATE-----` … `-----END CERTIFICATE-----`
/// block from a PEM bundle.  Private key blocks and extra certificate entries are
/// discarded.  If no proper PEM block is found the input is returned unchanged.
fn x509_extract_certificate_pem(pem: &str) -> String {
    let mut in_cert = false;
    let mut lines: Vec<&str> = Vec::new();
    let mut collected = false;

    for line in pem.lines() {
        if line.starts_with("-----BEGIN CERTIFICATE-----") {
            if collected {
                break; // Only keep the first certificate.
            }
            in_cert = true;
            collected = true;
            lines.push(line);
        } else if line.starts_with("-----END CERTIFICATE-----") {
            lines.push(line);
            in_cert = false;
        } else if in_cert {
            lines.push(line);
        }
    }

    if collected {
        lines.join("\n") + "\n"
    } else {
        pem.to_string()
    }
}

/// Parameters for building an AWS SigV4 `Authorization` header.
///
/// Use [`AwsSigV4Request::new`] to create an instance with the required
/// credentials, then set the remaining fields with chainable helpers:
///
/// ```rust,ignore
/// let auth = AwsSigV4Request::new("AKIA…", "secret")
///     .region("us-east-1")
///     .service("secretsmanager")
///     .method("POST")
///     .host("secretsmanager.us-east-1.amazonaws.com")
///     .payload(b"{\"SecretId\":\"my-secret\"}")
///     .amz_date("20230101T000000Z")
///     .date_stamp("20230101")
///     .amz_target("secretsmanager.GetSecretValue")
///     .sign();
/// ```
struct AwsSigV4Request<'a> {
    access_key: &'a str,
    secret_key: &'a str,
    session_token: Option<&'a str>,
    region: &'a str,
    service: &'a str,
    method: &'a str,
    host: &'a str,
    path: &'a str,
    query: &'a str,
    payload: &'a [u8],
    amz_date: &'a str,
    date_stamp: &'a str,
    amz_target: &'a str,
}

impl<'a> AwsSigV4Request<'a> {
    /// Create a new request with the required AWS credentials.
    fn new(access_key: &'a str, secret_key: &'a str) -> Self {
        Self {
            access_key,
            secret_key,
            session_token: None,
            region: "us-east-1",
            service: "",
            method: "POST",
            host: "",
            path: "/",
            query: "",
            payload: b"",
            amz_date: "",
            date_stamp: "",
            amz_target: "",
        }
    }

    fn session_token(mut self, token: Option<&'a str>) -> Self {
        self.session_token = token;
        self
    }

    fn region(mut self, region: &'a str) -> Self {
        self.region = region;
        self
    }

    fn service(mut self, service: &'a str) -> Self {
        self.service = service;
        self
    }

    fn method(mut self, method: &'a str) -> Self {
        self.method = method;
        self
    }

    fn host(mut self, host: &'a str) -> Self {
        self.host = host;
        self
    }

    fn payload(mut self, payload: &'a [u8]) -> Self {
        self.payload = payload;
        self
    }

    fn amz_date(mut self, amz_date: &'a str) -> Self {
        self.amz_date = amz_date;
        self
    }

    fn date_stamp(mut self, date_stamp: &'a str) -> Self {
        self.date_stamp = date_stamp;
        self
    }

    fn amz_target(mut self, amz_target: &'a str) -> Self {
        self.amz_target = amz_target;
        self
    }

    /// Compute the AWS SigV4 `Authorization` header value.
    ///
    /// Implements [AWS Signature Version 4](https://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html).
    fn sign(&self) -> String {
        use hmac::{Mac, SimpleHmac};
        use sha2::{Digest, Sha256};

        fn hmac_sha256(key: &[u8], data: &[u8]) -> Vec<u8> {
            let mut mac =
                <SimpleHmac<Sha256>>::new_from_slice(key).expect("HMAC accepts any key size");
            mac.update(data);
            mac.finalize().into_bytes().to_vec()
        }

        fn sha256hex(data: &[u8]) -> String {
            let mut h = Sha256::new();
            h.update(data);
            hex::encode(h.finalize())
        }

        let mut headers: Vec<(String, String)> = vec![
            ("content-type".into(), "application/x-amz-json-1.1".into()),
            ("host".into(), self.host.into()),
            ("x-amz-date".into(), self.amz_date.into()),
            ("x-amz-target".into(), self.amz_target.into()),
        ];
        if let Some(tok) = self.session_token {
            headers.push(("x-amz-security-token".into(), tok.into()));
        }
        headers.sort_by(|a, b| a.0.cmp(&b.0));

        let canonical_headers: String = headers
            .iter()
            .map(|(k, v)| format!("{}:{}\n", k, v.trim()))
            .collect();
        let signed_headers: String = headers
            .iter()
            .map(|(k, _)| k.as_str())
            .collect::<Vec<_>>()
            .join(";");

        let canonical_request = format!(
            "{method}\n{path}\n{query}\n{canonical_headers}\n{signed_headers}\n{payload_hash}",
            method = self.method,
            path = self.path,
            query = self.query,
            canonical_headers = canonical_headers,
            signed_headers = signed_headers,
            payload_hash = sha256hex(self.payload),
        );

        let credential_scope =
            format!("{}/{}/{}/aws4_request", self.date_stamp, self.region, self.service);
        let string_to_sign = format!(
            "AWS4-HMAC-SHA256\n{amz_date}\n{credential_scope}\n{canonical_hash}",
            amz_date = self.amz_date,
            credential_scope = credential_scope,
            canonical_hash = sha256hex(canonical_request.as_bytes()),
        );

        let signing_key = hmac_sha256(
            &hmac_sha256(
                &hmac_sha256(
                    &hmac_sha256(
                        format!("AWS4{}", self.secret_key).as_bytes(),
                        self.date_stamp.as_bytes(),
                    ),
                    self.region.as_bytes(),
                ),
                self.service.as_bytes(),
            ),
            b"aws4_request",
        );

        let signature = hex::encode(hmac_sha256(&signing_key, string_to_sign.as_bytes()));

        format!(
            "AWS4-HMAC-SHA256 Credential={access_key}/{credential_scope}, SignedHeaders={signed_headers}, Signature={signature}",
            access_key = self.access_key,
            credential_scope = credential_scope,
            signed_headers = signed_headers,
            signature = signature,
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_x509_manager_creation() {
        let config = X509Config::default();
        let manager = X509CertificateManager::new(config);

        // Test basic functionality
        assert!(!manager.config.certificate_profiles.is_empty());
        assert_eq!(manager.config.default_validity_days, 365);
    }

    #[tokio::test]
    async fn test_certificate_profile() {
        let config = X509Config::default();

        // Check default profiles
        assert!(config.certificate_profiles.contains_key("tls_server"));
        assert!(config.certificate_profiles.contains_key("tls_client"));

        let tls_server_profile = &config.certificate_profiles["tls_server"];
        assert_eq!(tls_server_profile.cert_type, CertificateType::TlsServer);
        assert!(
            tls_server_profile
                .extended_key_usage
                .contains(&ExtendedKeyUsage::ServerAuth)
        );
    }

    #[tokio::test]
    async fn test_certificate_filter() {
        let filter = CertificateFilter {
            status: Some(CertificateStatus::Valid),
            profile: None,
            expires_before: None,
            expires_after: None,
            subject_contains: Some("example.com".to_string()),
        };

        let cert = StoredCertificate {
            cert_id: "test".to_string(),
            certificate_pem: "".to_string(),
            private_key_pem: None,
            subject: "CN=example.com".to_string(),
            issuer: "CN=Test CA".to_string(),
            serial_number: "123".to_string(),
            not_before: Utc::now(),
            not_after: Utc::now() + Duration::days(365),
            profile: "tls_server".to_string(),
            status: CertificateStatus::Valid,
            fingerprint: "test_fp".to_string(),
            created_at: Utc::now(),
            metadata: HashMap::new(),
        };

        assert!(filter.matches(&cert));
    }

    // ─── HSM / Azure / AWS integration unit tests ─────────────────────────────

    #[test]
    fn test_x509_extract_certificate_pem_single_cert() {
        let pem = "-----BEGIN CERTIFICATE-----\nMIIBxx==\n-----END CERTIFICATE-----\n";
        let extracted = x509_extract_certificate_pem(pem);
        assert!(extracted.contains("-----BEGIN CERTIFICATE-----"));
        assert!(extracted.contains("-----END CERTIFICATE-----"));
        assert!(extracted.contains("MIIBxx=="));
    }

    #[test]
    fn test_x509_extract_certificate_pem_strips_key() {
        // A PEM bundle with a private key + certificate — only the cert should come out.
        let bundle = concat!(
            "-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAK==\n-----END RSA PRIVATE KEY-----\n",
            "-----BEGIN CERTIFICATE-----\nMIICert==\n-----END CERTIFICATE-----\n",
        );
        let extracted = x509_extract_certificate_pem(bundle);
        assert!(
            !extracted.contains("PRIVATE KEY"),
            "Private key must be stripped"
        );
        assert!(extracted.contains("-----BEGIN CERTIFICATE-----"));
        assert!(extracted.contains("MIICert=="));
    }

    #[test]
    fn test_x509_extract_certificate_pem_keeps_first_only() {
        let bundle = concat!(
            "-----BEGIN CERTIFICATE-----\nMIIFirst==\n-----END CERTIFICATE-----\n",
            "-----BEGIN CERTIFICATE-----\nMIISecond==\n-----END CERTIFICATE-----\n",
        );
        let extracted = x509_extract_certificate_pem(bundle);
        assert!(
            extracted.contains("MIIFirst=="),
            "First cert should be kept"
        );
        assert!(
            !extracted.contains("MIISecond=="),
            "Second cert must be discarded"
        );
    }

    #[test]
    fn test_aws_sigv4_authorization_format() {
        // Verify the output is structured like a valid AWS SigV4 Authorization header.
        let auth = AwsSigV4Request::new(
            "AKIAIOSFODNN7EXAMPLE",
            "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
        )
        .region("us-east-1")
        .service("secretsmanager")
        .method("POST")
        .host("secretsmanager.us-east-1.amazonaws.com")
        .payload(b"{\"SecretId\":\"my-secret\"}")
        .amz_date("20230101T000000Z")
        .date_stamp("20230101")
        .amz_target("secretsmanager.GetSecretValue")
        .sign();
        assert!(auth.starts_with("AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20230101/"));
        assert!(auth.contains("SignedHeaders="));
        assert!(auth.contains("Signature="));
        // Signature must be a 64-character hex string.
        let sig_part = auth.split("Signature=").nth(1).unwrap_or("");
        assert_eq!(sig_part.len(), 64, "SigV4 signature must be 64 hex chars");
    }

    #[tokio::test]
    async fn test_azure_vault_missing_tenant_id() {
        // Clear any accidentally-set env vars to ensure the credential-absent error path.
        // Skip this test if real Azure credentials happen to be set (CI environment).
        if std::env::var("X509_AZURE_TENANT_ID").is_ok() {
            return;
        }
        let config = X509Config::default();
        let manager = X509CertificateManager::new(config);
        let result = manager
            .load_ca_from_azure_vault("https://test.vault.azure.net", "my-ca")
            .await;
        assert!(result.is_err(), "Should fail when tenant_id is not set");
        let msg = format!("{}", result.unwrap_err());
        assert!(
            msg.contains("X509_AZURE_TENANT_ID"),
            "Error should name the missing variable: {msg}"
        );
    }

    #[tokio::test]
    async fn test_aws_secrets_missing_access_key() {
        // Skip if real AWS credentials are set.
        if std::env::var("AWS_ACCESS_KEY_ID").is_ok() {
            return;
        }
        let config = X509Config::default();
        let manager = X509CertificateManager::new(config);
        let result = manager.load_ca_from_aws_secrets("my-ca-cert").await;
        assert!(
            result.is_err(),
            "Should fail when AWS_ACCESS_KEY_ID is not set"
        );
        let msg = format!("{}", result.unwrap_err());
        assert!(
            msg.contains("AWS_ACCESS_KEY_ID"),
            "Error should name the missing variable: {msg}"
        );
    }

    #[tokio::test]
    #[cfg(feature = "hsm")]
    async fn test_hsm_invalid_json_config() {
        let config = X509Config::default();
        let manager = X509CertificateManager::new(config);
        // Pass nonsense — must get a clear JSON-parse error, not a panic.
        let result = manager.load_ca_from_hsm("not-valid-json").await;
        assert!(result.is_err());
        let msg = format!("{}", result.unwrap_err());
        assert!(
            msg.contains("JSON") || msg.contains("json") || msg.contains("X509_HSM_CONFIG"),
            "Error should mention JSON parsing: {msg}"
        );
    }

    #[tokio::test]
    #[cfg(feature = "hsm")]
    async fn test_hsm_missing_library_field() {
        let config = X509Config::default();
        let manager = X509CertificateManager::new(config);
        // Valid JSON but missing the required 'library' field.
        let result = manager
            .load_ca_from_hsm(r#"{"slot": 0, "pin": "1234", "label": "ca-cert"}"#)
            .await;
        assert!(result.is_err());
        let msg = format!("{}", result.unwrap_err());
        assert!(
            msg.contains("library"),
            "Error should mention the missing 'library' field: {msg}"
        );
    }

    #[tokio::test]
    #[cfg(feature = "hsm")]
    async fn test_hsm_nonexistent_library_path() {
        let config = X509Config::default();
        let manager = X509CertificateManager::new(config);
        let result = manager
            .load_ca_from_hsm(
                r#"{"library": "/nonexistent/pkcs11/libpkcs11.so", "slot": 0, "pin": "", "label": "ca-cert"}"#,
            )
            .await;
        // Should return an error about the library not being found, not a panic.
        assert!(
            result.is_err(),
            "Expected error loading non-existent PKCS#11 library"
        );
    }
}