rustls 0.24.0-dev.1

Rustls is a modern TLS library written in Rust.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
//! Error types used throughout rustls.

use alloc::format;
use alloc::string::String;
use alloc::vec::Vec;
use core::ops::Deref;
use core::{fmt, mem};
use std::time::SystemTimeError;

use pki_types::{AlgorithmIdentifier, EchConfigListBytes, ServerName, UnixTime};
#[cfg(feature = "webpki")]
use webpki::ExtendedKeyUsage;

use crate::common_state::maybe_send_fatal_alert;
use crate::conn::SendPath;
use crate::crypto::kx::KeyExchangeAlgorithm;
use crate::crypto::{CipherSuite, GetRandomFailed, InconsistentKeys};
use crate::enums::{ContentType, HandshakeType};
use crate::msgs::{Codec, EchConfigPayload};

#[cfg(test)]
mod tests;

/// rustls reports protocol errors using this type.
#[non_exhaustive]
#[derive(Debug, PartialEq, Clone)]
pub enum Error {
    /// We received a TLS message that isn't valid right now.
    /// `expect_types` lists the message types we can expect right now.
    /// `got_type` is the type we found.  This error is typically
    /// caused by a buggy TLS stack (the peer or this one), a broken
    /// network, or an attack.
    InappropriateMessage {
        /// Which types we expected
        expect_types: Vec<ContentType>,
        /// What type we received
        got_type: ContentType,
    },

    /// We received a TLS handshake message that isn't valid right now.
    /// `expect_types` lists the handshake message types we can expect
    /// right now.  `got_type` is the type we found.
    InappropriateHandshakeMessage {
        /// Which handshake type we expected
        expect_types: Vec<HandshakeType>,
        /// What handshake type we received
        got_type: HandshakeType,
    },

    /// An error occurred while handling Encrypted Client Hello (ECH).
    InvalidEncryptedClientHello(EncryptedClientHelloError),

    /// The peer sent us a TLS message with invalid contents.
    InvalidMessage(InvalidMessage),

    /// The certificate verifier doesn't support the given type of name.
    UnsupportedNameType,

    /// We couldn't decrypt a message.  This is invariably fatal.
    DecryptError,

    /// We couldn't encrypt a message because it was larger than the allowed message size.
    /// This should never happen if the application is using valid record sizes.
    EncryptError,

    /// The peer doesn't support a protocol version/feature we require.
    /// The parameter gives a hint as to what version/feature it is.
    PeerIncompatible(PeerIncompatible),

    /// The peer deviated from the standard TLS protocol.
    /// The parameter gives a hint where.
    PeerMisbehaved(PeerMisbehaved),

    /// We received a fatal alert.  This means the peer is unhappy.
    AlertReceived(AlertDescription),

    /// We saw an invalid certificate.
    ///
    /// The contained error is from the certificate validation trait
    /// implementation.
    InvalidCertificate(CertificateError),

    /// A provided certificate revocation list (CRL) was invalid.
    InvalidCertRevocationList(CertRevocationListError),

    /// A catch-all error for unlikely errors.
    General(String),

    /// We failed to figure out what time it currently is.
    FailedToGetCurrentTime,

    /// We failed to acquire random bytes from the system.
    FailedToGetRandomBytes,

    /// This function doesn't work until the TLS handshake
    /// is complete.
    HandshakeNotComplete,

    /// The peer sent an oversized record/fragment.
    PeerSentOversizedRecord,

    /// An incoming connection did not support any known application protocol.
    NoApplicationProtocol,

    /// The server certificate resolver didn't find an appropriate certificate.
    NoSuitableCertificate,

    /// The `max_fragment_size` value supplied in configuration was too small,
    /// or too large.
    BadMaxFragmentSize,

    /// Specific failure cases from [`Credentials::new()`] or a
    /// [`crate::crypto::SigningKey`] that cannot produce a corresponding public key.
    ///
    /// If encountered while building a [`Credentials`], consider if
    /// [`Credentials::new_unchecked()`] might be appropriate for your use case.
    ///
    /// [`Credentials::new()`]: crate::crypto::Credentials::new()
    /// [`Credentials`]: crate::crypto::Credentials
    /// [`Credentials::new_unchecked()`]: crate::crypto::Credentials::new_unchecked()
    InconsistentKeys(InconsistentKeys),

    /// The server rejected encrypted client hello (ECH) negotiation
    ///
    /// It may have returned new ECH configurations that could be used to retry negotiation
    /// with a fresh connection.
    ///
    /// See [`RejectedEch::can_retry()`] and [`crate::client::EchConfig::for_retry()`].
    RejectedEch(RejectedEch),

    /// Errors of this variant should never be produced by the library.
    ///
    /// Please file a bug if you see one.
    Unreachable(&'static str),

    /// The caller misused the API
    ///
    /// Generally we try to make error cases like this unnecessary by embedding
    /// the constraints in the type system, so misuses simply do not compile.  But,
    /// for cases where that is not possible or exceptionally costly, we return errors
    /// of this variant.
    ///
    /// This only results from the ordering, dependencies or parameter values of calls,
    /// so (assuming parameter values are fixed) these can be determined and fixed by
    /// reading the code.  They are never caused by the values of untrusted data, or
    /// other non-determinism.
    ApiMisuse(ApiMisuse),

    /// Any other error.
    ///
    /// This variant should only be used when the error is not better described by a more
    /// specific variant. For example, if a custom crypto provider returns a
    /// provider specific error.
    ///
    /// Enums holding this variant will never compare equal to each other.
    Other(OtherError),
}

/// Determine which alert should be sent for a given error.
///
/// If this mapping fails, no alert is sent.
impl TryFrom<&Error> for AlertDescription {
    type Error = ();

    fn try_from(error: &Error) -> Result<Self, Self::Error> {
        Ok(match error {
            Error::DecryptError => Self::BadRecordMac,
            Error::InappropriateMessage { .. } | Error::InappropriateHandshakeMessage { .. } => {
                Self::UnexpectedMessage
            }
            Error::InvalidCertificate(e) => Self::from(e),
            Error::InvalidMessage(e) => Self::from(*e),
            Error::NoApplicationProtocol => Self::NoApplicationProtocol,
            Error::PeerMisbehaved(e) => Self::from(*e),
            Error::PeerIncompatible(e) => Self::from(*e),
            Error::PeerSentOversizedRecord => Self::RecordOverflow,
            Error::RejectedEch(_) => Self::EncryptedClientHelloRequired,

            _ => return Err(()),
        })
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InappropriateMessage {
                expect_types,
                got_type,
            } => write!(
                f,
                "received unexpected message: got {:?} when expecting {}",
                got_type,
                join::<ContentType>(expect_types)
            ),
            Self::InappropriateHandshakeMessage {
                expect_types,
                got_type,
            } => write!(
                f,
                "received unexpected handshake message: got {:?} when expecting {}",
                got_type,
                join::<HandshakeType>(expect_types)
            ),
            Self::InvalidMessage(typ) => {
                write!(f, "received corrupt message of type {typ:?}")
            }
            Self::PeerIncompatible(why) => write!(f, "peer is incompatible: {why:?}"),
            Self::PeerMisbehaved(why) => write!(f, "peer misbehaved: {why:?}"),
            Self::AlertReceived(alert) => write!(f, "received fatal alert: the peer {alert}"),
            Self::InvalidCertificate(err) => {
                write!(f, "invalid peer certificate: {err}")
            }
            Self::InvalidCertRevocationList(err) => {
                write!(f, "invalid certificate revocation list: {err:?}")
            }
            Self::UnsupportedNameType => write!(f, "presented server name type wasn't supported"),
            Self::DecryptError => write!(f, "cannot decrypt peer's message"),
            Self::InvalidEncryptedClientHello(err) => {
                write!(f, "encrypted client hello failure: {err:?}")
            }
            Self::EncryptError => write!(f, "cannot encrypt message"),
            Self::PeerSentOversizedRecord => write!(f, "peer sent excess record size"),
            Self::HandshakeNotComplete => write!(f, "handshake not complete"),
            Self::NoApplicationProtocol => write!(f, "peer doesn't support any known protocol"),
            Self::NoSuitableCertificate => write!(f, "no suitable certificate found"),
            Self::FailedToGetCurrentTime => write!(f, "failed to get current time"),
            Self::FailedToGetRandomBytes => write!(f, "failed to get random bytes"),
            Self::BadMaxFragmentSize => {
                write!(f, "the supplied max_fragment_size was too small or large")
            }
            Self::InconsistentKeys(why) => {
                write!(f, "keys may not be consistent: {why:?}")
            }
            Self::RejectedEch(why) => {
                write!(
                    f,
                    "server rejected encrypted client hello (ECH) {} retry configs",
                    if why.can_retry() { "with" } else { "without" }
                )
            }
            Self::General(err) => write!(f, "unexpected error: {err}"),
            Self::Unreachable(err) => write!(
                f,
                "unreachable condition: {err} (please file a bug in rustls)"
            ),
            Self::ApiMisuse(why) => write!(f, "API misuse: {why:?}"),
            Self::Other(err) => write!(f, "other error: {err}"),
        }
    }
}

impl From<CertificateError> for Error {
    #[inline]
    fn from(e: CertificateError) -> Self {
        Self::InvalidCertificate(e)
    }
}

impl From<InvalidMessage> for Error {
    #[inline]
    fn from(e: InvalidMessage) -> Self {
        Self::InvalidMessage(e)
    }
}

impl From<PeerMisbehaved> for Error {
    #[inline]
    fn from(e: PeerMisbehaved) -> Self {
        Self::PeerMisbehaved(e)
    }
}

impl From<PeerIncompatible> for Error {
    #[inline]
    fn from(e: PeerIncompatible) -> Self {
        Self::PeerIncompatible(e)
    }
}

impl From<CertRevocationListError> for Error {
    #[inline]
    fn from(e: CertRevocationListError) -> Self {
        Self::InvalidCertRevocationList(e)
    }
}

impl From<EncryptedClientHelloError> for Error {
    #[inline]
    fn from(e: EncryptedClientHelloError) -> Self {
        Self::InvalidEncryptedClientHello(e)
    }
}

impl From<RejectedEch> for Error {
    fn from(rejected_error: RejectedEch) -> Self {
        Self::RejectedEch(rejected_error)
    }
}

impl From<ApiMisuse> for Error {
    fn from(e: ApiMisuse) -> Self {
        Self::ApiMisuse(e)
    }
}

impl From<OtherError> for Error {
    fn from(value: OtherError) -> Self {
        Self::Other(value)
    }
}

impl From<InconsistentKeys> for Error {
    #[inline]
    fn from(e: InconsistentKeys) -> Self {
        Self::InconsistentKeys(e)
    }
}

impl From<SystemTimeError> for Error {
    #[inline]
    fn from(_: SystemTimeError) -> Self {
        Self::FailedToGetCurrentTime
    }
}

impl From<GetRandomFailed> for Error {
    fn from(_: GetRandomFailed) -> Self {
        Self::FailedToGetRandomBytes
    }
}

impl core::error::Error for Error {}

/// The ways in which certificate validators can express errors.
///
/// Note that the rustls TLS protocol code interprets specifically these
/// error codes to send specific TLS alerts.  Therefore, if a
/// custom certificate validator uses incorrect errors the library as
/// a whole will send alerts that do not match the standard (this is usually
/// a minor issue, but could be misleading).
#[non_exhaustive]
#[derive(Debug, Clone)]
pub enum CertificateError {
    /// The certificate is not correctly encoded.
    BadEncoding,

    /// The current time is after the `notAfter` time in the certificate.
    Expired,

    /// The current time is after the `notAfter` time in the certificate.
    ///
    /// This variant is semantically the same as `Expired`, but includes
    /// extra data to improve error reports.
    ExpiredContext {
        /// The validation time.
        time: UnixTime,
        /// The `notAfter` time of the certificate.
        not_after: UnixTime,
    },

    /// The current time is before the `notBefore` time in the certificate.
    NotValidYet,

    /// The current time is before the `notBefore` time in the certificate.
    ///
    /// This variant is semantically the same as `NotValidYet`, but includes
    /// extra data to improve error reports.
    NotValidYetContext {
        /// The validation time.
        time: UnixTime,
        /// The `notBefore` time of the certificate.
        not_before: UnixTime,
    },

    /// The certificate has been revoked.
    Revoked,

    /// The certificate contains an extension marked critical, but it was
    /// not processed by the certificate validator.
    UnhandledCriticalExtension,

    /// The certificate chain is not issued by a known root certificate.
    UnknownIssuer,

    /// The certificate's revocation status could not be determined.
    UnknownRevocationStatus,

    /// The certificate's revocation status could not be determined, because the CRL is expired.
    ExpiredRevocationList,

    /// The certificate's revocation status could not be determined, because the CRL is expired.
    ///
    /// This variant is semantically the same as `ExpiredRevocationList`, but includes
    /// extra data to improve error reports.
    ExpiredRevocationListContext {
        /// The validation time.
        time: UnixTime,
        /// The nextUpdate time of the CRL.
        next_update: UnixTime,
    },

    /// A certificate is not correctly signed by the key of its alleged
    /// issuer.
    BadSignature,

    /// A signature inside a certificate or on a handshake was made with an unsupported algorithm.
    UnsupportedSignatureAlgorithm {
        /// The signature algorithm OID that was unsupported.
        signature_algorithm_id: Vec<u8>,
        /// Supported algorithms that were available for signature verification.
        supported_algorithms: Vec<AlgorithmIdentifier>,
    },

    /// A signature was made with an algorithm that doesn't match the relevant public key.
    UnsupportedSignatureAlgorithmForPublicKey {
        /// The signature algorithm OID.
        signature_algorithm_id: Vec<u8>,
        /// The public key algorithm OID.
        public_key_algorithm_id: Vec<u8>,
    },

    /// The subject names in an end-entity certificate do not include
    /// the expected name.
    NotValidForName,

    /// The subject names in an end-entity certificate do not include
    /// the expected name.
    ///
    /// This variant is semantically the same as `NotValidForName`, but includes
    /// extra data to improve error reports.
    NotValidForNameContext {
        /// Expected server name.
        expected: ServerName<'static>,

        /// The names presented in the end entity certificate.
        ///
        /// These are the subject names as present in the leaf certificate and may contain DNS names
        /// with or without a wildcard label as well as IP address names.
        presented: Vec<String>,
    },

    /// The certificate is being used for a different purpose than allowed.
    InvalidPurpose,

    /// The certificate is being used for a different purpose than allowed.
    ///
    /// This variant is semantically the same as `InvalidPurpose`, but includes
    /// extra data to improve error reports.
    InvalidPurposeContext {
        /// Extended key purpose that was required by the application.
        required: ExtendedKeyPurpose,
        /// Extended key purposes that were presented in the peer's certificate.
        presented: Vec<ExtendedKeyPurpose>,
    },

    /// The OCSP response provided to the verifier was invalid.
    ///
    /// This should be returned from [`ServerVerifier::verify_identity()`]
    /// when a verifier checks its `ocsp_response` parameter and finds it invalid.
    ///
    /// This maps to [`AlertDescription::BadCertificateStatusResponse`].
    ///
    /// [`ServerVerifier::verify_identity()`]: crate::client::danger::ServerVerifier::verify_identity
    InvalidOcspResponse,

    /// The certificate is valid, but the handshake is rejected for other
    /// reasons.
    ApplicationVerificationFailure,

    /// Any other error.
    ///
    /// This can be used by custom verifiers to expose the underlying error
    /// (where they are not better described by the more specific errors
    /// above).
    ///
    /// It is also used by the default verifier in case its error is
    /// not covered by the above common cases.
    ///
    /// Enums holding this variant will never compare equal to each other.
    Other(OtherError),
}

impl PartialEq<Self> for CertificateError {
    fn eq(&self, other: &Self) -> bool {
        use CertificateError::*;
        match (self, other) {
            (BadEncoding, BadEncoding) => true,
            (Expired, Expired) => true,
            (
                ExpiredContext {
                    time: left_time,
                    not_after: left_not_after,
                },
                ExpiredContext {
                    time: right_time,
                    not_after: right_not_after,
                },
            ) => (left_time, left_not_after) == (right_time, right_not_after),
            (NotValidYet, NotValidYet) => true,
            (
                NotValidYetContext {
                    time: left_time,
                    not_before: left_not_before,
                },
                NotValidYetContext {
                    time: right_time,
                    not_before: right_not_before,
                },
            ) => (left_time, left_not_before) == (right_time, right_not_before),
            (Revoked, Revoked) => true,
            (UnhandledCriticalExtension, UnhandledCriticalExtension) => true,
            (UnknownIssuer, UnknownIssuer) => true,
            (BadSignature, BadSignature) => true,
            (
                UnsupportedSignatureAlgorithm {
                    signature_algorithm_id: left_signature_algorithm_id,
                    supported_algorithms: left_supported_algorithms,
                },
                UnsupportedSignatureAlgorithm {
                    signature_algorithm_id: right_signature_algorithm_id,
                    supported_algorithms: right_supported_algorithms,
                },
            ) => {
                (left_signature_algorithm_id, left_supported_algorithms)
                    == (right_signature_algorithm_id, right_supported_algorithms)
            }
            (
                UnsupportedSignatureAlgorithmForPublicKey {
                    signature_algorithm_id: left_signature_algorithm_id,
                    public_key_algorithm_id: left_public_key_algorithm_id,
                },
                UnsupportedSignatureAlgorithmForPublicKey {
                    signature_algorithm_id: right_signature_algorithm_id,
                    public_key_algorithm_id: right_public_key_algorithm_id,
                },
            ) => {
                (left_signature_algorithm_id, left_public_key_algorithm_id)
                    == (right_signature_algorithm_id, right_public_key_algorithm_id)
            }
            (NotValidForName, NotValidForName) => true,
            (
                NotValidForNameContext {
                    expected: left_expected,
                    presented: left_presented,
                },
                NotValidForNameContext {
                    expected: right_expected,
                    presented: right_presented,
                },
            ) => (left_expected, left_presented) == (right_expected, right_presented),
            (InvalidPurpose, InvalidPurpose) => true,
            (
                InvalidPurposeContext {
                    required: left_required,
                    presented: left_presented,
                },
                InvalidPurposeContext {
                    required: right_required,
                    presented: right_presented,
                },
            ) => (left_required, left_presented) == (right_required, right_presented),
            (InvalidOcspResponse, InvalidOcspResponse) => true,
            (ApplicationVerificationFailure, ApplicationVerificationFailure) => true,
            (UnknownRevocationStatus, UnknownRevocationStatus) => true,
            (ExpiredRevocationList, ExpiredRevocationList) => true,
            (
                ExpiredRevocationListContext {
                    time: left_time,
                    next_update: left_next_update,
                },
                ExpiredRevocationListContext {
                    time: right_time,
                    next_update: right_next_update,
                },
            ) => (left_time, left_next_update) == (right_time, right_next_update),
            _ => false,
        }
    }
}

// The following mapping are heavily referenced in:
// * [OpenSSL Implementation](https://github.com/openssl/openssl/blob/45bb98bfa223efd3258f445ad443f878011450f0/ssl/statem/statem_lib.c#L1434)
// * [BoringSSL Implementation](https://github.com/google/boringssl/blob/583c60bd4bf76d61b2634a58bcda99a92de106cb/ssl/ssl_x509.cc#L1323)
impl From<&CertificateError> for AlertDescription {
    fn from(e: &CertificateError) -> Self {
        use CertificateError::*;
        match e {
            BadEncoding
            | UnhandledCriticalExtension
            | NotValidForName
            | NotValidForNameContext { .. } => Self::BadCertificate,
            // RFC 5246/RFC 8446
            // certificate_expired
            //  A certificate has expired or **is not currently valid**.
            Expired | ExpiredContext { .. } | NotValidYet | NotValidYetContext { .. } => {
                Self::CertificateExpired
            }
            Revoked => Self::CertificateRevoked,
            // OpenSSL, BoringSSL and AWS-LC all generate an Unknown CA alert for
            // the case where revocation status can not be determined, so we do the same here.
            UnknownIssuer
            | UnknownRevocationStatus
            | ExpiredRevocationList
            | ExpiredRevocationListContext { .. } => Self::UnknownCa,
            InvalidOcspResponse => Self::BadCertificateStatusResponse,
            BadSignature
            | UnsupportedSignatureAlgorithm { .. }
            | UnsupportedSignatureAlgorithmForPublicKey { .. } => Self::DecryptError,
            InvalidPurpose | InvalidPurposeContext { .. } => Self::UnsupportedCertificate,
            ApplicationVerificationFailure => Self::AccessDenied,
            // RFC 5246/RFC 8446
            // certificate_unknown
            //  Some other (unspecified) issue arose in processing the
            //  certificate, rendering it unacceptable.
            Other(..) => Self::CertificateUnknown,
        }
    }
}

impl fmt::Display for CertificateError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::NotValidForNameContext {
                expected,
                presented,
            } => {
                write!(
                    f,
                    "certificate not valid for name {:?}; certificate ",
                    expected.to_str()
                )?;

                match presented.as_slice() {
                    &[] => write!(
                        f,
                        "is not valid for any names (according to its subjectAltName extension)"
                    ),
                    [one] => write!(f, "is only valid for {one}"),
                    many => {
                        write!(f, "is only valid for ")?;

                        let n = many.len();
                        let all_but_last = &many[..n - 1];
                        let last = &many[n - 1];

                        for (i, name) in all_but_last.iter().enumerate() {
                            write!(f, "{name}")?;
                            if i < n - 2 {
                                write!(f, ", ")?;
                            }
                        }
                        write!(f, " or {last}")
                    }
                }
            }

            Self::ExpiredContext { time, not_after } => write!(
                f,
                "certificate expired: verification time {} (UNIX), \
                 but certificate is not valid after {} \
                 ({} seconds ago)",
                time.as_secs(),
                not_after.as_secs(),
                time.as_secs()
                    .saturating_sub(not_after.as_secs())
            ),

            Self::NotValidYetContext { time, not_before } => write!(
                f,
                "certificate not valid yet: verification time {} (UNIX), \
                 but certificate is not valid before {} \
                 ({} seconds in future)",
                time.as_secs(),
                not_before.as_secs(),
                not_before
                    .as_secs()
                    .saturating_sub(time.as_secs())
            ),

            Self::ExpiredRevocationListContext { time, next_update } => write!(
                f,
                "certificate revocation list expired: \
                 verification time {} (UNIX), \
                 but CRL is not valid after {} \
                 ({} seconds ago)",
                time.as_secs(),
                next_update.as_secs(),
                time.as_secs()
                    .saturating_sub(next_update.as_secs())
            ),

            Self::InvalidPurposeContext {
                required,
                presented,
            } => {
                write!(
                    f,
                    "certificate does not allow extended key usage for {required}, allows "
                )?;
                for (i, eku) in presented.iter().enumerate() {
                    if i > 0 {
                        write!(f, ", ")?;
                    }
                    write!(f, "{eku}")?;
                }
                Ok(())
            }

            Self::Other(other) => write!(f, "{other}"),

            other => write!(f, "{other:?}"),
        }
    }
}

enum_builder! {
    /// The `AlertDescription` TLS protocol enum.  Values in this enum are taken
    /// from the various RFCs covering TLS, and are listed by IANA.
    ///
    /// The list of alerts is available at
    /// <https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#tls-parameters-6>.
    pub struct AlertDescription(pub u8);

    enum AlertDescriptionName {
        /// Notifies the recipient that the sender will not send any more messages on this connection.
        ///
        /// <https://www.rfc-editor.org/info/rfc9846/#section-6.1-2.2.1>
        CloseNotify => 0x00,

        /// An inappropriate message was received.
        ///
        /// E.g., the wrong handshake message, premature Application Data, etc.
        /// This alert should never be observed in communication between proper implementations.
        ///
        /// <https://www.rfc-editor.org/info/rfc9846/#section-6.2-4.2.1>
        UnexpectedMessage => 0x0a,

        /// This alert is returned if a record is received which cannot be deprotected.
        ///
        /// Because AEAD algorithms combine decryption and verification,
        /// and also to avoid side-channel attacks,
        /// this alert is used for all deprotection failures.
        /// This alert should never be observed in communication between proper implementations,
        /// except when messages were corrupted in the network.
        ///
        /// <https://www.rfc-editor.org/info/rfc9846/#section-6.2-4.4.1>
        BadRecordMac => 0x14,

        /// Reserved. Used in TLS versions prior to 1.3.
        ///
        /// According to TLS 1.2 specification at <https://www.rfc-editor.org/info/rfc5246/>
        /// "This alert was used in some earlier versions of TLS, and may have
        /// permitted certain attacks against the CBC mode.
        /// It MUST NOT be sent by compliant implementations."
        DecryptionFailed => 0x15,

        /// TLS record larger than the limit was received.
        ///
        /// A TLSCiphertext record was received that had a length more than 214 + 256 bytes,
        /// or a record decrypted to a TLSPlaintext record with more than 214 bytes
        /// (or some other negotiated limit).
        /// This alert should never be observed in communication between proper implementations,
        /// except when messages were corrupted in the network.
        ///
        /// <https://www.rfc-editor.org/info/rfc9846/#section-6.2-4.6.1>
        RecordOverflow => 0x16,

        /// Reserved. Used in TLS versions prior to 1.3.
        ///
        /// The decompression function received improper input
        /// (e.g., data that would expand to excessive length).
        /// This message is always fatal and should never be observed
        /// in communication between proper implementations.
        ///
        /// <https://www.rfc-editor.org/info/rfc5246/>
        DecompressionFailure => 0x1e,

        /// The sender was unable to negotiate an acceptable set of security parameters.
        ///
        /// <https://www.rfc-editor.org/info/rfc9846/#section-6.2-4.8.1>
        HandshakeFailure => 0x28,

        /// Reserved. Used in SSLv3 but not in TLS.
        NoCertificate => 0x29,

        /// A certificate was corrupt, contained signatures that did not verify correctly, etc.
        ///
        /// <https://www.rfc-editor.org/info/rfc9846/#section-6.2-4.10.1>
        BadCertificate => 0x2a,

        /// A certificate was of an unsupported type.
        ///
        /// <https://www.rfc-editor.org/info/rfc9846/#section-6.2-4.12.1>
        UnsupportedCertificate => 0x2b,

        /// A certificate was revoked by its signer.
        ///
        /// <https://www.rfc-editor.org/info/rfc9846/#section-6.2-4.14.1>
        CertificateRevoked => 0x2c,

        /// A certificate has expired or is not currently valid.
        ///
        /// <https://www.rfc-editor.org/info/rfc9846/#section-6.2-4.16.1>
        CertificateExpired => 0x2d,

        /// Unspecified issue arose in processing the certificate, rendering it unacceptable.
        ///
        /// <https://www.rfc-editor.org/info/rfc9846/#section-6.2-4.18.1>
        CertificateUnknown => 0x2e,

        /// A field in the handshake was incorrect or inconsistent with other fields.
        ///
        /// This alert is used for errors which conform to the formal protocol syntax
        /// but are otherwise incorrect.
        ///
        /// <https://www.rfc-editor.org/info/rfc9846/#section-6.2-4.20.1>
        IllegalParameter => 0x2f,

        /// The CA certificate could not be located or could not be matched with a known trust anchor.
        ///
        /// <https://www.rfc-editor.org/info/rfc9846/#section-6.2-4.22.1>
        UnknownCa => 0x30,

        /// A valid certificate or PSK was received, but did not pass access control.
        ///
        /// <https://www.rfc-editor.org/info/rfc9846/#section-6.2-4.24.1>
        AccessDenied => 0x31,

        /// A message could not be decoded.
        ///
        /// Some field was out of the specified range
        /// or the length of the message was incorrect.
        /// This alert is used for errors where the message does not conform
        /// to the formal protocol syntax.
        /// This alert should never be observed in communication between proper implementations,
        /// except when messages were corrupted in the network.
        ///
        /// <https://www.rfc-editor.org/info/rfc9846/#section-6.2-4.26.1>
        DecodeError => 0x32,

        /// A handshake (not record layer) cryptographic operation failed.
        ///
        /// <https://www.rfc-editor.org/info/rfc9846/#section-6.2-4.28.1>
        DecryptError => 0x33,

        /// Reserved. Used in TLS 1.0 but not TLS 1.1 or later.
        ExportRestriction => 0x3c,

        /// Peer has attempted to negotiate a recognized but not supported protocol version.
        ///
        /// <https://www.rfc-editor.org/info/rfc9846/#section-6.2-4.30.1>
        ProtocolVersion => 0x46,

        /// The server requires parameters more secure than those supported by the client.
        ///
        /// <https://www.rfc-editor.org/info/rfc9846/#section-6.2-4.32.1>
        InsufficientSecurity => 0x47,

        /// An internal error unrelated to the peer or the correctness of the protocol.
        ///
        /// <https://www.rfc-editor.org/info/rfc9846/#section-6.2-4.34.1>
        InternalError => 0x50,

        /// Sent by a server in response to an invalid connection retry attempt from a client.
        ///
        /// <https://www.rfc-editor.org/info/rfc9846/#section-6.2-4.36.1>
        InappropriateFallback => 0x56,

        /// The sender is canceling the handshake for some reason unrelated to a protocol failure.
        ///
        /// <https://www.rfc-editor.org/info/rfc9846/#section-6.1-2.4.1>
        UserCanceled => 0x5a,

        /// Reserved. Used in TLS versions prior to 1.3.
        ///
        /// See TLS 1.2 specification at <https://www.rfc-editor.org/info/rfc5246/>
        /// for the description.
        NoRenegotiation => 0x64,

        /// A handshake message does not contain an extension that is mandatory to send.
        ///
        /// <https://www.rfc-editor.org/info/rfc9846/#section-6.2-4.38.1>
        MissingExtension => 0x6d,

        /// Received an extension not offered in ClientHello or CertificateRequest.
        ///
        /// <https://www.rfc-editor.org/info/rfc9846/#section-6.2-4.38.1>
        UnsupportedExtension => 0x6e,

        /// The server is unable to obtain certificate sent as an URL by the client.
        ///
        /// <https://datatracker.ietf.org/doc/html/rfc6066>
        CertificateUnobtainable => 0x6f,

        /// The server does not recognize SNI sent by the client.
        ///
        /// <https://datatracker.ietf.org/doc/html/rfc6066>
        UnrecognizedName => 0x70,

        /// <https://datatracker.ietf.org/doc/html/rfc6066>
        BadCertificateStatusResponse => 0x71,

        /// Reserved. Used in TLS versions prior to 1.3.
        ///
        /// <https://datatracker.ietf.org/doc/html/rfc6066>
        BadCertificateHashValue => 0x72,

        /// The server does not recognize PSK identity.
        ///
        /// <https://datatracker.ietf.org/doc/html/rfc4279>
        UnknownPskIdentity => 0x73,

        /// A client certificate is desired but none was provided by the client.
        ///
        /// <https://datatracker.ietf.org/doc/html/rfc9846#section-6.2-4.48.1>
        CertificateRequired => 0x74,

        /// A client ALPN extension advertises only protocols that the server does not support.
        ///
        /// <https://datatracker.ietf.org/doc/html/rfc9846#section-6.2-4.52.1>
        NoApplicationProtocol => 0x78,

        /// Use of Encrypted Client Hello is required.
        ///
        /// <https://datatracker.ietf.org/doc/html/rfc9849#section-11.2>
        EncryptedClientHelloRequired => 0x79,
    }
}

impl fmt::Display for AlertDescription {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let Ok(known) = AlertDescriptionName::try_from(*self) else {
            return write!(f, "sent an unknown alert (0x{:02x?})", self.0);
        };

        // these should be:
        // - in past tense
        // - be syntactically correct if prefaced with 'the peer' to describe
        //   received alerts
        match known {
            // this is normal.
            AlertDescriptionName::CloseNotify => write!(f, "cleanly closed the connection"),

            // these are abnormal.  they are usually symptomatic of an interop failure.
            // please file a bug report.
            AlertDescriptionName::UnexpectedMessage => write!(f, "received an unexpected message"),
            AlertDescriptionName::BadRecordMac => write!(f, "failed to verify a message"),
            AlertDescriptionName::RecordOverflow => write!(f, "rejected an over-length message"),
            AlertDescriptionName::IllegalParameter => write!(
                f,
                "rejected a message because a field was incorrect or inconsistent"
            ),
            AlertDescriptionName::DecodeError => write!(f, "failed to decode a message"),
            AlertDescriptionName::DecryptError => {
                write!(f, "failed to perform a handshake cryptographic operation")
            }
            AlertDescriptionName::InappropriateFallback => {
                write!(f, "detected an attempted version downgrade")
            }
            AlertDescriptionName::MissingExtension => {
                write!(f, "required a specific extension that was not provided")
            }
            AlertDescriptionName::UnsupportedExtension => {
                write!(f, "rejected an unsolicited extension")
            }

            // these are deprecated by TLS1.3 and should be very rare (but possible
            // with TLS1.2 or earlier peers)
            AlertDescriptionName::DecryptionFailed => write!(f, "failed to decrypt a message"),
            AlertDescriptionName::DecompressionFailure => {
                write!(f, "failed to decompress a message")
            }
            AlertDescriptionName::NoCertificate => write!(f, "found no certificate"),
            AlertDescriptionName::ExportRestriction => {
                write!(f, "refused due to export restrictions")
            }
            AlertDescriptionName::NoRenegotiation => {
                write!(f, "rejected an attempt at renegotiation")
            }
            AlertDescriptionName::CertificateUnobtainable => {
                write!(f, "failed to retrieve its certificate")
            }
            AlertDescriptionName::BadCertificateHashValue => {
                write!(f, "rejected the `certificate_hash` extension")
            }

            // this is fairly normal. it means a server cannot choose compatible parameters
            // given our offer.  please use ssllabs.com or similar to investigate what parameters
            // the server supports.
            AlertDescriptionName::HandshakeFailure => write!(
                f,
                "failed to negotiate an acceptable set of security parameters"
            ),
            AlertDescriptionName::ProtocolVersion => {
                write!(f, "did not support a suitable TLS version")
            }
            AlertDescriptionName::InsufficientSecurity => {
                write!(f, "required a higher security level than was offered")
            }

            // these usually indicate a local misconfiguration, either in certificate selection
            // or issuance.
            AlertDescriptionName::BadCertificate => {
                write!(
                    f,
                    "rejected the certificate as corrupt or incorrectly signed"
                )
            }
            AlertDescriptionName::UnsupportedCertificate => {
                write!(f, "did not support the certificate")
            }
            AlertDescriptionName::CertificateRevoked => {
                write!(f, "found the certificate to be revoked")
            }
            AlertDescriptionName::CertificateExpired => {
                write!(f, "found the certificate to be expired")
            }
            AlertDescriptionName::CertificateUnknown => {
                write!(f, "rejected the certificate for an unspecified reason")
            }
            AlertDescriptionName::UnknownCa => {
                write!(f, "found the certificate was not issued by a trusted CA")
            }
            AlertDescriptionName::BadCertificateStatusResponse => {
                write!(f, "rejected the certificate status response")
            }
            // typically this means client authentication is required, in TLS1.2...
            AlertDescriptionName::AccessDenied => write!(f, "denied access"),
            // and in TLS1.3...
            AlertDescriptionName::CertificateRequired => {
                write!(f, "required a client certificate")
            }

            AlertDescriptionName::InternalError => write!(f, "encountered an internal error"),
            AlertDescriptionName::UserCanceled => write!(f, "canceled the handshake"),

            // rejection of SNI (uncommon; usually servers behave as if it was not sent)
            AlertDescriptionName::UnrecognizedName => {
                write!(f, "did not recognize a name in the `server_name` extension")
            }

            // rejection of PSK connections (NYI in this library); indicates a local
            // misconfiguration.
            AlertDescriptionName::UnknownPskIdentity => {
                write!(f, "did not recognize any offered PSK identity")
            }

            // rejection of ALPN (varying levels of support, but missing support is
            // often dangerous if the peers fail to agree on the same protocol)
            AlertDescriptionName::NoApplicationProtocol => write!(
                f,
                "did not support any of the offered application protocols"
            ),

            // ECH requirement by clients, see
            // <https://datatracker.ietf.org/doc/html/rfc9849#name-update-of-the-tls-alert-reg>
            AlertDescriptionName::EncryptedClientHelloRequired => {
                write!(f, "required use of encrypted client hello")
            }
        }
    }
}

/// A corrupt TLS message payload that resulted in an error.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum InvalidMessage {
    /// A certificate payload exceeded rustls's 64KB limit
    CertificatePayloadTooLarge,
    /// An advertised message was larger then expected.
    HandshakePayloadTooLarge,
    /// The peer sent us a syntactically incorrect ChangeCipherSpec payload.
    InvalidCcs,
    /// An unknown content type was encountered during message decoding.
    InvalidContentType,
    /// A peer sent an invalid certificate status type
    InvalidCertificateStatusType,
    /// Context was incorrectly attached to a certificate request during a handshake.
    InvalidCertRequest,
    /// A peer's DH params could not be decoded
    InvalidDhParams,
    /// A message was zero-length when its record kind forbids it.
    InvalidEmptyPayload,
    /// A peer sent an unexpected key update request.
    InvalidKeyUpdate,
    /// A peer's server name could not be decoded
    InvalidServerName,
    /// A TLS message payload was larger then allowed by the specification.
    MessageTooLarge,
    /// Message is shorter than the expected length
    MessageTooShort,
    /// Missing data for the named handshake payload value
    MissingData(&'static str),
    /// A peer did not advertise its supported key exchange groups.
    MissingKeyExchange,
    /// A peer sent an empty list of signature schemes
    NoSignatureSchemes,
    /// Trailing data found for the named handshake payload value
    TrailingData(&'static str),
    /// A peer sent an unexpected message type.
    UnexpectedMessage(&'static str),
    /// An unknown TLS protocol was encountered during message decoding.
    UnknownProtocolVersion,
    /// A peer sent a non-null compression method.
    UnsupportedCompression,
    /// A peer sent an unknown elliptic curve type.
    UnsupportedCurveType,
    /// A peer sent an unsupported key exchange algorithm.
    UnsupportedKeyExchangeAlgorithm(KeyExchangeAlgorithm),
    /// A server sent an empty ticket
    EmptyTicketValue,
    /// A peer sent an empty list of items, but a non-empty list is required.
    ///
    /// The argument names the context.
    IllegalEmptyList(&'static str),
    /// A peer sent a message where a given extension type was repeated
    DuplicateExtension(u16),
    /// A peer sent a message with a PSK offer extension in wrong position
    PreSharedKeyIsNotFinalExtension,
    /// A server sent a HelloRetryRequest with an unknown extension
    UnknownHelloRetryRequestExtension,
    /// The peer sent a TLS1.3 Certificate with an unknown extension
    UnknownCertificateExtension,
}

impl From<InvalidMessage> for AlertDescription {
    fn from(e: InvalidMessage) -> Self {
        match e {
            InvalidMessage::PreSharedKeyIsNotFinalExtension => Self::IllegalParameter,
            InvalidMessage::DuplicateExtension(_) => Self::IllegalParameter,
            InvalidMessage::UnknownHelloRetryRequestExtension => Self::UnsupportedExtension,
            InvalidMessage::CertificatePayloadTooLarge => Self::BadCertificate,
            _ => Self::DecodeError,
        }
    }
}

/// The set of cases where we failed to make a connection because we thought
/// the peer was misbehaving.
///
/// This is `non_exhaustive`: we might add or stop using items here in minor
/// versions.  We also don't document what they mean.  Generally a user of
/// rustls shouldn't vary its behaviour on these error codes, and there is
/// nothing it can do to improve matters.
///
/// Please file a bug against rustls if you see `Error::PeerMisbehaved` in
/// the wild.
#[expect(missing_docs)]
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PeerMisbehaved {
    AttemptedDowngradeToTls12WhenTls13IsSupported,
    BadCertChainExtensions,
    DisallowedEncryptedExtension,
    DuplicateClientHelloExtensions,
    DuplicateEncryptedExtensions,
    DuplicateHelloRetryRequestExtensions,
    DuplicateNewSessionTicketExtensions,
    DuplicateServerHelloExtensions,
    DuplicateServerNameTypes,
    EarlyDataAttemptedInSecondClientHello,
    EarlyDataExtensionWithoutResumption,
    EarlyDataOfferedWithVariedCipherSuite,
    EmptyFragment,
    HandshakeHashVariedAfterRetry,
    /// Received an alert with an undefined level and the given [`AlertDescription`]
    IllegalAlertLevel(u8, AlertDescription),
    IllegalHelloRetryRequestWithEmptyCookie,
    IllegalHelloRetryRequestWithNoChanges,
    IllegalHelloRetryRequestWithOfferedGroup,
    IllegalHelloRetryRequestWithUnofferedCipherSuite,
    IllegalHelloRetryRequestWithUnofferedNamedGroup,
    IllegalHelloRetryRequestWithUnsupportedVersion,
    IllegalHelloRetryRequestWithWrongSessionId,
    IllegalHelloRetryRequestWithInvalidEch,
    IllegalMiddleboxChangeCipherSpec,
    IllegalTlsInnerPlaintext,
    /// Received a warning alert with the given [`AlertDescription`]
    IllegalWarningAlert(AlertDescription),
    IncorrectBinder,
    IncorrectFinished,
    InvalidCertCompression,
    InvalidMaxEarlyDataSize,
    InvalidKeyShare,
    KeyEpochWithPendingFragment,
    KeyUpdateReceivedInQuicConnection,
    MessageInterleavedWithHandshakeMessage,
    MissingBinderInPskExtension,
    MissingKeyShare,
    MissingPskModesExtension,
    MissingQuicTransportParameters,
    NoCertificatesPresented,
    OfferedDuplicateCertificateCompressions,
    OfferedDuplicateKeyShares,
    OfferedEarlyDataWithOldProtocolVersion,
    OfferedEmptyApplicationProtocol,
    OfferedIncorrectCompressions,
    PskExtensionMustBeLast,
    PskExtensionWithMismatchedIdsAndBinders,
    RefusedToFollowHelloRetryRequest,
    RejectedEarlyDataInterleavedWithHandshakeMessage,
    ResumptionAttemptedWithVariedEms,
    ResumptionOfferedWithVariedCipherSuite,
    ResumptionOfferedWithVariedEms,
    ResumptionOfferedWithIncompatibleCipherSuite,
    SelectedDifferentCipherSuiteAfterRetry,
    SelectedInvalidPsk,
    SelectedTls12UsingTls13VersionExtension,
    SelectedUnofferedApplicationProtocol,
    SelectedUnofferedCertCompression,
    SelectedUnofferedCipherSuite,
    SelectedUnofferedCompression,
    SelectedUnofferedKxGroup,
    SelectedUnofferedPsk,
    ServerEchoedCompatibilitySessionId,
    ServerHelloMustOfferUncompressedEcPoints,
    ServerNameDifferedOnRetry,
    ServerNameMustContainOneHostName,
    SignedKxWithWrongAlgorithm,
    SignedHandshakeWithUnadvertisedSigScheme,
    TooManyEmptyFragments,
    TooManyConsecutiveHandshakeMessagesAfterHandshake,
    TooManyRenegotiationRequests,
    TooManyWarningAlertsReceived,
    TooMuchEarlyDataReceived,
    UnexpectedCleartextExtension,
    UnsolicitedCertExtension,
    UnsolicitedEncryptedExtension,
    UnsolicitedSctList,
    UnsolicitedServerHelloExtension,
    WrongGroupForKeyShare,
    UnsolicitedEchExtension,
}

impl From<PeerMisbehaved> for AlertDescription {
    fn from(e: PeerMisbehaved) -> Self {
        match e {
            PeerMisbehaved::DisallowedEncryptedExtension
            | PeerMisbehaved::IllegalHelloRetryRequestWithInvalidEch
            | PeerMisbehaved::UnexpectedCleartextExtension
            | PeerMisbehaved::UnsolicitedEchExtension
            | PeerMisbehaved::UnsolicitedEncryptedExtension
            | PeerMisbehaved::UnsolicitedServerHelloExtension => Self::UnsupportedExtension,

            PeerMisbehaved::IllegalMiddleboxChangeCipherSpec
            | PeerMisbehaved::KeyEpochWithPendingFragment
            | PeerMisbehaved::KeyUpdateReceivedInQuicConnection => Self::UnexpectedMessage,

            PeerMisbehaved::IllegalWarningAlert(_) => Self::DecodeError,

            PeerMisbehaved::IncorrectBinder | PeerMisbehaved::IncorrectFinished => {
                Self::DecryptError
            }

            PeerMisbehaved::InvalidCertCompression
            | PeerMisbehaved::SelectedUnofferedCertCompression => Self::BadCertificate,

            PeerMisbehaved::MissingKeyShare
            | PeerMisbehaved::MissingPskModesExtension
            | PeerMisbehaved::MissingQuicTransportParameters => Self::MissingExtension,

            PeerMisbehaved::NoCertificatesPresented => Self::CertificateRequired,

            _ => Self::IllegalParameter,
        }
    }
}

/// The set of cases where we failed to make a connection because a peer
/// doesn't support a TLS version/feature we require.
///
/// This is `non_exhaustive`: we might add or stop using items here in minor
/// versions.
#[expect(missing_docs)]
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PeerIncompatible {
    EcPointsExtensionRequired,
    ExtendedMasterSecretExtensionRequired,
    IncorrectCertificateTypeExtension,
    KeyShareExtensionRequired,
    MultipleRawKeys,
    NamedGroupsExtensionRequired,
    NoCertificateRequestSignatureSchemesInCommon,
    NoCipherSuitesInCommon,
    NoEcPointFormatsInCommon,
    NoKxGroupsInCommon,
    NoSignatureSchemesInCommon,
    NoServerNameProvided,
    NullCompressionRequired,
    ServerDoesNotSupportTls12Or13,
    ServerSentHelloRetryRequestWithUnknownExtension,
    ServerTlsVersionIsDisabledByOurConfig,
    SignatureAlgorithmsExtensionRequired,
    SupportedVersionsExtensionRequired,
    Tls12NotOffered,
    Tls12NotOfferedOrEnabled,
    Tls13RequiredForQuic,
    UncompressedEcPointsRequired,
    UnknownCertificateType(u8),
    UnsolicitedCertificateTypeExtension,
}

impl From<PeerIncompatible> for AlertDescription {
    fn from(e: PeerIncompatible) -> Self {
        match e {
            PeerIncompatible::NullCompressionRequired => Self::IllegalParameter,

            PeerIncompatible::ServerTlsVersionIsDisabledByOurConfig
            | PeerIncompatible::SupportedVersionsExtensionRequired
            | PeerIncompatible::Tls12NotOffered
            | PeerIncompatible::Tls12NotOfferedOrEnabled
            | PeerIncompatible::Tls13RequiredForQuic => Self::ProtocolVersion,

            PeerIncompatible::UnknownCertificateType(_) => Self::UnsupportedCertificate,

            _ => Self::HandshakeFailure,
        }
    }
}

/// Extended Key Usage (EKU) purpose values.
///
/// These are usually represented as OID values in the certificate's extension (if present), but
/// we represent the values that are most relevant to rustls as named enum variants.
#[non_exhaustive]
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ExtendedKeyPurpose {
    /// Client authentication
    ClientAuth,
    /// Server authentication
    ServerAuth,
    /// Other EKU values
    ///
    /// Represented here as a `Vec<usize>` for human readability.
    Other(Vec<usize>),
}

impl ExtendedKeyPurpose {
    #[cfg(feature = "webpki")]
    pub(crate) fn for_values(values: impl Iterator<Item = usize>) -> Self {
        let values = values.collect::<Vec<_>>();
        match &*values {
            ExtendedKeyUsage::CLIENT_AUTH_REPR => Self::ClientAuth,
            ExtendedKeyUsage::SERVER_AUTH_REPR => Self::ServerAuth,
            _ => Self::Other(values),
        }
    }
}

impl fmt::Display for ExtendedKeyPurpose {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::ClientAuth => write!(f, "client authentication"),
            Self::ServerAuth => write!(f, "server authentication"),
            Self::Other(values) => {
                for (i, value) in values.iter().enumerate() {
                    if i > 0 {
                        write!(f, ", ")?;
                    }
                    write!(f, "{value}")?;
                }
                Ok(())
            }
        }
    }
}

/// The ways in which a certificate revocation list (CRL) can be invalid.
#[non_exhaustive]
#[derive(Debug, Clone)]
pub enum CertRevocationListError {
    /// The CRL had a bad signature from its issuer.
    BadSignature,

    /// The CRL's signature was made with an unsupported algorithm.
    UnsupportedSignatureAlgorithm {
        /// The signature algorithm OID that was unsupported.
        signature_algorithm_id: Vec<u8>,
        /// Supported algorithms that were available for signature verification.
        supported_algorithms: Vec<AlgorithmIdentifier>,
    },

    /// A signature was made with an algorithm that doesn't match the relevant public key.
    UnsupportedSignatureAlgorithmForPublicKey {
        /// The signature algorithm OID.
        signature_algorithm_id: Vec<u8>,
        /// The public key algorithm OID.
        public_key_algorithm_id: Vec<u8>,
    },

    /// The CRL contained an invalid CRL number.
    InvalidCrlNumber,

    /// The CRL contained a revoked certificate with an invalid serial number.
    InvalidRevokedCertSerialNumber,

    /// The CRL issuer does not specify the cRLSign key usage.
    IssuerInvalidForCrl,

    /// The CRL is invalid for some other reason.
    ///
    /// Enums holding this variant will never compare equal to each other.
    Other(OtherError),

    /// The CRL is not correctly encoded.
    ParseError,

    /// The CRL is not a v2 X.509 CRL.
    UnsupportedCrlVersion,

    /// The CRL, or a revoked certificate in the CRL, contained an unsupported critical extension.
    UnsupportedCriticalExtension,

    /// The CRL is an unsupported delta CRL, containing only changes relative to another CRL.
    UnsupportedDeltaCrl,

    /// The CRL is an unsupported indirect CRL, containing revoked certificates issued by a CA
    /// other than the issuer of the CRL.
    UnsupportedIndirectCrl,

    /// The CRL contained a revoked certificate with an unsupported revocation reason.
    /// See RFC 5280 Section 5.3.1[^1] for a list of supported revocation reasons.
    ///
    /// [^1]: <https://www.rfc-editor.org/rfc/rfc5280#section-5.3.1>
    UnsupportedRevocationReason,
}

impl PartialEq<Self> for CertRevocationListError {
    fn eq(&self, other: &Self) -> bool {
        use CertRevocationListError::*;
        match (self, other) {
            (BadSignature, BadSignature) => true,
            (
                UnsupportedSignatureAlgorithm {
                    signature_algorithm_id: left_signature_algorithm_id,
                    supported_algorithms: left_supported_algorithms,
                },
                UnsupportedSignatureAlgorithm {
                    signature_algorithm_id: right_signature_algorithm_id,
                    supported_algorithms: right_supported_algorithms,
                },
            ) => {
                (left_signature_algorithm_id, left_supported_algorithms)
                    == (right_signature_algorithm_id, right_supported_algorithms)
            }
            (
                UnsupportedSignatureAlgorithmForPublicKey {
                    signature_algorithm_id: left_signature_algorithm_id,
                    public_key_algorithm_id: left_public_key_algorithm_id,
                },
                UnsupportedSignatureAlgorithmForPublicKey {
                    signature_algorithm_id: right_signature_algorithm_id,
                    public_key_algorithm_id: right_public_key_algorithm_id,
                },
            ) => {
                (left_signature_algorithm_id, left_public_key_algorithm_id)
                    == (right_signature_algorithm_id, right_public_key_algorithm_id)
            }
            (InvalidCrlNumber, InvalidCrlNumber) => true,
            (InvalidRevokedCertSerialNumber, InvalidRevokedCertSerialNumber) => true,
            (IssuerInvalidForCrl, IssuerInvalidForCrl) => true,
            (ParseError, ParseError) => true,
            (UnsupportedCrlVersion, UnsupportedCrlVersion) => true,
            (UnsupportedCriticalExtension, UnsupportedCriticalExtension) => true,
            (UnsupportedDeltaCrl, UnsupportedDeltaCrl) => true,
            (UnsupportedIndirectCrl, UnsupportedIndirectCrl) => true,
            (UnsupportedRevocationReason, UnsupportedRevocationReason) => true,
            _ => false,
        }
    }
}

/// An error that occurred while handling Encrypted Client Hello (ECH).
#[non_exhaustive]
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum EncryptedClientHelloError {
    /// The provided ECH configuration list was invalid.
    InvalidConfigList,
    /// No compatible ECH configuration.
    NoCompatibleConfig,
    /// The client configuration has server name indication (SNI) disabled.
    SniRequired,
}

/// The server rejected the request to enable Encrypted Client Hello (ECH)
///
/// If [`RejectedEch::can_retry()`] is true, then you may use this with
/// [`crate::client::EchConfig::for_retry()`] to build a new `EchConfig` for a fresh client
/// connection that will use a compatible ECH configuration provided by the server for a retry.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq)]
pub struct RejectedEch {
    pub(crate) retry_configs: Option<Vec<EchConfigPayload>>,
}

impl RejectedEch {
    /// Returns true if the server provided new ECH configurations to use for a fresh retry connection
    ///
    /// The `RejectedEch` error can be provided to [`crate::client::EchConfig::for_retry()`]
    /// to build a new `EchConfig` for a fresh client connection that will use a compatible ECH
    /// configuration provided by the server for a retry.
    pub fn can_retry(&self) -> bool {
        self.retry_configs.is_some()
    }

    /// Returns an `EchConfigListBytes` with the server's provided retry configurations (if any)
    pub fn retry_configs(&self) -> Option<EchConfigListBytes<'static>> {
        let Some(retry_configs) = &self.retry_configs else {
            return None;
        };

        let mut tls_encoded_list = Vec::new();
        retry_configs.encode(&mut tls_encoded_list);

        Some(EchConfigListBytes::from(tls_encoded_list))
    }
}

fn join<T: fmt::Debug>(items: &[T]) -> String {
    items
        .iter()
        .map(|x| format!("{x:?}"))
        .collect::<Vec<String>>()
        .join(" or ")
}

/// Describes cases of API misuse
///
/// Variants here should be sufficiently detailed that the action needed is clear.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq)]
pub enum ApiMisuse {
    /// Trying to resume a session with an unknown cipher suite.
    ResumingFromUnknownCipherSuite(CipherSuite),

    /// The [`KeyingMaterialExporter`][] was already consumed.
    ///
    /// Methods that obtain an exporter (eg, [`Connection::exporter()`][]) can only
    /// be used once.  This error is returned on subsequent calls.
    ///
    /// [`KeyingMaterialExporter`]: crate::KeyingMaterialExporter
    /// [`Connection::exporter()`]: crate::Connection::exporter()
    ExporterAlreadyUsed,

    /// The `context` parameter to [`KeyingMaterialExporter::derive()`][] was too long.
    ///
    /// For TLS1.2 connections (only) this parameter is limited to 64KB.
    ///
    /// [`KeyingMaterialExporter::derive()`]: crate::KeyingMaterialExporter::derive()
    ExporterContextTooLong,

    /// The `output` object for [`KeyingMaterialExporter::derive()`][] was too long.
    ///
    /// For TLS1.3 connections this is limited to 255 times the hash output length.
    ///
    /// [`KeyingMaterialExporter::derive()`]: crate::KeyingMaterialExporter::derive()
    ExporterOutputTooLong,

    /// The `output` object to [`KeyingMaterialExporter::derive()`][] was zero length.
    ///
    /// This doesn't make sense, so we explicitly return an error (rather than simply
    /// producing no output as requested.)
    ///
    /// [`KeyingMaterialExporter::derive()`]: crate::KeyingMaterialExporter::derive()
    ExporterOutputZeroLength,

    /// Incorrect sample length provided to [`quic::HeaderProtectionKey::encrypt_in_place()`][]
    ///
    /// [`quic::HeaderProtectionKey::encrypt_in_place()`]: crate::quic::HeaderProtectionKey::encrypt_in_place()
    InvalidQuicHeaderProtectionSampleLength,

    /// Incorrect relation between sample length and header number length provided to
    /// [`quic::HeaderProtectionKey::encrypt_in_place()`][]
    ///
    /// [`quic::HeaderProtectionKey::encrypt_in_place()`]: crate::quic::HeaderProtectionKey::encrypt_in_place()
    InvalidQuicHeaderProtectionPacketNumberLength,

    /// Raw keys cannot be used with TLS 1.2.
    InvalidSignerForProtocolVersion,

    /// QUIC attempted with a configuration that does not support TLS1.3.
    QuicRequiresTls13Support,

    /// QUIC attempted with a configuration that does not support a ciphersuite that supports QUIC.
    NoQuicCompatibleCipherSuites,

    /// An empty certificate chain was provided.
    EmptyCertificateChain,

    /// QUIC attempted with unsupported [`ServerConfig::max_early_data_size`][]
    ///
    /// This field must be either zero or [`u32::MAX`] for QUIC.
    ///
    /// [`ServerConfig::max_early_data_size`]: crate::server::ServerConfig::max_early_data_size
    QuicRestrictsMaxEarlyDataSize,

    /// A `CryptoProvider` must have at least one cipher suite.
    NoCipherSuitesConfigured,

    /// A `CryptoProvider` must have at least one key exchange group.
    NoKeyExchangeGroupsConfigured,

    /// An empty list of signature verification algorithms was provided.
    NoSignatureVerificationAlgorithms,

    /// ECH attempted with a configuration that does not support TLS1.3.
    EchRequiresTls13Support,

    /// ECH attempted with a configuration that also supports TLS1.2.
    EchForbidsTls12Support,

    /// The received plaintext buffer is full; read out some plaintext before receiving more.
    ReceivedPlaintextBufferFull,

    /// Secret extraction operation attempted without opting-in to secret extraction.
    ///
    /// This is possible from [`Connection::dangerous_extract_secrets()`][crate::Connection::dangerous_extract_secrets].
    ///
    /// You must set [`ServerConfig::enable_secret_extraction`][crate::server::ServerConfig::enable_secret_extraction] or
    /// [`ClientConfig::enable_secret_extraction`][crate::client::ClientConfig::enable_secret_extraction] to true before this
    /// is available.
    SecretExtractionRequiresPriorOptIn,

    /// Secret extraction operation attempted without first extracting all pending
    /// TLS data.
    ///
    /// See [`Self::SecretExtractionRequiresPriorOptIn`] for a list of the affected
    /// functions.  You must ensure any prior generated TLS records are extracted
    /// from the library before using one of these functions.
    SecretExtractionWithPendingSendableData,

    /// Attempt to verify a certificate with an unsupported type.
    ///
    /// A verifier indicated support for a certificate type but then failed to verify the peer's
    /// identity of that type.
    UnverifiableCertificateType,

    /// A verifier or resolver implementation signalled that it does not support any certificate types.
    NoSupportedCertificateTypes,

    /// [`Nonce::to_array()`][] called with incorrect array size.
    ///
    /// The nonce length does not match the requested array size `N`.
    ///
    /// [`Nonce::to_array()`]: crate::crypto::cipher::Nonce::to_array()
    NonceArraySizeMismatch {
        /// The expected array size (type parameter N)
        expected: usize,
        /// The actual nonce length
        actual: usize,
    },

    /// [`Iv::new()`][] called with a value that exceeds the maximum IV length.
    ///
    /// The IV length must not exceed [`Iv::MAX_LEN`][].
    ///
    /// [`Iv::new()`]: crate::crypto::cipher::Iv::new()
    /// [`Iv::MAX_LEN`]: crate::crypto::cipher::Iv::MAX_LEN
    IvLengthExceedsMaximum {
        /// The actual IV length provided
        actual: usize,
        /// The maximum allowed IV length
        maximum: usize,
    },

    /// Calling [`ServerConnection::set_resumption_data()`] must be done before
    /// any resumption is offered.
    ///
    /// [`ServerConnection::set_resumption_data()`]: crate::server::ServerConnection::set_resumption_data()
    ResumptionDataProvidedTooLate,

    /// [`KernelConnection::update_tx_secret()`] and associated are not available for TLS1.2 connections.
    ///
    /// [`KernelConnection::update_tx_secret()`]: crate::conn::kernel::KernelConnection::update_tx_secret()
    KeyUpdateNotAvailableForTls12,

    /// [`ClientConnection::split()`] or [`ServerConnection::split()`] called during handshake.
    ///
    /// [`ServerConnection::split()`]: crate::server::ServerConnection::split()
    /// [`ClientConnection::split()`]: crate::client::ClientConnection::split()
    SplitDuringHandshake,

    /// [`ClientConnection::split()`] or [`ServerConnection::split()`] called with pending plaintext or TLS data.
    ///
    /// [`ServerConnection::split()`]: crate::server::ServerConnection::split()
    /// [`ClientConnection::split()`]: crate::client::ClientConnection::split()
    SplitWithPendingBuffers,

    /// An output buffer provided for encryption was too small.
    EncryptBufferTooSmall {
        /// The minimum required buffer length
        required: usize,
        /// The buffer length actually provided
        provided: usize,
    },
}

impl fmt::Display for ApiMisuse {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{self:?}")
    }
}

impl core::error::Error for ApiMisuse {}

mod other_error {
    use core::error::Error as StdError;
    use core::fmt;

    use crate::sync::Arc;

    /// Any other error that cannot be expressed by a more specific [`Error`][super::Error]
    /// variant.
    ///
    /// For example, an `OtherError` could be produced by a custom crypto provider
    /// exposing a provider specific error.
    ///
    /// Enums holding this type will never compare equal to each other.
    #[derive(Debug, Clone)]
    pub struct OtherError(Arc<dyn StdError + Send + Sync>);

    impl OtherError {
        /// Create a new `OtherError` from any error type.
        pub fn new(err: impl StdError + Send + Sync + 'static) -> Self {
            Self(Arc::new(err))
        }
    }

    impl PartialEq<Self> for OtherError {
        fn eq(&self, _other: &Self) -> bool {
            false
        }
    }

    impl fmt::Display for OtherError {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "{}", self.0)
        }
    }

    impl StdError for OtherError {
        fn source(&self) -> Option<&(dyn StdError + 'static)> {
            Some(self.0.as_ref())
        }
    }
}

pub use other_error::OtherError;

/// An [`Error`] along with the (possibly encrypted) alert to send to
/// the peer.
pub struct ErrorWithAlert {
    /// The error
    pub error: Error,
    pub(crate) data: Vec<u8>,
}

impl ErrorWithAlert {
    pub(crate) fn new(error: Error, send_path: &mut SendPath) -> Self {
        maybe_send_fatal_alert(send_path, &error);
        Self {
            error,
            data: send_path.sendable_tls.take_one_vec(),
        }
    }

    /// Consume any pending TLS data.
    ///
    /// The returned buffer will contain the alert, if one is to be sent.
    pub fn take_tls_data(&mut self) -> Option<Vec<u8>> {
        match self.data.is_empty() {
            true => None,
            false => Some(mem::take(&mut self.data)),
        }
    }
}

impl Deref for ErrorWithAlert {
    type Target = Error;

    fn deref(&self) -> &Self::Target {
        &self.error
    }
}

/// Direct conversion with no alert.
impl From<Error> for ErrorWithAlert {
    fn from(error: Error) -> Self {
        Self {
            error,
            data: Vec::new(),
        }
    }
}

impl fmt::Debug for ErrorWithAlert {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ErrorWithAlert")
            .field("error", &self.error)
            .field("data", &self.data.len())
            .finish_non_exhaustive()
    }
}