zentinel-proxy 0.6.11

A security-first reverse proxy built on Pingora with sleepable ops at the edge
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
//! TLS Configuration and SNI Support
//!
//! This module provides TLS configuration with Server Name Indication (SNI) support
//! for serving multiple certificates based on the requested hostname.
//!
//! # Features
//!
//! - SNI-based certificate selection
//! - Wildcard certificate matching (e.g., `*.example.com`)
//! - Automatic CN/SAN extraction when hostnames are omitted
//! - Default certificate fallback
//! - Certificate validation at startup
//! - mTLS client certificate verification
//! - Certificate hot-reload on SIGHUP
//! - OCSP stapling support
//!
//! # Example KDL Configuration
//!
//! ```kdl
//! listener "https" {
//!     address "0.0.0.0:443"
//!     protocol "https"
//!     tls {
//!         cert-file "/etc/certs/default.crt"
//!         key-file "/etc/certs/default.key"
//!
//!         // SNI certificates with explicit hostnames
//!         sni {
//!             hostnames "example.com" "www.example.com"
//!             cert-file "/etc/certs/example.crt"
//!             key-file "/etc/certs/example.key"
//!         }
//!         sni {
//!             hostnames "*.api.example.com"
//!             cert-file "/etc/certs/api-wildcard.crt"
//!             key-file "/etc/certs/api-wildcard.key"
//!         }
//!
//!         // SNI certificate with auto-extracted hostnames from CN/SAN
//!         sni {
//!             cert-file "/etc/certs/premium.crt"
//!             key-file "/etc/certs/premium.key"
//!         }
//!
//!         // SNI certificate with priority tie-breaking (auto-extracts all SANs,
//!         // but this cert wins for "shared.example.com" if contested)
//!         sni {
//!             priority-hostnames "shared.example.com"
//!             cert-file "/etc/certs/shared.crt"
//!             key-file "/etc/certs/shared.key"
//!         }
//!
//!         // mTLS configuration
//!         ca-file "/etc/certs/ca.crt"
//!         client-auth true
//!
//!         // OCSP stapling
//!         ocsp-stapling true
//!     }
//! }
//! ```

use std::collections::{HashMap, HashSet};
use std::fs::File;
use std::io::BufReader;
use std::path::Path;
use std::sync::Arc;
use std::time::{Duration, Instant};

use parking_lot::RwLock;
use rustls::client::ClientConfig;
use rustls::pki_types::CertificateDer;
use rustls::server::{ClientHello, ResolvesServerCert};
use rustls::sign::CertifiedKey;
use rustls::{RootCertStore, ServerConfig};
use tracing::{debug, error, info, trace, warn};

use zentinel_config::{TlsConfig, UpstreamTlsConfig};

/// Error type for TLS operations
#[derive(Debug)]
pub enum TlsError {
    /// Failed to load certificate file
    CertificateLoad(String),
    /// Failed to load private key file
    KeyLoad(String),
    /// Failed to build TLS configuration
    ConfigBuild(String),
    /// Certificate/key mismatch
    CertKeyMismatch(String),
    /// Invalid certificate
    InvalidCertificate(String),
    /// OCSP fetch error
    OcspFetch(String),
}

impl std::fmt::Display for TlsError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            TlsError::CertificateLoad(e) => write!(f, "Failed to load certificate: {}", e),
            TlsError::KeyLoad(e) => write!(f, "Failed to load private key: {}", e),
            TlsError::ConfigBuild(e) => write!(f, "Failed to build TLS config: {}", e),
            TlsError::CertKeyMismatch(e) => write!(f, "Certificate/key mismatch: {}", e),
            TlsError::InvalidCertificate(e) => write!(f, "Invalid certificate: {}", e),
            TlsError::OcspFetch(e) => write!(f, "Failed to fetch OCSP response: {}", e),
        }
    }
}

impl std::error::Error for TlsError {}

/// SNI-aware certificate resolver
///
/// Resolves certificates based on the Server Name Indication (SNI) extension
/// in the TLS handshake. Supports:
/// - Exact hostname matches
/// - Wildcard certificates (e.g., `*.example.com`)
/// - Default certificate fallback
#[derive(Debug)]
pub struct SniResolver {
    /// Default certificate (used when no SNI match)
    default_cert: Arc<CertifiedKey>,
    /// SNI hostname to certificate mapping
    /// Key is lowercase hostname, value is the certified key
    sni_certs: HashMap<String, Arc<CertifiedKey>>,
    /// Wildcard certificates (e.g., "*.example.com" -> cert)
    wildcard_certs: HashMap<String, Arc<CertifiedKey>>,
}

impl SniResolver {
    /// Create a new SNI resolver from TLS configuration
    pub fn from_config(config: &TlsConfig) -> Result<Self, TlsError> {
        // Get cert_file and key_file - manual certs or ACME-managed paths
        let (cert_path_buf, key_path_buf);
        let (cert_file, key_file) = match (&config.cert_file, &config.key_file) {
            (Some(cert), Some(key)) => (cert.as_path(), key.as_path()),
            _ if config.acme.is_some() => {
                let acme = config.acme.as_ref().unwrap();
                let primary = acme.domains.first().ok_or_else(|| {
                    TlsError::ConfigBuild(
                        "ACME configuration has no domains for cert path resolution".to_string(),
                    )
                })?;
                cert_path_buf = acme.storage.join("domains").join(primary).join("cert.pem");
                key_path_buf = acme.storage.join("domains").join(primary).join("key.pem");
                (cert_path_buf.as_path(), key_path_buf.as_path())
            }
            _ => {
                return Err(TlsError::ConfigBuild(
                    "TLS configuration requires cert_file and key_file (or ACME block)".to_string(),
                ));
            }
        };

        // Load default certificate
        let default_cert = load_certified_key(cert_file, key_file)?;

        info!(
            cert_file = %cert_file.display(),
            "Loaded default TLS certificate"
        );

        let mut sni_certs = HashMap::new();
        let mut wildcard_certs = HashMap::new();

        // Track which hostnames were registered with priority, so we can resolve
        // conflicts during build. These sets are not stored in the final resolver
        // because priority is a build-time concept only.
        let mut priority_exact: HashSet<String> = HashSet::new();
        let mut priority_wildcard: HashSet<String> = HashSet::new();

        // Load SNI certificates
        for sni_config in &config.additional_certs {
            let cert = load_certified_key(&sni_config.cert_file, &sni_config.key_file)?;
            let cert = Arc::new(cert);

            // Build priority set for this cert (lowercased for consistent matching)
            let priority_set: HashSet<String> = sni_config
                .priority_hostnames
                .iter()
                .map(|h| h.to_lowercase())
                .collect();
            let has_priority = !priority_set.is_empty();

            // Determine hostnames: use explicit config or auto-extract from certificate.
            // When priority_hostnames is set, we always auto-extract (hostnames will be
            // empty due to mutual exclusion validation in the config parser).
            let hostnames = if sni_config.hostnames.is_empty() {
                let extracted =
                    extract_hostnames_from_cert(cert.cert.first().ok_or_else(|| {
                        TlsError::InvalidCertificate(format!(
                            "No certificates in chain for {:?}",
                            sni_config.cert_file
                        ))
                    })?)?;

                if has_priority {
                    info!(
                        cert_file = %sni_config.cert_file.display(),
                        hostnames = ?extracted,
                        priority_hostnames = ?sni_config.priority_hostnames,
                        "Auto-extracted hostnames from certificate CN/SAN (with priority tie-breaking)"
                    );
                } else {
                    info!(
                        cert_file = %sni_config.cert_file.display(),
                        hostnames = ?extracted,
                        "Auto-extracted hostnames from certificate CN/SAN"
                    );
                }

                extracted
            } else {
                sni_config.hostnames.clone()
            };

            for hostname in &hostnames {
                let hostname_lower = hostname.to_lowercase();
                let is_priority = priority_set.contains(&hostname_lower);

                if hostname_lower.starts_with("*.") {
                    // Wildcard certificate
                    let domain = hostname_lower.strip_prefix("*.").unwrap().to_string();

                    if let Some(existing) = wildcard_certs.get(&domain) {
                        if !Arc::ptr_eq(existing, &cert) {
                            let existing_has_priority = priority_wildcard.contains(&domain);

                            if is_priority && existing_has_priority {
                                // Both certs claim priority for the same wildcard
                                return Err(TlsError::ConfigBuild(format!(
                                    "Conflicting priority-hostnames: wildcard '*.{}' is claimed as priority by multiple certificates (including {:?}).",
                                    domain,
                                    sni_config.cert_file
                                )));
                            } else if is_priority {
                                // New cert has priority, overwrite the existing one
                                debug!(
                                    pattern = %hostname,
                                    domain = %domain,
                                    cert_file = %sni_config.cert_file.display(),
                                    "Priority wildcard SNI certificate overwrites previous registration"
                                );
                            } else if existing_has_priority {
                                // Existing cert has priority, skip the new one
                                debug!(
                                    pattern = %hostname,
                                    domain = %domain,
                                    cert_file = %sni_config.cert_file.display(),
                                    "Skipping wildcard SNI registration, existing cert has priority"
                                );
                                continue;
                            } else {
                                // Neither has priority, ambiguity error
                                return Err(TlsError::ConfigBuild(format!(
                                    "Ambiguous SNI configuration: wildcard '*.{}' matches multiple certificates (including {:?}). \
                                     Use explicit 'hostnames' or 'priority-hostnames' to resolve the conflict.",
                                    domain,
                                    sni_config.cert_file
                                )));
                            }
                        }
                    }

                    wildcard_certs.insert(domain.clone(), cert.clone());
                    if is_priority {
                        priority_wildcard.insert(domain.clone());
                    }
                    debug!(
                        pattern = %hostname,
                        domain = %domain,
                        priority = is_priority,
                        cert_file = %sni_config.cert_file.display(),
                        "Registered wildcard SNI certificate"
                    );
                } else {
                    // Exact hostname match
                    if let Some(existing) = sni_certs.get(&hostname_lower) {
                        if !Arc::ptr_eq(existing, &cert) {
                            let existing_has_priority = priority_exact.contains(&hostname_lower);

                            if is_priority && existing_has_priority {
                                // Both certs claim priority for the same hostname
                                return Err(TlsError::ConfigBuild(format!(
                                    "Conflicting priority-hostnames: hostname '{}' is claimed as priority by multiple certificates (including {:?}).",
                                    hostname_lower,
                                    sni_config.cert_file
                                )));
                            } else if is_priority {
                                // New cert has priority, overwrite
                                debug!(
                                    hostname = %hostname_lower,
                                    cert_file = %sni_config.cert_file.display(),
                                    "Priority SNI certificate overwrites previous registration"
                                );
                            } else if existing_has_priority {
                                // Existing cert has priority, skip
                                debug!(
                                    hostname = %hostname_lower,
                                    cert_file = %sni_config.cert_file.display(),
                                    "Skipping SNI registration, existing cert has priority"
                                );
                                continue;
                            } else {
                                // Neither has priority, ambiguity error
                                return Err(TlsError::ConfigBuild(format!(
                                    "Ambiguous SNI configuration: hostname '{}' matches multiple certificates (including {:?}). \
                                     Use explicit 'hostnames' or 'priority-hostnames' to resolve the conflict.",
                                    hostname_lower,
                                    sni_config.cert_file
                                )));
                            }
                        }
                    }

                    sni_certs.insert(hostname_lower.clone(), cert.clone());
                    if is_priority {
                        priority_exact.insert(hostname_lower.clone());
                    }
                    debug!(
                        hostname = %hostname_lower,
                        priority = is_priority,
                        cert_file = %sni_config.cert_file.display(),
                        "Registered SNI certificate"
                    );
                }
            }
        }

        info!(
            exact_certs = sni_certs.len(),
            wildcard_certs = wildcard_certs.len(),
            "SNI resolver initialized"
        );

        Ok(Self {
            default_cert: Arc::new(default_cert),
            sni_certs,
            wildcard_certs,
        })
    }

    /// Resolve certificate for a given server name
    ///
    /// This is the core resolution logic. For the rustls trait implementation,
    /// see `ResolvesServerCert`.
    pub fn resolve(&self, server_name: Option<&str>) -> Arc<CertifiedKey> {
        let Some(name) = server_name else {
            debug!("No SNI provided, using default certificate");
            return self.default_cert.clone();
        };

        let name_lower = name.to_lowercase();

        // Try exact match first
        if let Some(cert) = self.sni_certs.get(&name_lower) {
            debug!(hostname = %name_lower, "SNI exact match found");
            return cert.clone();
        }

        // Try wildcard match
        // For "foo.bar.example.com", try "bar.example.com", then "example.com"
        let parts: Vec<&str> = name_lower.split('.').collect();
        for i in 1..parts.len() {
            let domain = parts[i..].join(".");
            if let Some(cert) = self.wildcard_certs.get(&domain) {
                debug!(
                    hostname = %name_lower,
                    wildcard_domain = %domain,
                    "SNI wildcard match found"
                );
                return cert.clone();
            }
        }

        debug!(
            hostname = %name_lower,
            "No SNI match found, using default certificate"
        );
        self.default_cert.clone()
    }
}

impl ResolvesServerCert for SniResolver {
    fn resolve(&self, client_hello: ClientHello<'_>) -> Option<Arc<CertifiedKey>> {
        Some(self.resolve(client_hello.server_name()))
    }
}

// ============================================================================
// Hot-Reloadable Certificate Support
// ============================================================================

/// Hot-reloadable SNI certificate resolver
///
/// Wraps an SniResolver behind an RwLock to allow certificate hot-reload
/// without restarting the server. On SIGHUP, the inner resolver is replaced
/// with a newly loaded one.
pub struct HotReloadableSniResolver {
    /// Inner resolver (protected by RwLock for hot-reload)
    inner: RwLock<Arc<SniResolver>>,
    /// Original config for reloading
    config: RwLock<TlsConfig>,
    /// Last reload time
    last_reload: RwLock<Instant>,
}

impl std::fmt::Debug for HotReloadableSniResolver {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("HotReloadableSniResolver")
            .field("last_reload", &*self.last_reload.read())
            .finish()
    }
}

impl HotReloadableSniResolver {
    /// Create a new hot-reloadable resolver from TLS configuration
    pub fn from_config(config: TlsConfig) -> Result<Self, TlsError> {
        let resolver = SniResolver::from_config(&config)?;

        Ok(Self {
            inner: RwLock::new(Arc::new(resolver)),
            config: RwLock::new(config),
            last_reload: RwLock::new(Instant::now()),
        })
    }

    /// Reload certificates from disk
    ///
    /// This is called on SIGHUP to pick up new certificates without restart.
    /// If the reload fails, the old certificates continue to be used.
    pub fn reload(&self) -> Result<(), TlsError> {
        let config = self.config.read();

        let cert_file_display = config
            .cert_file
            .as_ref()
            .map(|p| p.display().to_string())
            .unwrap_or_else(|| "(acme-managed)".to_string());

        info!(
            cert_file = %cert_file_display,
            sni_count = config.additional_certs.len(),
            "Reloading TLS certificates"
        );

        // Try to load new certificates
        let new_resolver = SniResolver::from_config(&config)?;

        // Swap in the new resolver atomically
        *self.inner.write() = Arc::new(new_resolver);
        *self.last_reload.write() = Instant::now();

        info!("TLS certificates reloaded successfully");
        Ok(())
    }

    /// Update configuration and reload
    pub fn update_config(&self, new_config: TlsConfig) -> Result<(), TlsError> {
        // Load with new config first
        let new_resolver = SniResolver::from_config(&new_config)?;

        // Update both config and resolver
        *self.config.write() = new_config;
        *self.inner.write() = Arc::new(new_resolver);
        *self.last_reload.write() = Instant::now();

        info!("TLS configuration updated and certificates reloaded");
        Ok(())
    }

    /// Get time since last reload
    pub fn last_reload_age(&self) -> Duration {
        self.last_reload.read().elapsed()
    }

    /// Resolve certificate for a given server name
    ///
    /// This is the core resolution logic exposed for testing.
    pub fn resolve(&self, server_name: Option<&str>) -> Arc<CertifiedKey> {
        self.inner.read().resolve(server_name)
    }
}

impl ResolvesServerCert for HotReloadableSniResolver {
    fn resolve(&self, client_hello: ClientHello<'_>) -> Option<Arc<CertifiedKey>> {
        Some(self.inner.read().resolve(client_hello.server_name()))
    }
}

/// Certificate reload manager
///
/// Tracks all TLS listeners and provides a unified reload interface.
pub struct CertificateReloader {
    /// Map of listener ID to hot-reloadable resolver
    resolvers: RwLock<HashMap<String, Arc<HotReloadableSniResolver>>>,
}

impl CertificateReloader {
    /// Create a new certificate reloader
    pub fn new() -> Self {
        Self {
            resolvers: RwLock::new(HashMap::new()),
        }
    }

    /// Register a resolver for a listener
    pub fn register(&self, listener_id: &str, resolver: Arc<HotReloadableSniResolver>) {
        debug!(listener_id = %listener_id, "Registering TLS resolver for hot-reload");
        self.resolvers
            .write()
            .insert(listener_id.to_string(), resolver);
    }

    /// Reload all registered certificates
    ///
    /// Returns the number of successfully reloaded listeners and any errors.
    pub fn reload_all(&self) -> (usize, Vec<(String, TlsError)>) {
        let resolvers = self.resolvers.read();
        let mut success_count = 0;
        let mut errors = Vec::new();

        info!(
            listener_count = resolvers.len(),
            "Reloading certificates for all TLS listeners"
        );

        for (listener_id, resolver) in resolvers.iter() {
            match resolver.reload() {
                Ok(()) => {
                    success_count += 1;
                    debug!(listener_id = %listener_id, "Certificate reload successful");
                }
                Err(e) => {
                    error!(listener_id = %listener_id, error = %e, "Certificate reload failed");
                    errors.push((listener_id.clone(), e));
                }
            }
        }

        if errors.is_empty() {
            info!(
                success_count = success_count,
                "All certificates reloaded successfully"
            );
        } else {
            warn!(
                success_count = success_count,
                error_count = errors.len(),
                "Certificate reload completed with errors"
            );
        }

        (success_count, errors)
    }

    /// Get reload status for all listeners
    pub fn status(&self) -> HashMap<String, Duration> {
        self.resolvers
            .read()
            .iter()
            .map(|(id, resolver)| (id.clone(), resolver.last_reload_age()))
            .collect()
    }
}

impl Default for CertificateReloader {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// OCSP Stapling Support
// ============================================================================

/// OCSP response cache entry
#[derive(Debug, Clone)]
pub struct OcspCacheEntry {
    /// DER-encoded OCSP response
    pub response: Vec<u8>,
    /// When this response was fetched
    pub fetched_at: Instant,
    /// When this response expires (from nextUpdate field)
    pub expires_at: Option<Instant>,
}

/// OCSP stapling manager
///
/// Fetches and caches OCSP responses for certificates.
pub struct OcspStapler {
    /// Cache of OCSP responses by certificate fingerprint
    cache: RwLock<HashMap<String, OcspCacheEntry>>,
    /// Refresh interval for OCSP responses (default 1 hour)
    refresh_interval: Duration,
}

impl OcspStapler {
    /// Create a new OCSP stapler
    pub fn new() -> Self {
        Self {
            cache: RwLock::new(HashMap::new()),
            refresh_interval: Duration::from_secs(3600), // 1 hour default
        }
    }

    /// Create with custom refresh interval
    pub fn with_refresh_interval(interval: Duration) -> Self {
        Self {
            cache: RwLock::new(HashMap::new()),
            refresh_interval: interval,
        }
    }

    /// Get cached OCSP response for a certificate
    pub fn get_response(&self, cert_fingerprint: &str) -> Option<Vec<u8>> {
        let cache = self.cache.read();
        if let Some(entry) = cache.get(cert_fingerprint) {
            // Check if response is still valid
            if entry.fetched_at.elapsed() < self.refresh_interval {
                trace!(fingerprint = %cert_fingerprint, "OCSP cache hit");
                return Some(entry.response.clone());
            }
            trace!(fingerprint = %cert_fingerprint, "OCSP cache expired");
        }
        None
    }

    /// Fetch OCSP response for a certificate
    ///
    /// This performs an HTTP request to the OCSP responder specified in the
    /// certificate's Authority Information Access extension.
    pub fn fetch_ocsp_response(
        &self,
        cert_der: &[u8],
        issuer_der: &[u8],
    ) -> Result<Vec<u8>, TlsError> {
        use x509_parser::prelude::*;

        // Parse the end-entity certificate
        let (_, cert) = X509Certificate::from_der(cert_der)
            .map_err(|e| TlsError::OcspFetch(format!("Failed to parse certificate: {}", e)))?;

        // Parse the issuer certificate
        let (_, issuer) = X509Certificate::from_der(issuer_der).map_err(|e| {
            TlsError::OcspFetch(format!("Failed to parse issuer certificate: {}", e))
        })?;

        // Extract OCSP responder URL from AIA extension
        let ocsp_url = extract_ocsp_responder_url(&cert)?;
        debug!(url = %ocsp_url, "Found OCSP responder URL");

        // Build OCSP request
        let ocsp_request = build_ocsp_request(&cert, &issuer)?;

        // Send request synchronously (blocking context)
        // Note: In production, this should be async with proper timeout handling
        let response = send_ocsp_request_sync(&ocsp_url, &ocsp_request)?;

        // Calculate fingerprint for caching
        let fingerprint = calculate_cert_fingerprint(cert_der);

        // Cache the response
        let entry = OcspCacheEntry {
            response: response.clone(),
            fetched_at: Instant::now(),
            expires_at: None, // Could parse nextUpdate from response
        };
        self.cache.write().insert(fingerprint, entry);

        info!("Successfully fetched and cached OCSP response");
        Ok(response)
    }

    /// Async version of fetch_ocsp_response
    pub async fn fetch_ocsp_response_async(
        &self,
        cert_der: &[u8],
        issuer_der: &[u8],
    ) -> Result<Vec<u8>, TlsError> {
        use x509_parser::prelude::*;

        // Parse the end-entity certificate
        let (_, cert) = X509Certificate::from_der(cert_der)
            .map_err(|e| TlsError::OcspFetch(format!("Failed to parse certificate: {}", e)))?;

        // Parse the issuer certificate
        let (_, issuer) = X509Certificate::from_der(issuer_der).map_err(|e| {
            TlsError::OcspFetch(format!("Failed to parse issuer certificate: {}", e))
        })?;

        // Extract OCSP responder URL from AIA extension
        let ocsp_url = extract_ocsp_responder_url(&cert)?;
        debug!(url = %ocsp_url, "Found OCSP responder URL");

        // Build OCSP request
        let ocsp_request = build_ocsp_request(&cert, &issuer)?;

        // Send request asynchronously
        let response = send_ocsp_request_async(&ocsp_url, &ocsp_request).await?;

        // Calculate fingerprint for caching
        let fingerprint = calculate_cert_fingerprint(cert_der);

        // Cache the response
        let entry = OcspCacheEntry {
            response: response.clone(),
            fetched_at: Instant::now(),
            expires_at: None,
        };
        self.cache.write().insert(fingerprint, entry);

        info!("Successfully fetched and cached OCSP response (async)");
        Ok(response)
    }

    /// Prefetch OCSP responses for all certificates in a config
    pub fn prefetch_for_config(&self, config: &TlsConfig) -> Vec<String> {
        let mut warnings = Vec::new();

        if !config.ocsp_stapling {
            trace!("OCSP stapling disabled in config");
            return warnings;
        }

        info!("Prefetching OCSP responses for certificates");

        // For now, just log that we would prefetch
        // Full implementation would iterate certificates and fetch OCSP responses
        warnings.push("OCSP stapling prefetch not yet fully implemented".to_string());

        warnings
    }

    /// Clear the OCSP cache
    pub fn clear_cache(&self) {
        self.cache.write().clear();
        info!("OCSP cache cleared");
    }
}

impl Default for OcspStapler {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// OCSP Helper Functions
// ============================================================================

/// Extract OCSP responder URL from certificate's Authority Information Access extension
fn extract_ocsp_responder_url(
    cert: &x509_parser::certificate::X509Certificate,
) -> Result<String, TlsError> {
    use x509_parser::prelude::*;

    // Find the AIA extension
    let aia = cert
        .extensions()
        .iter()
        .find(|ext| ext.oid == oid_registry::OID_PKIX_AUTHORITY_INFO_ACCESS)
        .ok_or_else(|| {
            TlsError::OcspFetch(
                "Certificate does not have Authority Information Access extension".to_string(),
            )
        })?;

    // Parse AIA extension
    let aia_value = match aia.parsed_extension() {
        ParsedExtension::AuthorityInfoAccess(aia) => aia,
        _ => {
            return Err(TlsError::OcspFetch(
                "Failed to parse Authority Information Access extension".to_string(),
            ))
        }
    };

    // Find OCSP access method
    for access in &aia_value.accessdescs {
        if access.access_method == oid_registry::OID_PKIX_ACCESS_DESCRIPTOR_OCSP {
            match &access.access_location {
                GeneralName::URI(url) => {
                    return Ok(url.to_string());
                }
                _ => continue,
            }
        }
    }

    Err(TlsError::OcspFetch(
        "Certificate AIA does not contain OCSP responder URL".to_string(),
    ))
}

/// Build an OCSP request for the given certificate
///
/// This builds a minimal OCSP request with SHA-256 hashes
fn build_ocsp_request(
    cert: &x509_parser::certificate::X509Certificate,
    issuer: &x509_parser::certificate::X509Certificate,
) -> Result<Vec<u8>, TlsError> {
    use sha2::{Digest, Sha256};

    // Per RFC 6960, an OCSP request contains:
    // - Hash of issuer name
    // - Hash of issuer public key
    // - Certificate serial number

    // Hash issuer name (Distinguished Name)
    let issuer_name_hash = {
        let mut hasher = Sha256::new();
        hasher.update(issuer.subject().as_raw());
        hasher.finalize()
    };

    // Hash issuer public key (the BIT STRING content, not including tag/length)
    let issuer_key_hash = {
        let mut hasher = Sha256::new();
        hasher.update(issuer.public_key().subject_public_key.data.as_ref());
        hasher.finalize()
    };

    // Get certificate serial number
    let serial = cert.serial.to_bytes_be();

    // Build ASN.1 DER encoded OCSP request
    // This is a minimal implementation of the OCSP request structure
    let request = build_ocsp_request_der(&issuer_name_hash, &issuer_key_hash, &serial);

    Ok(request)
}

/// Build DER-encoded OCSP request
fn build_ocsp_request_der(
    issuer_name_hash: &[u8],
    issuer_key_hash: &[u8],
    serial_number: &[u8],
) -> Vec<u8> {
    // OID for SHA-256
    let sha256_oid: &[u8] = &[0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01];

    // Build CertID structure
    let hash_algorithm = der_sequence(&[&der_oid(sha256_oid), &der_null()]);

    let cert_id = der_sequence(&[
        &hash_algorithm,
        &der_octet_string(issuer_name_hash),
        &der_octet_string(issuer_key_hash),
        &der_integer(serial_number),
    ]);

    // Build Request structure
    let request = der_sequence(&[&cert_id]);

    // Build requestList (SEQUENCE OF Request)
    let request_list = der_sequence(&[&request]);

    // Build TBSRequest
    let tbs_request = der_sequence(&[&request_list]);

    // Build OCSPRequest
    der_sequence(&[&tbs_request])
}

// DER encoding helpers
fn der_sequence(items: &[&[u8]]) -> Vec<u8> {
    let mut content = Vec::new();
    for item in items {
        content.extend_from_slice(item);
    }
    let mut result = vec![0x30]; // SEQUENCE tag
    result.extend(der_length(content.len()));
    result.extend(content);
    result
}

fn der_oid(oid: &[u8]) -> Vec<u8> {
    let mut result = vec![0x06]; // OID tag
    result.extend(der_length(oid.len()));
    result.extend_from_slice(oid);
    result
}

fn der_null() -> Vec<u8> {
    vec![0x05, 0x00] // NULL
}

fn der_octet_string(data: &[u8]) -> Vec<u8> {
    let mut result = vec![0x04]; // OCTET STRING tag
    result.extend(der_length(data.len()));
    result.extend_from_slice(data);
    result
}

fn der_integer(data: &[u8]) -> Vec<u8> {
    let mut result = vec![0x02]; // INTEGER tag
                                 // Remove leading zeros but ensure at least one byte
    let data = match data.iter().position(|&b| b != 0) {
        Some(pos) => &data[pos..],
        None => &[0],
    };
    // Add leading zero if high bit is set (to ensure positive)
    if !data.is_empty() && data[0] & 0x80 != 0 {
        result.extend(der_length(data.len() + 1));
        result.push(0x00);
    } else {
        result.extend(der_length(data.len()));
    }
    result.extend_from_slice(data);
    result
}

fn der_length(len: usize) -> Vec<u8> {
    if len < 128 {
        vec![len as u8]
    } else if len < 256 {
        vec![0x81, len as u8]
    } else {
        vec![0x82, (len >> 8) as u8, len as u8]
    }
}

/// Send OCSP request synchronously (blocking)
fn send_ocsp_request_sync(url: &str, request: &[u8]) -> Result<Vec<u8>, TlsError> {
    use std::io::{Read, Write};
    use std::net::TcpStream;
    use std::time::Duration;

    // Parse URL to get host, port, and path
    let url = url::Url::parse(url)
        .map_err(|e| TlsError::OcspFetch(format!("Invalid OCSP URL: {}", e)))?;

    let host = url
        .host_str()
        .ok_or_else(|| TlsError::OcspFetch("OCSP URL has no host".to_string()))?;
    let port = url.port().unwrap_or(80);
    let path = if url.path().is_empty() {
        "/"
    } else {
        url.path()
    };

    // Connect to server
    let addr = format!("{}:{}", host, port);
    let mut stream = TcpStream::connect(&addr)
        .map_err(|e| TlsError::OcspFetch(format!("Failed to connect to OCSP responder: {}", e)))?;

    stream
        .set_read_timeout(Some(Duration::from_secs(10)))
        .map_err(|e| TlsError::OcspFetch(format!("Failed to set timeout: {}", e)))?;
    stream
        .set_write_timeout(Some(Duration::from_secs(10)))
        .map_err(|e| TlsError::OcspFetch(format!("Failed to set timeout: {}", e)))?;

    // Build HTTP POST request
    let http_request = format!(
        "POST {} HTTP/1.1\r\n\
         Host: {}\r\n\
         Content-Type: application/ocsp-request\r\n\
         Content-Length: {}\r\n\
         Connection: close\r\n\
         \r\n",
        path,
        host,
        request.len()
    );

    // Send request
    stream
        .write_all(http_request.as_bytes())
        .map_err(|e| TlsError::OcspFetch(format!("Failed to send OCSP request: {}", e)))?;
    stream
        .write_all(request)
        .map_err(|e| TlsError::OcspFetch(format!("Failed to send OCSP request body: {}", e)))?;

    // Read response
    let mut response = Vec::new();
    stream
        .read_to_end(&mut response)
        .map_err(|e| TlsError::OcspFetch(format!("Failed to read OCSP response: {}", e)))?;

    // Parse HTTP response - find body after headers
    let headers_end = response
        .windows(4)
        .position(|w| w == b"\r\n\r\n")
        .ok_or_else(|| TlsError::OcspFetch("Invalid HTTP response: no headers end".to_string()))?;

    let body = &response[headers_end + 4..];
    if body.is_empty() {
        return Err(TlsError::OcspFetch("Empty OCSP response body".to_string()));
    }

    Ok(body.to_vec())
}

/// Send OCSP request asynchronously
async fn send_ocsp_request_async(url: &str, request: &[u8]) -> Result<Vec<u8>, TlsError> {
    let client = reqwest::Client::builder()
        .timeout(Duration::from_secs(10))
        .build()
        .map_err(|e| TlsError::OcspFetch(format!("Failed to create HTTP client: {}", e)))?;

    let response = client
        .post(url)
        .header("Content-Type", "application/ocsp-request")
        .body(request.to_vec())
        .send()
        .await
        .map_err(|e| TlsError::OcspFetch(format!("OCSP request failed: {}", e)))?;

    if !response.status().is_success() {
        return Err(TlsError::OcspFetch(format!(
            "OCSP responder returned status: {}",
            response.status()
        )));
    }

    let body = response
        .bytes()
        .await
        .map_err(|e| TlsError::OcspFetch(format!("Failed to read OCSP response: {}", e)))?;

    Ok(body.to_vec())
}

/// Calculate certificate fingerprint for cache key
fn calculate_cert_fingerprint(cert_der: &[u8]) -> String {
    use sha2::{Digest, Sha256};
    let mut hasher = Sha256::new();
    hasher.update(cert_der);
    let result = hasher.finalize();
    hex::encode(result)
}

// ============================================================================
// Upstream mTLS Support (Client Certificates)
// ============================================================================

/// Load client certificate and key for mTLS to upstreams
///
/// This function loads PEM-encoded certificates and private key and converts
/// them to Pingora's CertKey format for use with `HttpPeer.client_cert_key`.
///
/// # Arguments
///
/// * `cert_path` - Path to PEM-encoded certificate (may include chain)
/// * `key_path` - Path to PEM-encoded private key
///
/// # Returns
///
/// An `Arc<CertKey>` that can be set on `peer.client_cert_key` for mTLS
pub fn load_client_cert_key(
    cert_path: &Path,
    key_path: &Path,
) -> Result<Arc<pingora_core::utils::tls::CertKey>, TlsError> {
    // Read certificate chain (PEM format, may contain intermediates)
    let cert_file = File::open(cert_path)
        .map_err(|e| TlsError::CertificateLoad(format!("{}: {}", cert_path.display(), e)))?;
    let mut cert_reader = BufReader::new(cert_file);

    // Parse certificates from PEM to DER
    let cert_ders: Vec<Vec<u8>> = rustls_pemfile::certs(&mut cert_reader)
        .collect::<Result<Vec<_>, _>>()
        .map_err(|e| TlsError::CertificateLoad(format!("{}: {}", cert_path.display(), e)))?
        .into_iter()
        .map(|c| c.to_vec())
        .collect();

    if cert_ders.is_empty() {
        return Err(TlsError::CertificateLoad(format!(
            "{}: No certificates found in PEM file",
            cert_path.display()
        )));
    }

    // Read private key (PEM format)
    let key_file = File::open(key_path)
        .map_err(|e| TlsError::KeyLoad(format!("{}: {}", key_path.display(), e)))?;
    let mut key_reader = BufReader::new(key_file);

    // Parse private key from PEM to DER
    let key_der = rustls_pemfile::private_key(&mut key_reader)
        .map_err(|e| TlsError::KeyLoad(format!("{}: {}", key_path.display(), e)))?
        .ok_or_else(|| {
            TlsError::KeyLoad(format!(
                "{}: No private key found in PEM file",
                key_path.display()
            ))
        })?
        .secret_der()
        .to_vec();

    // Create Pingora's CertKey (certificates: Vec<Vec<u8>>, key: Vec<u8>)
    let cert_key = pingora_core::utils::tls::CertKey::new(cert_ders, key_der);

    debug!(
        cert_path = %cert_path.display(),
        key_path = %key_path.display(),
        "Loaded mTLS client certificate for upstream connections"
    );

    Ok(Arc::new(cert_key))
}

/// Build a TLS client configuration for upstream connections with mTLS
///
/// This creates a rustls ClientConfig that can be used when Zentinel
/// connects to backends that require client certificate authentication.
pub fn build_upstream_tls_config(config: &UpstreamTlsConfig) -> Result<ClientConfig, TlsError> {
    let mut root_store = RootCertStore::empty();

    // Load CA certificates for server verification
    if let Some(ca_path) = &config.ca_cert {
        let ca_file = File::open(ca_path)
            .map_err(|e| TlsError::CertificateLoad(format!("{}: {}", ca_path.display(), e)))?;
        let mut ca_reader = BufReader::new(ca_file);

        let certs: Vec<CertificateDer<'static>> = rustls_pemfile::certs(&mut ca_reader)
            .collect::<Result<Vec<_>, _>>()
            .map_err(|e| TlsError::CertificateLoad(format!("{}: {}", ca_path.display(), e)))?;

        for cert in certs {
            root_store.add(cert).map_err(|e| {
                TlsError::InvalidCertificate(format!("Failed to add CA certificate: {}", e))
            })?;
        }

        debug!(
            ca_file = %ca_path.display(),
            cert_count = root_store.len(),
            "Loaded upstream CA certificates"
        );
    } else if !config.insecure_skip_verify {
        // Use webpki roots for standard TLS
        root_store = RootCertStore {
            roots: webpki_roots::TLS_SERVER_ROOTS.to_vec(),
        };
        trace!("Using webpki-roots for upstream TLS verification");
    }

    // Build the client config
    let builder = ClientConfig::builder().with_root_certificates(root_store);

    let client_config = if let (Some(cert_path), Some(key_path)) =
        (&config.client_cert, &config.client_key)
    {
        // Load client certificate for mTLS
        let cert_file = File::open(cert_path)
            .map_err(|e| TlsError::CertificateLoad(format!("{}: {}", cert_path.display(), e)))?;
        let mut cert_reader = BufReader::new(cert_file);

        let certs: Vec<CertificateDer<'static>> = rustls_pemfile::certs(&mut cert_reader)
            .collect::<Result<Vec<_>, _>>()
            .map_err(|e| TlsError::CertificateLoad(format!("{}: {}", cert_path.display(), e)))?;

        if certs.is_empty() {
            return Err(TlsError::CertificateLoad(format!(
                "{}: No certificates found",
                cert_path.display()
            )));
        }

        // Load client private key
        let key_file = File::open(key_path)
            .map_err(|e| TlsError::KeyLoad(format!("{}: {}", key_path.display(), e)))?;
        let mut key_reader = BufReader::new(key_file);

        let key = rustls_pemfile::private_key(&mut key_reader)
            .map_err(|e| TlsError::KeyLoad(format!("{}: {}", key_path.display(), e)))?
            .ok_or_else(|| {
                TlsError::KeyLoad(format!("{}: No private key found", key_path.display()))
            })?;

        info!(
            cert_file = %cert_path.display(),
            "Configured mTLS client certificate for upstream connections"
        );

        builder
            .with_client_auth_cert(certs, key)
            .map_err(|e| TlsError::CertKeyMismatch(format!("Failed to set client auth: {}", e)))?
    } else {
        // No client certificate
        builder.with_no_client_auth()
    };

    debug!("Upstream TLS configuration built successfully");
    Ok(client_config)
}

/// Validate upstream TLS configuration
pub fn validate_upstream_tls_config(config: &UpstreamTlsConfig) -> Result<(), TlsError> {
    // Validate CA certificate if specified
    if let Some(ca_path) = &config.ca_cert {
        if !ca_path.exists() {
            return Err(TlsError::CertificateLoad(format!(
                "Upstream CA certificate not found: {}",
                ca_path.display()
            )));
        }
    }

    // Validate client certificate pair if mTLS is configured
    if let Some(cert_path) = &config.client_cert {
        if !cert_path.exists() {
            return Err(TlsError::CertificateLoad(format!(
                "Upstream client certificate not found: {}",
                cert_path.display()
            )));
        }

        // If cert is specified, key must also be specified
        match &config.client_key {
            Some(key_path) if !key_path.exists() => {
                return Err(TlsError::KeyLoad(format!(
                    "Upstream client key not found: {}",
                    key_path.display()
                )));
            }
            None => {
                return Err(TlsError::ConfigBuild(
                    "client_cert specified without client_key".to_string(),
                ));
            }
            _ => {}
        }
    }

    if config.client_key.is_some() && config.client_cert.is_none() {
        return Err(TlsError::ConfigBuild(
            "client_key specified without client_cert".to_string(),
        ));
    }

    Ok(())
}

// ============================================================================
// Certificate Loading Functions
// ============================================================================

/// Load a certificate chain and private key from files
fn load_certified_key(cert_path: &Path, key_path: &Path) -> Result<CertifiedKey, TlsError> {
    // Load certificate chain
    let cert_file = File::open(cert_path)
        .map_err(|e| TlsError::CertificateLoad(format!("{}: {}", cert_path.display(), e)))?;
    let mut cert_reader = BufReader::new(cert_file);

    let certs: Vec<CertificateDer<'static>> = rustls_pemfile::certs(&mut cert_reader)
        .collect::<Result<Vec<_>, _>>()
        .map_err(|e| TlsError::CertificateLoad(format!("{}: {}", cert_path.display(), e)))?;

    if certs.is_empty() {
        return Err(TlsError::CertificateLoad(format!(
            "{}: No certificates found in file",
            cert_path.display()
        )));
    }

    // Load private key
    let key_file = File::open(key_path)
        .map_err(|e| TlsError::KeyLoad(format!("{}: {}", key_path.display(), e)))?;
    let mut key_reader = BufReader::new(key_file);

    let key = rustls_pemfile::private_key(&mut key_reader)
        .map_err(|e| TlsError::KeyLoad(format!("{}: {}", key_path.display(), e)))?
        .ok_or_else(|| {
            TlsError::KeyLoad(format!(
                "{}: No private key found in file",
                key_path.display()
            ))
        })?;

    // Create signing key using the default crypto provider
    let provider = rustls::crypto::CryptoProvider::get_default()
        .cloned()
        .unwrap_or_else(|| Arc::new(rustls::crypto::aws_lc_rs::default_provider()));

    let signing_key = provider
        .key_provider
        .load_private_key(key)
        .map_err(|e| TlsError::CertKeyMismatch(format!("Failed to load private key: {:?}", e)))?;

    Ok(CertifiedKey::new(certs, signing_key))
}

/// Extract DNS hostnames from a certificate's CN and Subject Alternative Names.
///
/// Returns a list of DNS names (e.g., "example.com", "*.example.com") found in:
/// 1. Subject Alternative Name (SAN) DNS entries (preferred)
/// 2. Common Name (CN) as fallback if no SAN DNS entries exist
///
/// IP addresses in SANs are ignored since SNI operates on hostnames only.
fn extract_hostnames_from_cert(cert_der: &CertificateDer<'_>) -> Result<Vec<String>, TlsError> {
    use x509_parser::prelude::*;

    let (_, cert) = X509Certificate::from_der(cert_der).map_err(|e| {
        TlsError::InvalidCertificate(format!("Failed to parse X.509 certificate: {}", e))
    })?;

    let mut hostnames = Vec::new();

    // Try SAN extension first (RFC 6125: SAN takes precedence over CN)
    if let Ok(Some(san_ext)) = cert.subject_alternative_name() {
        for name in &san_ext.value.general_names {
            if let GeneralName::DNSName(dns) = name {
                hostnames.push(dns.to_lowercase());
            }
        }
    }

    // Fall back to CN only if no SAN DNS names were found
    if hostnames.is_empty() {
        for attr in cert.subject().iter_common_name() {
            if let Ok(cn) = attr.as_str() {
                hostnames.push(cn.to_lowercase());
            }
        }
    }

    if hostnames.is_empty() {
        return Err(TlsError::InvalidCertificate(
            "Certificate has no DNS names in SAN or CN".to_string(),
        ));
    }

    Ok(hostnames)
}

/// Load CA certificates for client verification (mTLS)
pub fn load_client_ca(ca_path: &Path) -> Result<RootCertStore, TlsError> {
    let ca_file = File::open(ca_path)
        .map_err(|e| TlsError::CertificateLoad(format!("{}: {}", ca_path.display(), e)))?;
    let mut ca_reader = BufReader::new(ca_file);

    let mut root_store = RootCertStore::empty();

    let certs: Vec<CertificateDer<'static>> = rustls_pemfile::certs(&mut ca_reader)
        .collect::<Result<Vec<_>, _>>()
        .map_err(|e| TlsError::CertificateLoad(format!("{}: {}", ca_path.display(), e)))?;

    for cert in certs {
        root_store.add(cert).map_err(|e| {
            TlsError::InvalidCertificate(format!("Failed to add CA certificate: {}", e))
        })?;
    }

    if root_store.is_empty() {
        return Err(TlsError::CertificateLoad(format!(
            "{}: No CA certificates found",
            ca_path.display()
        )));
    }

    info!(
        ca_file = %ca_path.display(),
        cert_count = root_store.len(),
        "Loaded client CA certificates"
    );

    Ok(root_store)
}

/// Resolve TLS protocol versions from config into rustls version references.
fn resolve_protocol_versions(config: &TlsConfig) -> Vec<&'static rustls::SupportedProtocolVersion> {
    use zentinel_common::types::TlsVersion;

    let min = &config.min_version;
    let max = config.max_version.as_ref().unwrap_or(&TlsVersion::Tls13);

    let mut versions = Vec::new();

    // Include TLS 1.2 if within the min..=max range
    if matches!(min, TlsVersion::Tls12) {
        versions.push(&rustls::version::TLS12);
    }

    // Include TLS 1.3 if within the min..=max range
    if matches!(max, TlsVersion::Tls13) {
        versions.push(&rustls::version::TLS13);
    }

    if versions.is_empty() {
        // Shouldn't happen with valid config, but be safe
        warn!("No valid TLS versions resolved from config, falling back to TLS 1.2 + 1.3");
        versions.push(&rustls::version::TLS12);
        versions.push(&rustls::version::TLS13);
    }

    versions
}

/// Resolve cipher suite names from config to rustls `SupportedCipherSuite` values.
///
/// Uses the aws-lc-rs crypto provider's available cipher suites.
fn resolve_cipher_suites(names: &[String]) -> Result<Vec<rustls::SupportedCipherSuite>, TlsError> {
    use rustls::crypto::aws_lc_rs::cipher_suite;

    // Map of canonical IANA names to rustls cipher suite values
    let known: &[(&str, rustls::SupportedCipherSuite)] = &[
        // TLS 1.3
        (
            "TLS_AES_256_GCM_SHA384",
            cipher_suite::TLS13_AES_256_GCM_SHA384,
        ),
        (
            "TLS_AES_128_GCM_SHA256",
            cipher_suite::TLS13_AES_128_GCM_SHA256,
        ),
        (
            "TLS_CHACHA20_POLY1305_SHA256",
            cipher_suite::TLS13_CHACHA20_POLY1305_SHA256,
        ),
        // TLS 1.2
        (
            "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
            cipher_suite::TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
        ),
        (
            "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
            cipher_suite::TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
        ),
        (
            "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256",
            cipher_suite::TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
        ),
        (
            "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",
            cipher_suite::TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
        ),
        (
            "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
            cipher_suite::TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
        ),
        (
            "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256",
            cipher_suite::TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
        ),
    ];

    let mut suites = Vec::with_capacity(names.len());
    for name in names {
        let normalized = name.to_uppercase().replace('-', "_");
        match known.iter().find(|(n, _)| *n == normalized) {
            Some((_, suite)) => suites.push(*suite),
            None => {
                let available: Vec<&str> = known.iter().map(|(n, _)| *n).collect();
                return Err(TlsError::ConfigBuild(format!(
                    "Unknown cipher suite '{}'. Available: {}",
                    name,
                    available.join(", ")
                )));
            }
        }
    }

    Ok(suites)
}

/// Build a TLS ServerConfig from our configuration.
///
/// Applies protocol versions, cipher suites, session resumption, mTLS,
/// and SNI certificate resolution from the Zentinel TLS config.
///
/// # Note
///
/// This ServerConfig is fully configured but currently not used by
/// Pingora's listener infrastructure. Pingora's rustls `TlsSettings`
/// builds its own `ServerConfig` internally with hardcoded defaults.
/// A future update to the Pingora fork should accept a pre-built
/// `ServerConfig` via `TlsSettings`, at which point this function's
/// output will be wired into the listener setup.
pub fn build_server_config(config: &TlsConfig) -> Result<ServerConfig, TlsError> {
    let resolver = SniResolver::from_config(config)?;

    // Resolve protocol versions from config
    let versions = resolve_protocol_versions(config);
    info!(
        versions = ?versions.iter().map(|v| format!("{:?}", v.version)).collect::<Vec<_>>(),
        "TLS protocol versions configured"
    );

    // Build the ServerConfig builder, with custom cipher suites if specified
    let builder = if !config.cipher_suites.is_empty() {
        let suites = resolve_cipher_suites(&config.cipher_suites)?;
        info!(
            cipher_suites = ?config.cipher_suites,
            count = suites.len(),
            "Custom TLS cipher suites configured"
        );
        let provider = rustls::crypto::CryptoProvider {
            cipher_suites: suites,
            ..rustls::crypto::aws_lc_rs::default_provider()
        };
        ServerConfig::builder_with_provider(Arc::new(provider))
            .with_protocol_versions(&versions)
            .map_err(|e| {
                TlsError::ConfigBuild(format!("Invalid TLS protocol/cipher configuration: {}", e))
            })?
    } else {
        ServerConfig::builder_with_protocol_versions(&versions)
    };

    // Configure client authentication (mTLS)
    let server_config = if config.client_auth {
        if let Some(ca_path) = &config.ca_file {
            let root_store = load_client_ca(ca_path)?;
            let verifier = rustls::server::WebPkiClientVerifier::builder(Arc::new(root_store))
                .build()
                .map_err(|e| {
                    TlsError::ConfigBuild(format!("Failed to build client verifier: {}", e))
                })?;

            info!("mTLS enabled: client certificates required");

            builder
                .with_client_cert_verifier(verifier)
                .with_cert_resolver(Arc::new(resolver))
        } else {
            warn!("client_auth enabled but no ca_file specified, disabling client auth");
            builder
                .with_no_client_auth()
                .with_cert_resolver(Arc::new(resolver))
        }
    } else {
        builder
            .with_no_client_auth()
            .with_cert_resolver(Arc::new(resolver))
    };

    // Configure ALPN for HTTP/2 support
    let mut server_config = server_config;
    server_config.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()];

    // Disable session resumption if configured
    if !config.session_resumption {
        server_config.session_storage = Arc::new(rustls::server::NoServerSessionStorage {});
        info!("TLS session resumption disabled");
    }

    debug!("TLS configuration built successfully");

    Ok(server_config)
}

/// Validate TLS configuration files exist and are readable
pub fn validate_tls_config(config: &TlsConfig) -> Result<(), TlsError> {
    // If ACME is configured, skip manual cert file validation
    if config.acme.is_some() {
        // ACME-managed certificates don't need cert_file/key_file to exist
        trace!("Skipping manual cert validation for ACME-managed TLS");
    } else {
        // Check default certificate (required for non-ACME configs)
        match (&config.cert_file, &config.key_file) {
            (Some(cert_file), Some(key_file)) => {
                if !cert_file.exists() {
                    return Err(TlsError::CertificateLoad(format!(
                        "Certificate file not found: {}",
                        cert_file.display()
                    )));
                }
                if !key_file.exists() {
                    return Err(TlsError::KeyLoad(format!(
                        "Key file not found: {}",
                        key_file.display()
                    )));
                }
            }
            _ => {
                return Err(TlsError::ConfigBuild(
                    "TLS configuration requires cert_file and key_file (or ACME block)".to_string(),
                ));
            }
        }
    }

    // Check SNI certificates
    for sni in &config.additional_certs {
        if !sni.cert_file.exists() {
            return Err(TlsError::CertificateLoad(format!(
                "SNI certificate file not found: {}",
                sni.cert_file.display()
            )));
        }
        if !sni.key_file.exists() {
            return Err(TlsError::KeyLoad(format!(
                "SNI key file not found: {}",
                sni.key_file.display()
            )));
        }
    }

    // Check CA file if mTLS enabled
    if config.client_auth {
        if let Some(ca_path) = &config.ca_file {
            if !ca_path.exists() {
                return Err(TlsError::CertificateLoad(format!(
                    "CA certificate file not found: {}",
                    ca_path.display()
                )));
            }
        }
    }

    Ok(())
}

#[cfg(test)]
mod tests {

    #[test]
    fn test_wildcard_matching() {
        // Create a mock resolver without actual certs
        // Just test the matching logic
        let name = "foo.bar.example.com";
        let parts: Vec<&str> = name.split('.').collect();

        assert_eq!(parts.len(), 4);

        // Check domain extraction for wildcard matching
        let domain1 = parts[1..].join(".");
        assert_eq!(domain1, "bar.example.com");

        let domain2 = parts[2..].join(".");
        assert_eq!(domain2, "example.com");
    }

    #[test]
    fn test_hostname_normalization() {
        let hostname = "Example.COM";
        let normalized = hostname.to_lowercase();
        assert_eq!(normalized, "example.com");
    }
}