rustpython-host_env 0.6.0

Host OS API abstractions for RustPython
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
// cspell: ignore accessdescs

//! Certificate loading and rustls verifiers for `_ssl`.

use alloc::sync::Arc;
use parking_lot::RwLock as ParkingRwLock;
use rustls::{
    DigitallySignedStruct, RootCertStore, SignatureScheme,
    client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier},
    pki_types::{CertificateDer, PrivateKeyDer, ServerName, UnixTime},
    server::danger::{ClientCertVerified, ClientCertVerifier},
};
use std::collections::HashSet;
use x509_parser::prelude::*;

use super::cert::is_ca_certificate;
use super::constants::{VERIFY_X509_PARTIAL_CHAIN, VERIFY_X509_STRICT};
use super::providers::CryptoExt;

// Certificate Verification Constants

/// All supported signature schemes for certificate verification
///
/// This list includes all modern signature algorithms supported by rustls.
/// Used by verifiers that accept any signature scheme (NoVerifier, EmptyRootStoreVerifier).
const ALL_SIGNATURE_SCHEMES: &[SignatureScheme] = &[
    SignatureScheme::RSA_PKCS1_SHA256,
    SignatureScheme::RSA_PKCS1_SHA384,
    SignatureScheme::RSA_PKCS1_SHA512,
    SignatureScheme::ECDSA_NISTP256_SHA256,
    SignatureScheme::ECDSA_NISTP384_SHA384,
    SignatureScheme::ECDSA_NISTP521_SHA512,
    SignatureScheme::RSA_PSS_SHA256,
    SignatureScheme::RSA_PSS_SHA384,
    SignatureScheme::RSA_PSS_SHA512,
    SignatureScheme::ED25519,
];

// Error Handling Utilities

/// Certificate loading error types with specific error messages
///
/// This module provides consistent error creation functions for certificate
/// operations, reducing code duplication and ensuring uniform error messages
/// across the codebase.
mod cert_error {
    use alloc::sync::Arc;
    use core::fmt::{Debug, Display};
    use std::io;

    /// Create InvalidData error with formatted message
    pub(super) fn invalid_data(msg: impl Into<String>) -> io::Error {
        io::Error::new(io::ErrorKind::InvalidData, msg.into())
    }

    /// PEM parsing error variants
    pub(super) mod pem {
        use super::*;

        pub(crate) fn no_start_line(context: &str) -> io::Error {
            invalid_data(format!("no start line: {context}"))
        }

        pub(crate) fn parse_failed(e: impl Display) -> io::Error {
            invalid_data(format!("Failed to parse PEM certificate: {e}"))
        }

        pub(crate) fn parse_failed_debug(e: impl Debug) -> io::Error {
            invalid_data(format!("Failed to parse PEM certificate: {e:?}"))
        }

        pub(crate) fn invalid_cert() -> io::Error {
            invalid_data("No certificates found in certificate file")
        }
    }

    /// DER parsing error variants
    pub(super) mod der {
        use super::*;

        pub(crate) fn not_enough_data(context: &str) -> io::Error {
            invalid_data(format!("not enough data: {context}"))
        }

        pub(crate) fn parse_failed(e: impl Display) -> io::Error {
            invalid_data(format!("Failed to parse DER certificate: {e}"))
        }
    }

    /// Private key error variants
    pub(super) mod key {
        use super::*;

        pub(crate) fn not_found(context: &str) -> io::Error {
            invalid_data(format!("No private key found in {context}"))
        }

        pub(crate) fn parse_failed(e: impl Display) -> io::Error {
            invalid_data(format!("Failed to parse private key: {e}"))
        }

        pub(crate) fn parse_encrypted_failed(e: impl Display) -> io::Error {
            invalid_data(format!("Failed to parse encrypted private key: {e}"))
        }

        pub(crate) fn decrypt_failed(e: impl Display) -> io::Error {
            io::Error::other(format!(
                "Failed to decrypt private key (wrong password?): {e}",
            ))
        }
    }

    /// Convert error message to rustls::Error with InvalidCertificate wrapper
    pub(super) fn to_rustls_invalid_cert(msg: impl Into<String>) -> rustls::Error {
        rustls::Error::InvalidCertificate(rustls::CertificateError::Other(rustls::OtherError(
            Arc::new(invalid_data(msg)),
        )))
    }

    /// Convert error message to rustls::Error with InvalidCertificate wrapper and custom ErrorKind
    pub(super) fn to_rustls_cert_error(
        kind: io::ErrorKind,
        msg: impl Into<String>,
    ) -> rustls::Error {
        rustls::Error::InvalidCertificate(rustls::CertificateError::Other(rustls::OtherError(
            Arc::new(io::Error::new(kind, msg.into())),
        )))
    }
}

/// Normalize wildcard hostname by stripping "*." prefix
///
/// Returns the normalized hostname without the wildcard prefix.
/// Used for wildcard certificate matching.
fn normalize_wildcard_hostname(hostname: &str) -> &str {
    hostname.strip_prefix("*.").unwrap_or(hostname)
}

/// Build a verified certificate chain by adding CA certificates from the trust store
///
/// Takes peer certificates (from TLS handshake) and extends the chain by finding
/// issuer certificates from the trust store until reaching a root certificate.
///
/// Returns the complete chain as DER-encoded bytes.
pub fn build_verified_chain(
    peer_certs: &[CertificateDer<'static>],
    ca_certs_der: &[Vec<u8>],
) -> Vec<Vec<u8>> {
    let mut chain_der: Vec<Vec<u8>> = Vec::new();

    // Start with peer certificates (what was sent during handshake)
    for cert in peer_certs {
        chain_der.push(cert.as_ref().to_vec());
    }

    // Keep adding issuers until we reach a root or can't find the issuer
    while let Some(der) = chain_der.last() {
        let last_cert_der = der;

        // Parse the last certificate in the chain
        let (_, last_cert) = match X509Certificate::from_der(last_cert_der) {
            Ok(parsed) => parsed,
            Err(_) => break,
        };

        // Check if it's self-signed (root certificate)
        if last_cert.subject() == last_cert.issuer() {
            // This is a root certificate, we're done
            break;
        }

        // Try to find the issuer in the trust store
        let issuer_name = last_cert.issuer();
        let mut found_issuer = false;

        for ca_der in ca_certs_der {
            let (_, ca_cert) = match X509Certificate::from_der(ca_der) {
                Ok(parsed) => parsed,
                Err(_) => continue,
            };

            // Check if this CA's subject matches the certificate's issuer
            if ca_cert.subject() == issuer_name {
                // Check if we already have this certificate in the chain
                if !chain_der.iter().any(|existing| existing == ca_der) {
                    chain_der.push(ca_der.clone());
                    found_issuer = true;
                    break;
                }
            }
        }

        if !found_issuer {
            // Can't find issuer, stop here
            break;
        }
    }

    chain_der
}

/// Statistics from certificate loading operations
#[derive(Debug, Clone, Default)]
pub struct CertStats {
    pub total_certs: usize,
    pub ca_certs: usize,
}

/// Certificate loader that handles PEM/DER parsing and validation
///
/// This structure encapsulates the common pattern of loading certificates
/// from various sources (files, directories, bytes) and adding them to
/// a RootCertStore while tracking statistics.
///
/// Duplicate certificates are detected and only counted once.
pub struct CertLoader<'a> {
    store: &'a mut RootCertStore,
    ca_certs_der: &'a mut Vec<Vec<u8>>,
    seen_certs: HashSet<Vec<u8>>,
}

fn is_capath_hash_name(name: &std::ffi::OsStr) -> bool {
    let Some(name) = name.to_str() else {
        return false;
    };
    let Some((hash, suffix)) = name.split_once('.') else {
        return false;
    };
    hash.len() == 8
        && hash.bytes().all(|byte| byte.is_ascii_hexdigit())
        && !suffix.is_empty()
        && suffix.bytes().all(|byte| byte.is_ascii_digit())
}

#[cfg(test)]
mod tests {
    use super::is_capath_hash_name;
    use std::ffi::OsStr;

    #[test]
    fn capath_hash_names_follow_openssl_shape() {
        for valid in ["4e1295a3.0", "ABCDEF01.12"] {
            assert!(is_capath_hash_name(OsStr::new(valid)), "{valid}");
        }
        for invalid in [
            "4e1295a.0",
            "4e1295a30.0",
            "4e1295ag.0",
            "4e1295a3",
            "4e1295a3.",
            "4e1295a3.pem",
        ] {
            assert!(!is_capath_hash_name(OsStr::new(invalid)), "{invalid}");
        }
    }
}

impl<'a> CertLoader<'a> {
    /// Create a new CertLoader with references to the store and DER cache
    pub fn new(store: &'a mut RootCertStore, ca_certs_der: &'a mut Vec<Vec<u8>>) -> Self {
        // Initialize seen_certs with existing certificates
        let seen_certs = ca_certs_der.iter().cloned().collect();
        Self {
            store,
            ca_certs_der,
            seen_certs,
        }
    }

    /// Load certificates from a file (supports both PEM and DER formats)
    ///
    /// Returns statistics about loaded certificates
    pub fn load_from_file(&mut self, path: &str) -> Result<CertStats, std::io::Error> {
        let contents = crate::fs::read(path)?;
        self.load_from_bytes(&contents)
    }

    /// Load certificates from a directory
    ///
    /// Reads OpenSSL-style hashed entries and attempts to parse them as certificates.
    /// Invalid entries are silently skipped (matches OpenSSL capath behavior).
    pub fn load_from_dir(&mut self, dir_path: &str) -> Result<CertStats, std::io::Error> {
        let entries = crate::fs::read_dir(dir_path)?;
        let mut stats = CertStats::default();
        let mut paths = Vec::new();

        for entry in entries {
            let entry = entry?;
            let path = entry.path();
            if is_capath_hash_name(&entry.file_name()) && crate::fs::is_file(&path) {
                paths.push(path);
            }
        }
        paths.sort();

        for path in paths {
            let Ok(contents) = crate::fs::read(path) else {
                continue;
            };
            if let Ok(file_stats) = self.load_from_bytes(&contents) {
                stats.total_certs += file_stats.total_certs;
                stats.ca_certs += file_stats.ca_certs;
            }
        }

        Ok(stats)
    }

    /// Helper: Add a certificate to the store with duplicate checking
    ///
    /// Returns true if the certificate was added (not a duplicate), false if it was a duplicate.
    fn add_cert_to_store(
        &mut self,
        cert_bytes: Vec<u8>,
        cert_der: CertificateDer<'static>,
        treat_all_as_ca: bool,
        stats: &mut CertStats,
    ) -> bool {
        // Check for duplicates using HashSet
        if !self.seen_certs.insert(cert_bytes.clone()) {
            return false; // Duplicate certificate - skip
        }

        // Determine if this is a CA certificate
        let is_ca = if treat_all_as_ca {
            true
        } else {
            is_ca_certificate(&cert_bytes)
        };

        // Store full DER for get_ca_certs()
        self.ca_certs_der.push(cert_bytes);

        // Add to trust store (rustls may handle duplicates internally)
        let _ = self.store.add(cert_der);

        // Update statistics
        stats.total_certs += 1;
        if is_ca {
            stats.ca_certs += 1;
        }

        true
    }

    /// Load certificates from byte slice (auto-detects PEM vs DER format)
    ///
    /// Tries to parse as PEM first, falls back to DER if that fails.
    /// Duplicate certificates are detected and only counted once.
    ///
    /// If `treat_all_as_ca` is true, all certificates are counted as CA certificates
    /// regardless of their Basic Constraints (this matches
    /// load_verify_locations with cadata parameter).
    ///
    /// If `pem_only` is true, only PEM parsing is attempted (for string input)
    pub fn load_from_bytes_ex(
        &mut self,
        data: &[u8],
        treat_all_as_ca: bool,
        pem_only: bool,
    ) -> Result<CertStats, std::io::Error> {
        let mut stats = CertStats::default();

        // Try to parse as PEM first
        let mut cursor = std::io::Cursor::new(data);
        let certs_iter = rustls_pemfile::certs(&mut cursor);

        let mut found_any = false;
        let mut first_pem_error = None; // Store first PEM parsing error
        for cert_result in certs_iter {
            match cert_result {
                Ok(cert) => {
                    found_any = true;
                    let cert_bytes = cert.to_vec();

                    // Validate that this is actually a valid X.509 certificate
                    // rustls_pemfile only does base64 decoding, not X.509 validation
                    if let Err(e) = X509Certificate::from_der(&cert_bytes) {
                        // Invalid X.509 certificate
                        return Err(cert_error::pem::parse_failed_debug(e));
                    }

                    // Add certificate using helper method (handles duplicates)
                    self.add_cert_to_store(cert_bytes, cert, treat_all_as_ca, &mut stats);
                    // Helper returns false for duplicates (skip counting)
                }
                Err(e) if !found_any => {
                    // PEM parsing failed on first certificate
                    if pem_only {
                        // For string input (PEM only), return "no start line" error
                        return Err(cert_error::pem::no_start_line(
                            "cadata does not contain a certificate",
                        ));
                    }
                    // Store the error and break to try DER format below
                    first_pem_error = Some(e);
                    break;
                }
                Err(e) => {
                    // PEM parsing failed after some certs were loaded
                    return Err(cert_error::pem::parse_failed(e));
                }
            }
        }

        // If PEM parsing found nothing, try DER format (unless pem_only)
        // DER can have multiple certificates concatenated, so parse them sequentially
        if !found_any && stats.total_certs == 0 {
            // If we had a PEM parsing error, return it instead of trying DER fallback
            // This ensures that malformed PEM files (like badcert.pem) raise an error
            if let Some(e) = first_pem_error {
                return Err(cert_error::pem::parse_failed(e));
            }

            // For PEM-only mode (string input), don't fallback to DER
            if pem_only {
                return Err(cert_error::pem::no_start_line(
                    "cadata does not contain a certificate",
                ));
            }
            let mut remaining = data;
            let mut loaded_count = 0;

            while !remaining.is_empty() {
                match X509Certificate::from_der(remaining) {
                    Ok((rest, _parsed_cert)) => {
                        // Extract the DER bytes for this certificate
                        // Length = total remaining - bytes left after parsing
                        let cert_len = remaining.len() - rest.len();
                        let cert_bytes = &remaining[..cert_len];
                        let cert_der = CertificateDer::from(cert_bytes.to_vec());

                        // Add certificate using helper method (handles duplicates)
                        self.add_cert_to_store(
                            cert_bytes.to_vec(),
                            cert_der,
                            treat_all_as_ca,
                            &mut stats,
                        );

                        loaded_count += 1;
                        remaining = rest; // Move to next certificate
                    }
                    Err(e) => {
                        if loaded_count == 0 {
                            // Failed to parse first certificate - invalid data
                            return Err(cert_error::der::not_enough_data(
                                "cadata does not contain a certificate",
                            ));
                        }
                        // Loaded some certificates but failed on subsequent data (garbage)
                        return Err(cert_error::der::parse_failed(e));
                    }
                }
            }

            // If we somehow got here with no certificates loaded
            if loaded_count == 0 {
                return Err(cert_error::der::not_enough_data(
                    "cadata does not contain a certificate",
                ));
            }
        }

        Ok(stats)
    }

    /// Load certificates from byte slice (auto-detects PEM vs DER format)
    ///
    /// This is a convenience wrapper that calls load_from_bytes_ex with treat_all_as_ca=false
    /// and pem_only=false.
    pub fn load_from_bytes(&mut self, data: &[u8]) -> Result<CertStats, std::io::Error> {
        self.load_from_bytes_ex(data, false, false)
    }
}

// NoVerifier: disables certificate verification (for CERT_NONE mode)
#[derive(Debug)]
pub struct NoVerifier;

impl ServerCertVerifier for NoVerifier {
    fn verify_server_cert(
        &self,
        _end_entity: &CertificateDer<'_>,
        _intermediates: &[CertificateDer<'_>],
        _server_name: &ServerName<'_>,
        _ocsp_response: &[u8],
        _now: UnixTime,
    ) -> Result<ServerCertVerified, rustls::Error> {
        // Accept all certificates without verification
        Ok(ServerCertVerified::assertion())
    }

    fn verify_tls12_signature(
        &self,
        message: &[u8],
        cert: &CertificateDer<'_>,
        dss: &DigitallySignedStruct,
    ) -> Result<HandshakeSignatureValid, rustls::Error> {
        rustls::crypto::verify_tls12_signature(
            message,
            cert,
            dss,
            &CryptoExt::get_provider().signature_verification_algorithms,
        )
    }

    fn verify_tls13_signature(
        &self,
        message: &[u8],
        cert: &CertificateDer<'_>,
        dss: &DigitallySignedStruct,
    ) -> Result<HandshakeSignatureValid, rustls::Error> {
        rustls::crypto::verify_tls13_signature(
            message,
            cert,
            dss,
            &CryptoExt::get_provider().signature_verification_algorithms,
        )
    }

    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
        CryptoExt::get_provider()
            .signature_verification_algorithms
            .supported_schemes()
    }
}

// HostnameIgnoringVerifier: verifies certificate chain but ignores hostname
// This is used when check_hostname=False but verify_mode != CERT_NONE
//
// Unlike the previous implementation that used an inner WebPkiServerVerifier,
// this version uses webpki directly to verify only the certificate chain,
// completely bypassing hostname verification.
#[derive(Debug)]
pub struct HostnameIgnoringVerifier {
    inner: Arc<dyn ServerCertVerifier>,
}

impl HostnameIgnoringVerifier {
    /// Create a new HostnameIgnoringVerifier with a pre-built verifier
    /// This is useful when you need to configure the verifier with CRLs or other options
    pub fn new_with_verifier(inner: Arc<dyn ServerCertVerifier>) -> Self {
        Self { inner }
    }
}

impl ServerCertVerifier for HostnameIgnoringVerifier {
    fn verify_server_cert(
        &self,
        end_entity: &CertificateDer<'_>,
        intermediates: &[CertificateDer<'_>],
        _server_name: &ServerName<'_>, // Intentionally ignored
        ocsp_response: &[u8],
        now: UnixTime,
    ) -> Result<ServerCertVerified, rustls::Error> {
        // Extract a hostname from the certificate to pass to inner verifier
        // The inner verifier will validate certificate chain, trust anchors, etc.
        // but may fail on hostname mismatch - we'll catch and ignore that error
        let dummy_hostname = extract_first_dns_name(end_entity)
            .unwrap_or_else(|| ServerName::try_from("localhost").expect("localhost is valid"));

        // Call inner verifier for full certificate validation
        match self.inner.verify_server_cert(
            end_entity,
            intermediates,
            &dummy_hostname,
            ocsp_response,
            now,
        ) {
            Ok(verified) => Ok(verified),
            Err(e) => {
                // Check if the error is a hostname mismatch
                // If so, ignore it (that's the whole point of HostnameIgnoringVerifier)
                match e {
                    rustls::Error::InvalidCertificate(
                        rustls::CertificateError::NotValidForName
                        | rustls::CertificateError::NotValidForNameContext { .. },
                    ) => {
                        // Hostname mismatch - this is expected and acceptable
                        // The certificate chain, trust anchor, and expiry are valid
                        Ok(ServerCertVerified::assertion())
                    }
                    _ => {
                        // Other errors (expired cert, untrusted CA, etc.) should propagate
                        Err(e)
                    }
                }
            }
        }
    }

    fn verify_tls12_signature(
        &self,
        message: &[u8],
        cert: &CertificateDer<'_>,
        dss: &DigitallySignedStruct,
    ) -> Result<HandshakeSignatureValid, rustls::Error> {
        self.inner.verify_tls12_signature(message, cert, dss)
    }

    fn verify_tls13_signature(
        &self,
        message: &[u8],
        cert: &CertificateDer<'_>,
        dss: &DigitallySignedStruct,
    ) -> Result<HandshakeSignatureValid, rustls::Error> {
        self.inner.verify_tls13_signature(message, cert, dss)
    }

    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
        self.inner.supported_verify_schemes()
    }
}

// Helper function to extract the first DNS name from a certificate
fn extract_first_dns_name(cert_der: &CertificateDer<'_>) -> Option<ServerName<'static>> {
    let (_, cert) = X509Certificate::from_der(cert_der.as_ref()).ok()?;

    // Try Subject Alternative Names first
    if let Ok(Some(san_ext)) = cert.subject_alternative_name() {
        for name in &san_ext.value.general_names {
            if let x509_parser::extensions::GeneralName::DNSName(dns) = name {
                // Remove wildcard prefix if present (e.g., "*.example.com" → "example.com")
                // This allows us to use the domain for certificate chain verification
                // when check_hostname=False
                let dns_str = dns.to_string();
                let normalized_dns = normalize_wildcard_hostname(&dns_str);

                match ServerName::try_from(normalized_dns.to_string()) {
                    Ok(server_name) => {
                        return Some(server_name);
                    }
                    Err(_e) => {
                        // Continue to next
                    }
                }
            }
        }
    }

    // Fallback to Common Name
    for rdn in cert.subject().iter() {
        for attr in rdn.iter() {
            if attr.attr_type() == &x509_parser::oid_registry::OID_X509_COMMON_NAME
                && let Ok(cn) = attr.attr_value().as_str()
            {
                // Remove wildcard prefix if present
                let normalized_cn = normalize_wildcard_hostname(cn);

                match ServerName::try_from(normalized_cn.to_string()) {
                    Ok(server_name) => {
                        return Some(server_name);
                    }
                    Err(_e) => {}
                }
            }
        }
    }

    None
}

// Custom client certificate verifier for TLS 1.3 deferred validation
// This verifier always succeeds during handshake but stores verification errors
// for later retrieval during I/O operations
#[derive(Debug)]
pub struct DeferredClientCertVerifier {
    // The actual verifier that performs validation
    inner: Arc<dyn ClientCertVerifier>,
    // Shared storage for deferred error message
    deferred_error: Arc<ParkingRwLock<Option<String>>>,
}

impl DeferredClientCertVerifier {
    pub fn new(
        inner: Arc<dyn ClientCertVerifier>,
        deferred_error: Arc<ParkingRwLock<Option<String>>>,
    ) -> Self {
        Self {
            inner,
            deferred_error,
        }
    }
}

impl ClientCertVerifier for DeferredClientCertVerifier {
    fn offer_client_auth(&self) -> bool {
        self.inner.offer_client_auth()
    }

    fn client_auth_mandatory(&self) -> bool {
        // Delegate to inner verifier to respect CERT_REQUIRED mode
        // This ensures client certificates are mandatory when verify_mode=CERT_REQUIRED
        self.inner.client_auth_mandatory()
    }

    fn root_hint_subjects(&self) -> &[rustls::DistinguishedName] {
        self.inner.root_hint_subjects()
    }

    fn verify_client_cert(
        &self,
        end_entity: &CertificateDer<'_>,
        intermediates: &[CertificateDer<'_>],
        now: UnixTime,
    ) -> Result<ClientCertVerified, rustls::Error> {
        // Perform the actual verification
        let result = self
            .inner
            .verify_client_cert(end_entity, intermediates, now);

        // If verification failed, store the error for the server's Python code
        // AND return the error so rustls sends the appropriate TLS alert
        if let Err(ref e) = result {
            let error_msg = format!("certificate verify failed: {e}");
            *self.deferred_error.write() = Some(error_msg);
            // Return the error to rustls so it sends the alert to the client
            return result;
        }

        result
    }

    fn verify_tls12_signature(
        &self,
        message: &[u8],
        cert: &CertificateDer<'_>,
        dss: &DigitallySignedStruct,
    ) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
        self.inner.verify_tls12_signature(message, cert, dss)
    }

    fn verify_tls13_signature(
        &self,
        message: &[u8],
        cert: &CertificateDer<'_>,
        dss: &DigitallySignedStruct,
    ) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
        self.inner.verify_tls13_signature(message, cert, dss)
    }

    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
        self.inner.supported_verify_schemes()
    }
}

// Public Utility Functions

/// Load certificate chain and private key from files
///
/// This function loads a certificate chain from `cert_path` and a private key
/// from `key_path`. If `password` is provided, it will be used to decrypt
/// an encrypted private key.
///
/// Returns (certificate_chain, private_key) on success.
///
/// # Arguments
/// * `cert_path` - Path to certificate file (PEM or DER format)
/// * `key_path` - Path to private key file (PEM or DER format, optionally encrypted)
/// * `password` - Optional password for encrypted private key
///
/// # Errors
/// Returns error if:
/// - Files cannot be read
/// - Certificate or key cannot be parsed
/// - Password is incorrect for encrypted key
pub fn load_cert_chain_from_file(
    cert_path: &str,
    key_path: &str,
    password: Option<&str>,
) -> Result<(Vec<CertificateDer<'static>>, PrivateKeyDer<'static>), Box<dyn core::error::Error>> {
    // Load certificate file - preserve io::Error for errno
    let cert_contents = crate::fs::read(cert_path)?;

    // Parse certificates (PEM format)
    let mut cert_cursor = std::io::Cursor::new(&cert_contents);
    let certs: Vec<CertificateDer<'static>> = rustls_pemfile::certs(&mut cert_cursor)
        .collect::<Result<Vec<_>, _>>()
        .map_err(cert_error::pem::parse_failed)?;

    if certs.is_empty() {
        return Err(Box::new(cert_error::pem::invalid_cert()));
    }

    // Load private key file - preserve io::Error for errno
    let key_contents = crate::fs::read(key_path)?;

    // Parse private key (supports PKCS8, RSA, EC formats)
    let private_key = if let Some(pwd) = password {
        // Try to parse as encrypted PKCS#8
        use der::SecretDocument;
        use pkcs8::EncryptedPrivateKeyInfoRef;
        use rustls::pki_types::{PrivateKeyDer, PrivatePkcs8KeyDer};

        let pem_str = String::from_utf8_lossy(&key_contents);

        // Extract just the ENCRYPTED PRIVATE KEY block if present
        // (file may contain multiple PEM blocks like key + certificate)
        let encrypted_key_pem = if let Some(start) =
            pem_str.find("-----BEGIN ENCRYPTED PRIVATE KEY-----")
        {
            if let Some(end_marker) = pem_str[start..].find("-----END ENCRYPTED PRIVATE KEY-----") {
                let end = start + end_marker + "-----END ENCRYPTED PRIVATE KEY-----".len();
                Some(&pem_str[start..end])
            } else {
                None
            }
        } else {
            None
        };

        // Try to decode and decrypt PEM-encoded encrypted private key using pkcs8's PEM support
        let decrypted_key_result = if let Some(key_pem) = encrypted_key_pem {
            match SecretDocument::from_pem(key_pem) {
                Ok((label, doc)) => {
                    if label == "ENCRYPTED PRIVATE KEY" {
                        // Parse encrypted key info from DER
                        match EncryptedPrivateKeyInfoRef::try_from(doc.as_bytes()) {
                            Ok(encrypted_key) => {
                                // Decrypt with password
                                match encrypted_key.decrypt(pwd.as_bytes()) {
                                    Ok(decrypted) => {
                                        // Convert decrypted SecretDocument to PrivateKeyDer
                                        let key_vec: Vec<u8> = decrypted.as_bytes().to_vec();
                                        let pkcs8_key: PrivatePkcs8KeyDer<'static> = key_vec.into();
                                        Some(PrivateKeyDer::Pkcs8(pkcs8_key))
                                    }
                                    Err(e) => {
                                        return Err(Box::new(cert_error::key::decrypt_failed(e)));
                                    }
                                }
                            }
                            Err(e) => {
                                return Err(Box::new(cert_error::key::parse_encrypted_failed(e)));
                            }
                        }
                    } else {
                        None
                    }
                }
                Err(_) => None,
            }
        } else {
            None
        };

        match decrypted_key_result {
            Some(key) => key,
            None => {
                // Not encrypted PKCS#8, try as unencrypted key
                // (password might have been provided for an unencrypted key)
                let mut key_cursor = std::io::Cursor::new(&key_contents);
                match rustls_pemfile::private_key(&mut key_cursor) {
                    Ok(Some(key)) => key,
                    Ok(None) => {
                        return Err(Box::new(cert_error::key::not_found("key file")));
                    }
                    Err(e) => {
                        return Err(Box::new(cert_error::key::parse_failed(e)));
                    }
                }
            }
        }
    } else {
        // No password provided - try to parse unencrypted key
        let mut key_cursor = std::io::Cursor::new(&key_contents);
        match rustls_pemfile::private_key(&mut key_cursor) {
            Ok(Some(key)) => key,
            Ok(None) => {
                return Err(Box::new(cert_error::key::not_found("key file")));
            }
            Err(e) => {
                return Err(Box::new(cert_error::key::parse_failed(e)));
            }
        }
    };

    Ok((certs, private_key))
}

/// Validate that a certificate and private key match
///
/// This function checks that the public key in the certificate matches
/// the provided private key. This is a basic sanity check to prevent
/// configuration errors.
///
/// # Arguments
/// * `certs` - Certificate chain (first certificate is the leaf)
/// * `private_key` - Private key to validate against
///
/// # Errors
/// Returns error if:
/// - Certificate chain is empty
/// - Public key extraction fails
/// - Keys don't match
///
/// Note: This is a simplified validation. Full validation would require
/// signing and verifying a test message, which is complex with rustls.
pub fn validate_cert_key_match(
    certs: &[CertificateDer<'_>],
    private_key: &PrivateKeyDer<'_>,
) -> Result<(), String> {
    if certs.is_empty() {
        return Err("Certificate chain is empty".to_string());
    }

    // For rustls, the actual validation happens when creating CertifiedKey
    // We can attempt to create a signing key to verify the key is valid
    match CryptoExt::get_ext().any_supported_key(private_key) {
        Ok(_signing_key) => {
            // If we can create a signing key, the private key is valid
            // Rustls will validate the cert-key match when building config
            Ok(())
        }
        Err(_) => Err("PEM lib".to_string()),
    }
}

/// StrictCertVerifier: wraps a ServerCertVerifier and adds RFC 5280 strict validation
///
/// When VERIFY_X509_STRICT flag is set, performs additional validation:
/// - Checks for Authority Key Identifier (AKI) extension (required by RFC 5280 Section 4.2.1.1)
/// - Validates other RFC 5280 compliance requirements
///
/// This matches X509_V_FLAG_X509_STRICT behavior in OpenSSL.
#[derive(Debug)]
pub struct StrictCertVerifier {
    inner: Arc<dyn ServerCertVerifier>,
    verify_flags: i32,
}

impl StrictCertVerifier {
    /// Create a new StrictCertVerifier
    ///
    /// # Arguments
    /// * `inner` - The underlying verifier to wrap
    /// * `verify_flags` - SSL verification flags (e.g., VERIFY_X509_STRICT)
    pub fn new(inner: Arc<dyn ServerCertVerifier>, verify_flags: i32) -> Self {
        Self {
            inner,
            verify_flags,
        }
    }

    /// Check if a certificate has the Authority Key Identifier extension
    ///
    /// RFC 5280 Section 4.2.1.1 states that conforming CAs MUST include this
    /// extension in all certificates except self-signed certificates.
    fn check_aki_present(cert_der: &[u8]) -> Result<(), String> {
        let (_, cert) = X509Certificate::from_der(cert_der)
            .map_err(|e| format!("Failed to parse certificate: {e}"))?;

        // Check for Authority Key Identifier extension (OID 2.5.29.35)
        let has_aki = cert
            .tbs_certificate
            .extensions()
            .iter()
            .any(|ext| ext.oid == oid_registry::OID_X509_EXT_AUTHORITY_KEY_IDENTIFIER);

        if !has_aki {
            return Err(
                "certificate verification failed: certificate missing required Authority Key Identifier extension"
                    .to_string(),
            );
        }

        Ok(())
    }
}

impl ServerCertVerifier for StrictCertVerifier {
    fn verify_server_cert(
        &self,
        end_entity: &CertificateDer<'_>,
        intermediates: &[CertificateDer<'_>],
        server_name: &ServerName<'_>,
        ocsp_response: &[u8],
        now: UnixTime,
    ) -> Result<ServerCertVerified, rustls::Error> {
        // First, perform the standard verification
        let result = self.inner.verify_server_cert(
            end_entity,
            intermediates,
            server_name,
            ocsp_response,
            now,
        )?;

        // If VERIFY_X509_STRICT flag is set, perform additional validation
        if self.verify_flags & VERIFY_X509_STRICT != 0 {
            // Check end entity certificate for AKI
            // RFC 5280 Section 4.2.1.1: self-signed certificates are exempt from AKI requirement
            if !is_self_signed(end_entity) {
                Self::check_aki_present(end_entity.as_ref())
                    .map_err(cert_error::to_rustls_invalid_cert)?;
            }

            // Check intermediate certificates for AKI
            for intermediate in intermediates {
                Self::check_aki_present(intermediate.as_ref())
                    .map_err(cert_error::to_rustls_invalid_cert)?;
            }
        }

        Ok(result)
    }

    fn verify_tls12_signature(
        &self,
        message: &[u8],
        cert: &CertificateDer<'_>,
        dss: &DigitallySignedStruct,
    ) -> Result<HandshakeSignatureValid, rustls::Error> {
        self.inner.verify_tls12_signature(message, cert, dss)
    }

    fn verify_tls13_signature(
        &self,
        message: &[u8],
        cert: &CertificateDer<'_>,
        dss: &DigitallySignedStruct,
    ) -> Result<HandshakeSignatureValid, rustls::Error> {
        self.inner.verify_tls13_signature(message, cert, dss)
    }

    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
        self.inner.supported_verify_schemes()
    }
}

/// EmptyRootStoreVerifier: used when verify_mode != CERT_NONE but no CA certs are loaded
///
/// This verifier always fails certificate verification with UnknownIssuer error,
/// when no root certificates are available.
/// This allows the SSL context to be created successfully, but handshake will fail
/// with a proper SSLCertVerificationError (verify_code=20, UNABLE_TO_GET_ISSUER_CERT_LOCALLY).
#[derive(Debug)]
pub struct EmptyRootStoreVerifier;

impl ServerCertVerifier for EmptyRootStoreVerifier {
    fn verify_server_cert(
        &self,
        _end_entity: &CertificateDer<'_>,
        _intermediates: &[CertificateDer<'_>],
        _server_name: &ServerName<'_>,
        _ocsp_response: &[u8],
        _now: UnixTime,
    ) -> Result<ServerCertVerified, rustls::Error> {
        // Always fail with UnknownIssuer -  when no CA certs loaded
        // This will be mapped to X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY (20)
        Err(rustls::Error::InvalidCertificate(
            rustls::CertificateError::UnknownIssuer,
        ))
    }

    fn verify_tls12_signature(
        &self,
        _message: &[u8],
        _cert: &CertificateDer<'_>,
        _dss: &DigitallySignedStruct,
    ) -> Result<HandshakeSignatureValid, rustls::Error> {
        // Accept signatures during handshake - the cert verification will fail anyway
        Ok(HandshakeSignatureValid::assertion())
    }

    fn verify_tls13_signature(
        &self,
        _message: &[u8],
        _cert: &CertificateDer<'_>,
        _dss: &DigitallySignedStruct,
    ) -> Result<HandshakeSignatureValid, rustls::Error> {
        // Accept signatures during handshake - the cert verification will fail anyway
        Ok(HandshakeSignatureValid::assertion())
    }

    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
        ALL_SIGNATURE_SCHEMES.to_vec()
    }
}

/// CRLCheckVerifier: Wraps a verifier to enforce CRL checking when flags are set
///
/// This verifier ensures that when CRL checking flags are set (VERIFY_CRL_CHECK_LEAF = 4)
/// but no CRLs have been loaded, the verification fails with UnknownRevocationStatus.
/// This matches X509_V_FLAG_CRL_CHECK without loaded CRLs
/// causes "unable to get CRL" error.
#[derive(Debug)]
pub struct CRLCheckVerifier {
    inner: Arc<dyn ServerCertVerifier>,
    has_crls: bool,
    crl_check_enabled: bool,
}

impl CRLCheckVerifier {
    pub fn new(
        inner: Arc<dyn ServerCertVerifier>,
        has_crls: bool,
        crl_check_enabled: bool,
    ) -> Self {
        Self {
            inner,
            has_crls,
            crl_check_enabled,
        }
    }
}

impl ServerCertVerifier for CRLCheckVerifier {
    fn verify_server_cert(
        &self,
        end_entity: &CertificateDer<'_>,
        intermediates: &[CertificateDer<'_>],
        server_name: &ServerName<'_>,
        ocsp_response: &[u8],
        now: UnixTime,
    ) -> Result<ServerCertVerified, rustls::Error> {
        // If CRL checking is enabled but no CRLs are loaded, fail with UnknownRevocationStatus
        // X509_V_ERR_UNABLE_TO_GET_CRL (3)
        if self.crl_check_enabled && !self.has_crls {
            return Err(rustls::Error::InvalidCertificate(
                rustls::CertificateError::UnknownRevocationStatus,
            ));
        }

        // Otherwise, delegate to inner verifier
        self.inner
            .verify_server_cert(end_entity, intermediates, server_name, ocsp_response, now)
    }

    fn verify_tls12_signature(
        &self,
        message: &[u8],
        cert: &CertificateDer<'_>,
        dss: &DigitallySignedStruct,
    ) -> Result<HandshakeSignatureValid, rustls::Error> {
        self.inner.verify_tls12_signature(message, cert, dss)
    }

    fn verify_tls13_signature(
        &self,
        message: &[u8],
        cert: &CertificateDer<'_>,
        dss: &DigitallySignedStruct,
    ) -> Result<HandshakeSignatureValid, rustls::Error> {
        self.inner.verify_tls13_signature(message, cert, dss)
    }

    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
        self.inner.supported_verify_schemes()
    }
}

/// Partial Chain Verifier - Handles VERIFY_X509_PARTIAL_CHAIN flag
///
/// OpenSSL's X509_V_FLAG_PARTIAL_CHAIN allows verification to succeed if any certificate
/// in the presented chain is found in the trust store, not just the root CA. This is useful
/// for trusting intermediate certificates or self-signed certificates directly.
///
/// rustls's WebPkiServerVerifier doesn't support this behavior by default, so we wrap it
/// to add partial chain support when the flag is set.
///
/// Behavior:
/// 1. Try standard verification first (full chain to trusted root)
/// 2. If that fails and VERIFY_X509_PARTIAL_CHAIN is set:
///    - Check if the end-entity certificate is in the trust store
///    - If yes, accept the certificate as trusted
///
/// This matches accepting self-signed certificates that
/// are explicitly loaded via load_verify_locations().
#[derive(Debug)]
pub struct PartialChainVerifier {
    inner: Arc<dyn ServerCertVerifier>,
    ca_certs_der: Vec<Vec<u8>>,
    verify_flags: i32,
    check_common_name: bool,
}

impl PartialChainVerifier {
    pub fn new(
        inner: Arc<dyn ServerCertVerifier>,
        ca_certs_der: Vec<Vec<u8>>,
        verify_flags: i32,
        check_common_name: bool,
    ) -> Self {
        Self {
            inner,
            ca_certs_der,
            verify_flags,
            check_common_name,
        }
    }
}

impl ServerCertVerifier for PartialChainVerifier {
    fn verify_server_cert(
        &self,
        end_entity: &CertificateDer<'_>,
        intermediates: &[CertificateDer<'_>],
        server_name: &ServerName<'_>,
        ocsp_response: &[u8],
        now: UnixTime,
    ) -> Result<ServerCertVerified, rustls::Error> {
        // Try standard verification first
        match self.inner.verify_server_cert(
            end_entity,
            intermediates,
            server_name,
            ocsp_response,
            now,
        ) {
            Ok(result) => Ok(result),
            Err(e) => {
                // If verification failed, check if the end-entity certificate is in the trust store
                // OpenSSL behavior:
                // 1. Self-signed certs in trust store: ALWAYS trusted (flag not required)
                // 2. Non-self-signed end-entity certs in trust store: require VERIFY_X509_PARTIAL_CHAIN
                // 3. Intermediate certs in trust store: require VERIFY_X509_PARTIAL_CHAIN
                let end_entity_der = end_entity.as_ref();
                if self
                    .ca_certs_der
                    .iter()
                    .any(|cert_der| cert_der.as_slice() == end_entity_der)
                {
                    // End-entity certificate is in the trust store
                    // Check if this is a self-signed certificate
                    let is_self_signed_cert = is_self_signed(end_entity);

                    // Self-signed: always trust (OpenSSL behavior)
                    // Non-self-signed: require VERIFY_X509_PARTIAL_CHAIN flag
                    if is_self_signed_cert || (self.verify_flags & VERIFY_X509_PARTIAL_CHAIN != 0) {
                        // Certificate is trusted, but still perform hostname verification
                        verify_hostname(end_entity, server_name, self.check_common_name)?;
                        return Ok(ServerCertVerified::assertion());
                    }
                }
                // No match found or non-self-signed without flag - return original error
                Err(e)
            }
        }
    }

    fn verify_tls12_signature(
        &self,
        message: &[u8],
        cert: &CertificateDer<'_>,
        dss: &DigitallySignedStruct,
    ) -> Result<HandshakeSignatureValid, rustls::Error> {
        self.inner.verify_tls12_signature(message, cert, dss)
    }

    fn verify_tls13_signature(
        &self,
        message: &[u8],
        cert: &CertificateDer<'_>,
        dss: &DigitallySignedStruct,
    ) -> Result<HandshakeSignatureValid, rustls::Error> {
        self.inner.verify_tls13_signature(message, cert, dss)
    }

    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
        self.inner.supported_verify_schemes()
    }
}

// Hostname Verification:

/// Check if a certificate is self-signed by comparing issuer and subject.
/// Returns true if the certificate is self-signed (issuer == subject).
fn is_self_signed(cert_der: &CertificateDer<'_>) -> bool {
    use x509_parser::prelude::*;

    // Parse the certificate
    let Ok((_, cert)) = X509Certificate::from_der(cert_der.as_ref()) else {
        // If we can't parse it, assume it's not self-signed (conservative approach)
        return false;
    };

    // Compare issuer and subject
    // A certificate is self-signed if issuer == subject
    cert.issuer() == cert.subject()
}

/// True when the certificate advertises at least one dNSName SAN.
fn cert_has_dns_san(cert: &X509Certificate<'_>) -> bool {
    use x509_parser::extensions::GeneralName;
    cert.subject_alternative_name()
        .ok()
        .flatten()
        .is_some_and(|san| {
            san.value
                .general_names
                .iter()
                .any(|name| matches!(name, GeneralName::DNSName(_)))
        })
}

/// rustls checks SAN only. When no dNSName SAN is present and CN matching
/// is enabled, accept a Common Name that matches the requested hostname.
#[derive(Debug)]
pub struct CommonNameFallbackVerifier {
    inner: Arc<dyn ServerCertVerifier>,
}

impl CommonNameFallbackVerifier {
    pub fn new(inner: Arc<dyn ServerCertVerifier>) -> Self {
        Self { inner }
    }
}

impl ServerCertVerifier for CommonNameFallbackVerifier {
    fn verify_server_cert(
        &self,
        end_entity: &CertificateDer<'_>,
        intermediates: &[CertificateDer<'_>],
        server_name: &ServerName<'_>,
        ocsp_response: &[u8],
        now: UnixTime,
    ) -> Result<ServerCertVerified, rustls::Error> {
        match self.inner.verify_server_cert(
            end_entity,
            intermediates,
            server_name,
            ocsp_response,
            now,
        ) {
            Ok(verified) => Ok(verified),
            Err(
                e @ rustls::Error::InvalidCertificate(
                    rustls::CertificateError::NotValidForName
                    | rustls::CertificateError::NotValidForNameContext { .. },
                ),
            ) => {
                verify_hostname(end_entity, server_name, true).map_err(|_| e)?;
                Ok(ServerCertVerified::assertion())
            }
            Err(error) => Err(error),
        }
    }

    fn verify_tls12_signature(
        &self,
        message: &[u8],
        cert: &CertificateDer<'_>,
        dss: &DigitallySignedStruct,
    ) -> Result<HandshakeSignatureValid, rustls::Error> {
        self.inner.verify_tls12_signature(message, cert, dss)
    }

    fn verify_tls13_signature(
        &self,
        message: &[u8],
        cert: &CertificateDer<'_>,
        dss: &DigitallySignedStruct,
    ) -> Result<HandshakeSignatureValid, rustls::Error> {
        self.inner.verify_tls13_signature(message, cert, dss)
    }

    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
        self.inner.supported_verify_schemes()
    }
}

/// Verify that a certificate is valid for the given hostname/IP address.
/// SAN dNSName entries take precedence. Common Name is used only when
/// `check_common_name` is set and the certificate has no dNSName SAN.
fn verify_hostname(
    cert_der: &CertificateDer<'_>,
    server_name: &ServerName<'_>,
    check_common_name: bool,
) -> Result<(), rustls::Error> {
    use x509_parser::extensions::GeneralName;
    use x509_parser::prelude::*;

    // Parse the certificate
    let (_, cert) = X509Certificate::from_der(cert_der.as_ref()).map_err(|e| {
        cert_error::to_rustls_invalid_cert(format!(
            "Failed to parse certificate for hostname verification: {e}"
        ))
    })?;

    match server_name {
        ServerName::DnsName(dns) => {
            let expected_name = dns.as_ref();
            let has_dns_san = cert_has_dns_san(&cert);

            if has_dns_san {
                if let Ok(Some(san_ext)) = cert.subject_alternative_name() {
                    for name in &san_ext.value.general_names {
                        if let GeneralName::DNSName(dns_name) = name
                            && hostname_matches(expected_name, dns_name)
                        {
                            return Ok(());
                        }
                    }
                }
            } else if check_common_name {
                for rdn in cert.subject().iter() {
                    for attr in rdn.iter() {
                        if attr.attr_type() == &x509_parser::oid_registry::OID_X509_COMMON_NAME
                            && let Ok(cn) = attr.attr_value().as_str()
                            && hostname_matches(expected_name, cn)
                        {
                            return Ok(());
                        }
                    }
                }
            }

            Err(cert_error::to_rustls_invalid_cert(format!(
                "Hostname mismatch: certificate is not valid for '{expected_name}'",
            )))
        }
        ServerName::IpAddress(ip) => verify_ip_address(&cert, ip),
        _ => {
            // Unknown server name type
            Err(cert_error::to_rustls_cert_error(
                std::io::ErrorKind::InvalidInput,
                "Unsupported server name type for hostname verification",
            ))
        }
    }
}

/// Match a hostname against a pattern, supporting wildcard certificates (*.example.com).
/// Implements RFC 6125 wildcard matching rules:
/// - Wildcard must be in the leftmost label
/// - Wildcard must be the only character in that label
/// - Wildcard must match at least one character
fn hostname_matches(expected: &str, pattern: &str) -> bool {
    // Wildcard matching for *.example.com
    if let Some(pattern_base) = pattern.strip_prefix("*.") {
        // Find the first dot in expected hostname
        if let Some(dot_pos) = expected.find('.') {
            let expected_base = &expected[dot_pos + 1..];

            // The base domains must match (case insensitive)
            // and the leftmost label must not be empty
            return dot_pos > 0 && expected_base.eq_ignore_ascii_case(pattern_base);
        }

        // No dot in expected, can't match wildcard
        return false;
    }

    // Exact match (case insensitive per RFC 4343)
    expected.eq_ignore_ascii_case(pattern)
}

/// Verify that a certificate is valid for the given IP address.
/// Checks Subject Alternative Names for IP Address entries.
fn verify_ip_address(
    cert: &X509Certificate<'_>,
    expected_ip: &rustls::pki_types::IpAddr,
) -> Result<(), rustls::Error> {
    use core::net::IpAddr;
    use x509_parser::extensions::GeneralName;

    // Convert rustls IpAddr to std::net::IpAddr for comparison
    let expected_std_ip: IpAddr = match expected_ip {
        rustls::pki_types::IpAddr::V4(octets) => IpAddr::V4(core::net::Ipv4Addr::from(*octets)),
        rustls::pki_types::IpAddr::V6(octets) => IpAddr::V6(core::net::Ipv6Addr::from(*octets)),
    };

    // Check Subject Alternative Names for IP addresses
    if let Ok(Some(san_ext)) = cert.subject_alternative_name() {
        for name in &san_ext.value.general_names {
            if let GeneralName::IPAddress(cert_ip_bytes) = name {
                // Parse the IP address from the certificate
                let cert_ip = match cert_ip_bytes.len() {
                    4 => {
                        // IPv4
                        if let Ok(octets) = <[u8; 4]>::try_from(*cert_ip_bytes) {
                            IpAddr::V4(core::net::Ipv4Addr::from(octets))
                        } else {
                            continue;
                        }
                    }
                    16 => {
                        // IPv6
                        if let Ok(octets) = <[u8; 16]>::try_from(*cert_ip_bytes) {
                            IpAddr::V6(core::net::Ipv6Addr::from(octets))
                        } else {
                            continue;
                        }
                    }
                    _ => continue, // Invalid IP address length
                };

                if cert_ip == expected_std_ip {
                    return Ok(());
                }
            }
        }
    }

    // No matching IP address found
    Err(cert_error::to_rustls_invalid_cert(format!(
        "IP address mismatch: certificate is not valid for '{expected_std_ip}'",
    )))
}