rtci-dtls 0.1.0

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

use crate::conn::DTLSConn;
use shared::error::{Error, Result};
use shared::{EcnCodepoint, TransportContext};
use shared::{TransportMessage, TransportProtocol};

use crate::config::HandshakeConfig;
use crate::cookie::{ClientHelloPrefix, CookieSecrets};
use crate::state::State;
use bytes::BytesMut;
use std::collections::hash_map::Keys;
use std::collections::{HashMap, VecDeque, hash_map::Entry::Vacant};
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::{Duration, Instant};

/// What the endpoint reports to its caller.
#[non_exhaustive]
pub enum EndpointEvent {
    /// The handshake finished; application data may now be sent, and SRTP keys can be exported.
    ///
    /// A server endpoint reports it again for an address that already had an association when
    /// the client there completed a new handshake (RFC 6347 4.2.8): the new association has
    /// replaced the old one, and with it the keys.
    HandshakeComplete,
    /// Decrypted application data arrived.
    ApplicationData(BytesMut),
    /// The peer closed the connection with a `close_notify` alert (RFC 5246 ยง7.2.1). The
    /// matching `close_notify` reply is queued for [`Endpoint::poll_transmit`], and the connection
    /// has been removed.
    PeerClosed,
    /// DTLS 1.3 server: the client answered a post-handshake CertificateRequest
    /// ([`Endpoint::request_client_certificate`]) and the answer verified. The chain is in
    /// [`State::peer_certificates`]; a client that declined left the earlier one there.
    PeerAuthenticated,
    /// DTLS 1.3 server: 0-RTT data the client sent with its ClientHello (RFC 8446 section
    /// 4.2.10), delivered before the handshake is complete. Unlike [`Self::ApplicationData`]
    /// it may be a replay (RFC 8446 section 8): each ticket is accepted once, and the
    /// ticket's age is checked, but whoever saw the ClientHello can send it to another
    /// server, or this one before its ticket record exists.
    EarlyData(BytesMut),
}

/// The most associations a server endpoint holds for addresses it has not verified: those
/// of ClientHellos too long for one record, which have to be put together before the cookie
/// exchange can be run (RFC 9147 section 5.1).
const MAX_UNVERIFIED_ASSOCIATIONS: usize = 32;

/// How long such an association lives without a datagram from its address while the address
/// is not verified. It holds state for an address nobody has verified, so it does not stay for
/// as long as the application lets handshakes run (by default with no limit), but each datagram
/// that reaches it gives it this long again: twice the longest retransmission interval (60
/// seconds), so that a client retransmitting at full backoff, which by then cuts its
/// ClientHello into more and smaller fragments (RFC 9147 section 4.4), is put together from
/// several transmissions, not only from one that arrives whole. Its HelloRetryRequest cookies
/// are the endpoint's (`RetryKeys`): one that goes costs a client nothing while the endpoint's
/// cookie secret lasts, and a repeated first ClientHello gets a new association.
const UNVERIFIED_ASSOCIATION_LIFETIME: Duration =
    Duration::from_secs(2 * crate::conn::MAXIMUM_RETRANSMIT_INTERVAL.as_secs());

/// What a server endpoint makes of a datagram before an association sees it.
enum Admission {
    /// It has been dealt with (answered with a HelloVerifyRequest, or dropped).
    Done,
    /// It goes to the association, or associations, of its source address.
    Deliver,
}

/// The main entry point to the library
///
/// This object performs no I/O whatsoever. Instead, it generates a stream of packets to send via
/// `poll_transmit`, and consumes incoming packets and connections-generated events via `handle` and
/// `handle_event`.
///
/// As a server it performs the cookie exchange of RFC 6347 4.2.1 without keeping state: a
/// ClientHello that carries no valid cookie is answered with a HelloVerifyRequest and
/// forgotten, and an association exists only once a client has echoed the cookie, which
/// proves it receives at the address it sends from. See
/// [`ConfigBuilder::with_cookie_exchange`](crate::config::ConfigBuilder::with_cookie_exchange).
pub struct Endpoint {
    local_addr: SocketAddr,
    transport_protocol: TransportProtocol,
    transmits: VecDeque<TransportMessage<BytesMut>>,
    connections: HashMap<SocketAddr, DTLSConn>,
    /// Server associations in the making for addresses that already have an established one:
    /// the client there has echoed a cookie for a new ClientHello (RFC 6347 4.2.8). The
    /// established association stays in `connections`, and in use, until the new handshake
    /// completes; then this one takes its place.
    pending: HashMap<SocketAddr, DTLSConn>,
    server_config: Option<Arc<HandshakeConfig>>,
    /// What the server's cookies are made with.
    cookie_secrets: CookieSecrets,
}

impl Endpoint {
    /// Create a new endpoint
    ///
    /// Returns `Err` if the configuration is invalid.
    pub fn new(
        local_addr: SocketAddr,
        protocol: TransportProtocol,
        server_config: Option<Arc<HandshakeConfig>>,
    ) -> Self {
        Self {
            local_addr,
            transport_protocol: protocol,
            transmits: VecDeque::new(),
            connections: HashMap::new(),
            pending: HashMap::new(),
            server_config,
            cookie_secrets: CookieSecrets::default(),
        }
    }

    /// Replace the server configuration, affecting new incoming associations only
    pub fn set_server_config(&mut self, server_config: Option<Arc<HandshakeConfig>>) {
        self.server_config = server_config;
    }

    /// Get the next packet to transmit
    #[must_use]
    pub fn poll_transmit(&mut self) -> Option<TransportMessage<BytesMut>> {
        self.transmits.pop_front()
    }

    /// Get keys of Connections
    pub fn get_connections_keys(&self) -> Keys<'_, SocketAddr, DTLSConn> {
        self.connections.keys()
    }

    /// Get Connection State
    pub fn get_connection_state(&self, remote: SocketAddr) -> Option<&State> {
        if let Some(conn) = self.connections.get(&remote) {
            Some(conn.connection_state())
        } else {
            None
        }
    }

    /// How many bytes a protected record to `remote` adds to its content: see
    /// [`DTLSConn::record_overhead`]. `None` without an association, or before it has keys.
    pub fn record_overhead(&self, remote: SocketAddr) -> Option<usize> {
        self.connections.get(&remote)?.record_overhead()
    }

    /// How often the handshake flight under way with `remote` has been sent again; zero once
    /// the handshake is complete, `None` without an association. See
    /// [`DTLSConn::handshake_retransmissions`].
    pub fn handshake_retransmissions(&self, remote: &SocketAddr) -> Option<usize> {
        self.connections
            .get(remote)
            .map(DTLSConn::handshake_retransmissions)
    }

    /// Whether the association with `remote` has failed: a fatal alert was sent or received, or
    /// its handshake gave up (a handshake error, or its deadline passed). An ordinary
    /// retransmission or a discarded record never fails it. `false` when there is no such
    /// association.
    pub fn is_connection_failed(&self, remote: &SocketAddr) -> bool {
        self.connections
            .get(remote)
            .is_some_and(|conn| conn.is_failed())
    }

    /// The fatal alerts that ended the association with `remote`, as alert description codes:
    /// (sent, received). `None` when there is no such association.
    pub fn connection_fatal_alerts(&self, remote: &SocketAddr) -> Option<(Option<u8>, Option<u8>)> {
        self.connections.get(remote).map(|conn| conn.fatal_alerts())
    }

    /// The connection with `remote`, for the fuzz harness to reach its record state.
    #[cfg(any(fuzzing, test))]
    pub(crate) fn connection_mut(&mut self, remote: &SocketAddr) -> Option<&mut DTLSConn> {
        self.connections.get_mut(remote)
    }

    /// Queues everything `conn` wants to send to `remote`.
    fn queue_transmits(
        transmits: &mut VecDeque<TransportMessage<BytesMut>>,
        conn: &mut DTLSConn,
        now: Instant,
        local_addr: SocketAddr,
        remote: SocketAddr,
        ecn: Option<EcnCodepoint>,
        transport_protocol: TransportProtocol,
    ) {
        while let Some(payload) = conn.outgoing_raw_packet() {
            transmits.push_back(TransportMessage {
                now,
                transport: TransportContext {
                    local_addr,
                    peer_addr: remote,
                    ecn,
                    transport_protocol,
                },
                message: payload,
            });
        }
    }

    /// Initiate an Association
    pub fn connect(
        &mut self,
        now: Instant,
        remote: SocketAddr,
        client_config: Arc<HandshakeConfig>,
        initial_state: Option<State>,
    ) -> Result<()> {
        self.connect_with_early_data(now, remote, client_config, initial_state, &[])
    }

    /// As [`Self::connect`], with `early_data` sent as DTLS 1.3 0-RTT data (RFC 8446 section
    /// 4.2.10) if the configuration's session store has a ticket for the server that allows
    /// that much. [`State::early_data_accepted`] says, once the server has answered, whether
    /// it took it; data it did not take is lost, and the application may send it again.
    /// 0-RTT data can be replayed (RFC 8446 section 8): send only what is safe to repeat.
    pub fn connect_with_early_data(
        &mut self,
        now: Instant,
        remote: SocketAddr,
        client_config: Arc<HandshakeConfig>,
        initial_state: Option<State>,
        early_data: &[u8],
    ) -> Result<()> {
        if remote.port() == 0 {
            return Err(Error::InvalidRemoteAddress(remote));
        }

        if let Vacant(e) = self.connections.entry(remote) {
            let mut conn = DTLSConn::new(client_config, true, initial_state);
            conn.state.early_data = early_data.to_vec();
            conn.handshake(now)?;
            Self::queue_transmits(
                &mut self.transmits,
                &mut conn,
                now,
                self.local_addr,
                remote,
                None,
                self.transport_protocol,
            );
            e.insert(conn);
        }

        Ok(())
    }

    /// Process stop remote
    ///
    /// `now` stamps the close_notify this queues. Like [`Self::connect`], the instant is a
    /// parameter rather than something the endpoint samples: it owns no sockets and reads no
    /// clock.
    pub fn stop(&mut self, now: Instant, remote: SocketAddr) -> Option<DTLSConn> {
        self.pending.remove(&remote);
        if let Some(conn) = self.connections.get_mut(&remote) {
            conn.close();
            Self::queue_transmits(
                &mut self.transmits,
                conn,
                now,
                self.local_addr,
                remote,
                None,
                self.transport_protocol,
            );
        }
        self.connections.remove(&remote)
    }

    /// Process close
    ///
    /// `now` stamps the close_notify queued for every live association.
    pub fn close(&mut self, now: Instant) -> Result<()> {
        for (remote_addr, conn) in self.connections.iter_mut() {
            conn.close();
            Self::queue_transmits(
                &mut self.transmits,
                conn,
                now,
                self.local_addr,
                *remote_addr,
                None,
                self.transport_protocol,
            );
        }
        self.connections.clear();
        self.pending.clear();

        Ok(())
    }

    /// Feeds one datagram to `conn` and advances its handshake, recording a completed handshake
    /// in `messages`. Draining application data and transmits is left to the caller, which does it
    /// whether or not this fails.
    fn read_into(
        conn: &mut DTLSConn,
        now: Instant,
        data: &[u8],
        messages: &mut Vec<EndpointEvent>,
    ) -> Result<()> {
        let is_handshake_completed_before = conn.is_handshake_completed();
        let authentications_before = conn.post_handshake_authentications;
        conn.set_clock(now);
        conn.read(data)?;
        while let Some(early) = conn.incoming_early_data() {
            messages.push(EndpointEvent::EarlyData(early));
        }
        if conn.is_dtls13() {
            // DTLS 1.3 has handshake messages after the handshake too (ACKs, key updates),
            // so its timers are set after every datagram.
            conn.handshake(now)?;
        } else if !conn.is_handshake_completed() {
            conn.handshake(now)?;
            // Drain any queued future-epoch packets (e.g. Finished that arrived
            // before ChangeCipherSpec bumped remote_epoch). If draining sets
            // handshake_rx, run handshake() again so the FSM can advance.
            let is_handshake = conn.handle_incoming_queued_packets()?;
            if is_handshake && !conn.is_handshake_completed() {
                conn.handshake(now)?;
            }
        } else if conn.received_handshake_in_last_datagram {
            // RFC 6347 4.2.4: this datagram carried an authenticated repeat of the peer's
            // Finished, so our final flight may have been lost and has to be sent again.
            // The gate is this datagram's accepted handshake record, not
            // the sticky `handshake_rx` flag, so ordinary post-handshake application data can
            // never provoke a spurious flight (certificate included, for a client). The
            // association is complete, so the FSM above is skipped, and `send()` never arms
            // `current_retransmit_timer` on the completed path, so `handle_timeout` cannot fire
            // for it either. `handshake_timeout`'s Finished branch regenerates the flight โ€” with
            // fresh record sequence numbers, since a verbatim replay would be dropped by the
            // peer's replay window (4.1.2.6) โ€” under the existing retransmission budget.
            // Clear `handshake_rx` first so
            // that retransmission re-sends the buffered flight instead of re-parsing the whole
            // transcript in `finish()`.
            conn.handshake_rx = None;
            conn.handshake_timeout(now)?;
        }
        if !is_handshake_completed_before && conn.is_handshake_completed() {
            messages.push(EndpointEvent::HandshakeComplete)
        }
        // One event per answer verified.
        for _ in authentications_before..conn.post_handshake_authentications {
            messages.push(EndpointEvent::PeerAuthenticated)
        }
        Ok(())
    }

    /// The server's part before any association: the stateless cookie exchange (RFC 6347
    /// 4.2.1), and with it the decision whether a ClientHello gets a new association. No
    /// association is made, and nothing is remembered, for a ClientHello that does not carry
    /// the cookie this server would have sent its source address for it.
    fn admit(
        &mut self,
        now: Instant,
        remote: SocketAddr,
        ecn: Option<EcnCodepoint>,
        data: &[u8],
        config: &Arc<HandshakeConfig>,
    ) -> Result<Admission> {
        let existing = self.connections.get(&remote);
        let failed = existing.is_some_and(|conn| conn.is_failed());
        let established = existing.is_some_and(|conn| !failed && conn.is_handshake_completed());
        let handshaking = existing.is_some() && !failed && !established;
        // A handshake under way takes its own records, a repeated ClientHello included; so
        // does one under way beside an established association.
        if handshaking || self.pending.contains_key(&remote) {
            return Ok(Admission::Deliver);
        }

        let Some(hello) = ClientHelloPrefix::parse(data) else {
            // Not a ClientHello. With no association there is nothing it could belong to.
            return Ok(if existing.is_some() {
                Admission::Deliver
            } else {
                Admission::Done
            });
        };

        // RFC 6347 4.2.8: a ClientHello on an established association may be a client that
        // lost its state and starts over. One that repeats the random of the ClientHello the
        // association was made from is that very ClientHello, late or duplicated.
        if established
            && existing
                .is_some_and(|conn| conn.state.remote_random.marshal_fixed() == hello.random())
        {
            return Ok(Admission::Deliver);
        }

        if config.supports_dtls13()
            && let Some(admission) =
                self.admit_dtls13(now, remote, ecn, data, config, &hello, established)?
        {
            return Ok(admission);
        }

        let provider = config.provider().clone();
        let verified = !config.cookie_exchange
            || self
                .cookie_secrets
                .verify(now, provider.as_ref(), remote, &hello)?;
        if !verified {
            // RFC 6347 4.2.1: a ClientHello without the cookie, or with an invalid one, is
            // answered with a HelloVerifyRequest. Nothing is kept, and the answer is smaller
            // than what it answers. An established association is not touched (4.2.8).
            let cookie = self
                .cookie_secrets
                .issue(now, provider.as_ref(), remote, &hello)?;
            self.transmits.push_back(TransportMessage {
                now,
                transport: TransportContext {
                    local_addr: self.local_addr,
                    peer_addr: remote,
                    ecn,
                    transport_protocol: self.transport_protocol,
                },
                message: BytesMut::from(
                    hello
                        .hello_verify_request(&cookie, config.hello_verify_request_version)
                        .as_slice(),
                ),
            });
            return Ok(Admission::Done);
        }

        // The client receives at `remote`: it gets an association. Beside the established one,
        // if there is one, which stays until the new handshake completes (RFC 6347 4.2.8); in
        // place of a failed one.
        let conn = DTLSConn::accept(
            config.clone(),
            hello.message_sequence,
            hello.record_sequence,
        )?;
        if established {
            self.pending.insert(remote, conn);
        } else {
            self.connections.insert(remote, conn);
        }
        Ok(Admission::Deliver)
    }

    /// A server's part before any association for a ClientHello that may be for DTLS 1.3
    /// (RFC 9147 section 5.1): the cookie exchange by HelloRetryRequest, without state. `None`
    /// when the ClientHello is DTLS 1.2's to answer.
    #[allow(clippy::too_many_arguments)]
    fn admit_dtls13(
        &mut self,
        now: Instant,
        remote: SocketAddr,
        ecn: Option<EcnCodepoint>,
        data: &[u8],
        config: &Arc<HandshakeConfig>,
        prefix: &ClientHelloPrefix<'_>,
        established: bool,
    ) -> Result<Option<Admission>> {
        use crate::dtls13::handshake::hello_retry_request;
        use crate::dtls13::hello::{RetryCookie, negotiate, parse_cookie, whole_client_hello};
        use crate::dtls13::messages::{self, ClientHello};
        use crate::dtls13::record::{CONTENT_TYPE_ALERT, CONTENT_TYPE_HANDSHAKE, plaintext_record};

        let Some((body, record_sequence, message_seq)) = whole_client_hello(data) else {
            // A ClientHello cut into several records cannot be judged from its first: its
            // extensions say which version it is for. With a DTLS 1.2 cookie it is DTLS
            // 1.2's. Without one, and with the cookie exchange on, it gets an association
            // that puts it together and runs the exchange itself, for either version; that
            // is state for an address nobody has verified, so only a bounded number exist.
            if prefix.cookie.is_empty() && config.cookie_exchange {
                self.drop_expired_unverified(now);
                let unverified = self
                    .connections
                    .values()
                    .chain(self.pending.values())
                    .filter(|conn| !conn.is_failed() && !conn.is_address_verified())
                    .count();
                if unverified >= MAX_UNVERIFIED_ASSOCIATIONS {
                    return Ok(Some(Admission::Done));
                }
                let mut conn = DTLSConn::new(config.clone(), false, None);
                // A DTLS 1.3 ClientHello that answers a HelloRetryRequest has message_seq 1
                // (RFC 9147 section 5.2): it is put together from there.
                conn.start_reassembly_at(prefix.message_sequence);
                let provider = config.provider().clone();
                conn.retry_keys = Some(crate::dtls13::hello::RetryKeys {
                    secrets: self.cookie_secrets.secrets(now, provider.as_ref())?,
                    remote,
                });
                conn.unverified_until = Some(now + UNVERIFIED_ASSOCIATION_LIFETIME);
                if established {
                    self.pending.insert(remote, conn);
                } else {
                    self.connections.insert(remote, conn);
                }
                return Ok(Some(Admission::Deliver));
            }
            return Ok(None);
        };
        let Ok(hello) = ClientHello::parse(body) else {
            return Ok(None);
        };
        let send = |endpoint: &mut Self, content_type: u8, fragment: &[u8]| {
            endpoint.transmits.push_back(TransportMessage {
                now,
                transport: TransportContext {
                    local_addr: endpoint.local_addr,
                    peer_addr: remote,
                    ecn,
                    transport_protocol: endpoint.transport_protocol,
                },
                message: BytesMut::from(
                    plaintext_record(content_type, record_sequence, fragment).as_slice(),
                ),
            });
        };
        if !hello.offers_dtls13() {
            if !config.supports_dtls12() {
                // RFC 8446 section 4.2.1: no version in common.
                send(
                    self,
                    CONTENT_TYPE_ALERT,
                    &[2, messages::alert::PROTOCOL_VERSION],
                );
                return Ok(Some(Admission::Done));
            }
            return Ok(None);
        }

        let provider = config.provider().clone();
        let secrets = self.cookie_secrets.secrets(now, provider.as_ref())?;
        let verified_retry = match hello.extension(messages::EXT_COOKIE) {
            Some(extension) => {
                let secrets: Vec<&[u8]> = secrets.iter().map(|secret| secret.as_ref()).collect();
                let opened = match parse_cookie(extension) {
                    Ok(cookie) => {
                        RetryCookie::open(provider.as_ref(), &secrets, Some(remote), cookie)?
                            .map(|opened| (cookie.to_vec(), opened))
                    }
                    Err(_) => None,
                };
                let Some(opened) = opened else {
                    // RFC 9147 section 5.1: a ClientHello with an invalid cookie is an
                    // illegal_parameter, so that the client can start again without one.
                    send(
                        self,
                        CONTENT_TYPE_ALERT,
                        &[2, messages::alert::ILLEGAL_PARAMETER],
                    );
                    return Ok(Some(Admission::Done));
                };
                Some(opened)
            }
            None => {
                let negotiated = match negotiate(config, &hello) {
                    Ok(negotiated) => negotiated,
                    Err(refusal) => {
                        send(self, CONTENT_TYPE_ALERT, &[2, refusal.alert]);
                        return Ok(Some(Admission::Done));
                    }
                };
                if config.cookie_exchange || negotiated.client_share.is_none() {
                    // Answered with a HelloRetryRequest and forgotten: the cookie carries
                    // what the second ClientHello has to be continued from.
                    let Some(secret) = secrets.first() else {
                        return Err(Error::Crypto("no cookie secret".to_owned()));
                    };
                    let (retry, _) = hello_retry_request(
                        provider.as_ref(),
                        secret.as_ref(),
                        Some(remote),
                        body,
                        &negotiated,
                    )?;
                    send(
                        self,
                        CONTENT_TYPE_HANDSHAKE,
                        &messages::handshake_fragment(
                            messages::SERVER_HELLO,
                            retry.len(),
                            0,
                            0,
                            &retry,
                        ),
                    );
                    return Ok(Some(Admission::Done));
                }
                None
            }
        };

        let mut conn = DTLSConn::accept(config.clone(), message_seq, record_sequence)?;
        conn.verified_retry = verified_retry;
        if established {
            self.pending.insert(remote, conn);
        } else {
            self.connections.insert(remote, conn);
        }
        Ok(Some(Admission::Deliver))
    }

    /// Whether `conn` is an association for an unverified address that has outlived
    /// [`UNVERIFIED_ASSOCIATION_LIFETIME`] at `now`.
    fn unverified_expired(conn: &DTLSConn, now: Instant) -> bool {
        !conn.is_address_verified() && conn.unverified_until.is_some_and(|until| now >= until)
    }

    /// Forgets the associations for unverified addresses that have outlived their time.
    /// Nothing is sent and nothing is reported: there was never a verified peer.
    fn drop_expired_unverified(&mut self, now: Instant) {
        self.connections
            .retain(|_, conn| !Self::unverified_expired(conn, now));
        self.pending
            .retain(|_, conn| !Self::unverified_expired(conn, now));
    }

    /// RFC 9146 section 6, RFC 9147 section 9: a datagram from an address without an
    /// association, under a connection id of an association at another address. When the
    /// configuration allows it, that association takes the datagram; if a record of it
    /// authenticates and is newer than any before, the association is at `remote` from now
    /// on. `None` when no association owns the datagram.
    fn migrate(
        &mut self,
        now: Instant,
        remote: SocketAddr,
        data: &[u8],
    ) -> Option<Vec<EndpointEvent>> {
        let previous = self.connections.iter().find_map(|(address, conn)| {
            let owns = match conn.v13.as_ref() {
                Some(v13) => v13.owns_connection_id(data),
                // DTLS 1.2 (RFC 9146 section 4): a `tls12_cid` record with this side's
                // connection id between its sequence number and its length.
                None => conn
                    .state
                    .receive_connection_id()
                    .is_some_and(|connection_id| {
                        let at =
                            crate::record_layer::record_layer_header::RECORD_LAYER_HEADER_SIZE - 2;
                        data.first() == Some(&(crate::content::ContentType::Tls12Cid as u8))
                            && data.get(at..at + connection_id.len()) == Some(connection_id)
                    }),
            };
            let migrates = conn.handshake_config.connection_id_migration
                && conn.is_handshake_completed()
                && !conn.is_failed()
                && owns;
            migrates.then_some(*address)
        })?;
        let conn = self.connections.get_mut(&previous)?;
        // An authentic, newer record is what moves the association. A replay or a forgery
        // is dropped by it like any other, and leaves it where it was.
        let authenticated = conn.authenticated_records;
        let newest_before = conn.newest_authenticated_record;
        conn.set_clock(now);
        let _ = conn.read(data);
        let _ = conn.handshake(now);
        let newest = match conn.v13.as_ref() {
            Some(v13) => v13.newest_record_read,
            None => conn.newest_authenticated_record > newest_before,
        };
        let moves = conn.authenticated_records != authenticated && newest;
        let mut events = vec![];
        while let Some(message) = conn.incoming_application_data() {
            events.push(EndpointEvent::ApplicationData(message));
        }
        let destination = if moves { remote } else { previous };
        Self::queue_transmits(
            &mut self.transmits,
            conn,
            now,
            self.local_addr,
            destination,
            None,
            self.transport_protocol,
        );
        if moves && let Some(conn) = self.connections.remove(&previous) {
            self.connections.insert(remote, conn);
        }
        Some(events)
    }

    /// Hands the peer at `remote` `count` new connection ids: see
    /// [`DTLSConn::new_connection_ids`].
    pub fn new_connection_ids(
        &mut self,
        now: Instant,
        remote: SocketAddr,
        count: usize,
        immediate: bool,
    ) -> Result<()> {
        self.with_dtls13(now, remote, |conn| {
            conn.new_connection_ids(count, immediate)
        })
    }

    /// Asks the peer at `remote` for `count` more connection ids: see
    /// [`DTLSConn::request_connection_ids`].
    pub fn request_connection_ids(
        &mut self,
        now: Instant,
        remote: SocketAddr,
        count: u8,
    ) -> Result<()> {
        self.with_dtls13(now, remote, |conn| conn.request_connection_ids(count))
    }

    /// The association with `remote` now sends on a new path (the transport under it changed
    /// its local or remote address, an ICE pair switch for one). RFC 9147 section 9:
    /// "Implementations SHOULD use a new CID whenever sending on a new path and SHOULD request
    /// new CIDs for this purpose if path changes are anticipated"; section 11: "implementations
    /// SHOULD attempt to use fresh CIDs whenever they change local addresses or ports". When
    /// the established DTLS 1.3 association sends a connection id, it switches to the next
    /// spare one the peer provided and asks for one more, for the next change. Returns whether
    /// it switched: `false` without connection ids, before the handshake completed, or with no
    /// spare id (one is requested then).
    ///
    /// # Errors
    ///
    /// When `remote` names no association, or the request cannot be written.
    pub fn path_changed(&mut self, now: Instant, remote: SocketAddr) -> Result<bool> {
        let Some(conn) = self.connections.get(&remote) else {
            return Err(Error::InvalidRemoteAddress(remote));
        };
        let sends_one = conn
            .connection_ids()
            .is_some_and(|(_, sent)| !sent.is_empty());
        if !sends_one || !conn.is_handshake_completed() {
            return Ok(false);
        }
        let mut switched = false;
        self.with_dtls13(now, remote, |conn| {
            switched = conn.use_next_connection_id();
            // One more for the next change; refused while an earlier request is unanswered,
            // which then brings it.
            let _ = conn.request_connection_ids(1);
            Ok(())
        })?;
        Ok(switched)
    }

    /// Runs `action` on the association with `remote`, sets its timers and queues what it
    /// wants sent.
    fn with_dtls13(
        &mut self,
        now: Instant,
        remote: SocketAddr,
        action: impl FnOnce(&mut DTLSConn) -> Result<()>,
    ) -> Result<()> {
        let Some(conn) = self.connections.get_mut(&remote) else {
            return Err(Error::InvalidRemoteAddress(remote));
        };
        action(conn)?;
        conn.handshake(now)?;
        Self::queue_transmits(
            &mut self.transmits,
            conn,
            now,
            self.local_addr,
            remote,
            None,
            self.transport_protocol,
        );
        Ok(())
    }

    /// Asks the client at `remote` for its certificate after the handshake (RFC 8446 section
    /// 4.6.2): see [`DTLSConn::request_client_certificate`].
    pub fn request_client_certificate(&mut self, now: Instant, remote: SocketAddr) -> Result<()> {
        self.with_dtls13(now, remote, DTLSConn::request_client_certificate)
    }

    /// Starts a key update on the DTLS 1.3 association with `remote` (RFC 9147 section 8):
    /// see [`DTLSConn::update_keys`].
    pub fn update_keys(
        &mut self,
        now: Instant,
        remote: SocketAddr,
        request_peer: bool,
    ) -> Result<()> {
        let Some(conn) = self.connections.get_mut(&remote) else {
            return Err(Error::InvalidRemoteAddress(remote));
        };
        conn.update_keys(request_peer)?;
        conn.handshake(now)?;
        Self::queue_transmits(
            &mut self.transmits,
            conn,
            now,
            self.local_addr,
            remote,
            None,
            self.transport_protocol,
        );
        Ok(())
    }

    /// Process an incoming UDP datagram
    pub fn read(
        &mut self,
        now: Instant,
        remote: SocketAddr,
        ecn: Option<EcnCodepoint>,
        data: BytesMut,
    ) -> Result<Vec<EndpointEvent>> {
        if !self.connections.contains_key(&remote)
            && !self.pending.contains_key(&remote)
            && let Some(events) = self.migrate(now, remote, &data)
        {
            return Ok(events);
        }
        if let Some(config) = self.server_config.clone() {
            if let Admission::Done = self.admit(now, remote, ecn, &data, &config)? {
                return Ok(vec![]);
            }
            // An association for an unverified address lives on while datagrams come.
            for conn in [
                self.connections.get_mut(&remote),
                self.pending.get_mut(&remote),
            ]
            .into_iter()
            .flatten()
            {
                if !conn.is_address_verified() && conn.unverified_until.is_some() {
                    conn.unverified_until = Some(now + UNVERIFIED_ASSOCIATION_LIFETIME);
                }
            }
            // A failed server association takes no more input. It still says its fatal alert
            // again when the peer repeats a flight (RFC 6347 4.2.7), which is not an error
            // for the caller: a datagram for an association that is over is simply dropped.
            if self.is_connection_failed(&remote) {
                if let Some(conn) = self.connections.get_mut(&remote) {
                    let _ = conn.read(&data);
                    Self::queue_transmits(
                        &mut self.transmits,
                        conn,
                        now,
                        self.local_addr,
                        remote,
                        ecn,
                        self.transport_protocol,
                    );
                }
                return Ok(vec![]);
            }
        } else if !self.connections.contains_key(&remote) {
            return Err(Error::NoServerConfig);
        }

        if self.pending.contains_key(&remote) {
            // Two associations for this address (RFC 6347 4.2.8). An epoch-0 record is the new
            // handshake's. A protected one is whichever association's keys open it: the
            // established one is asked first, so that its traffic goes on undisturbed.
            // (A DTLS 1.3 protected record has no epoch field there: its first byte says
            // what it is.)
            let plaintext = data.get(3..5) == Some(&[0, 0][..])
                && !data
                    .first()
                    .is_some_and(|first| crate::dtls13::record::is_unified_header(*first));
            if !plaintext {
                let authenticated = |endpoint: &Self| {
                    endpoint
                        .connections
                        .get(&remote)
                        .map(|conn| conn.authenticated_records)
                };
                let before = authenticated(self);
                let result = self.read_association(now, remote, ecn, &data);
                if authenticated(self) != before || !self.connections.contains_key(&remote) {
                    return result;
                }
            }
            return self.read_pending(now, remote, ecn, &data);
        }

        self.read_association(now, remote, ecn, &data)
    }

    /// Hands a datagram to the association of `remote`.
    fn read_association(
        &mut self,
        now: Instant,
        remote: SocketAddr,
        ecn: Option<EcnCodepoint>,
        data: &[u8],
    ) -> Result<Vec<EndpointEvent>> {
        // Handle packet on existing association, if any
        let mut messages = vec![];
        if let Some(conn) = self.connections.get_mut(&remote) {
            let result = Self::read_into(conn, now, data, &mut messages);
            // Whatever the outcome, deliver the data that arrived and send what the connection
            // queued: an alert in reply to the peer's (its close_notify, or a fatal alert) has to
            // go out even though this read is ending in an error.
            while let Some(message) = conn.incoming_application_data() {
                messages.push(EndpointEvent::ApplicationData(message));
            }
            Self::queue_transmits(
                &mut self.transmits,
                conn,
                now,
                self.local_addr,
                remote,
                ecn,
                self.transport_protocol,
            );
            // A peer's close_notify ends the connection gracefully: report it rather than the
            // error the connection returns for it.
            if conn.closed_by_peer {
                self.connections.remove(&remote);
                self.pending.remove(&remote);
                messages.push(EndpointEvent::PeerClosed);
                return Ok(messages);
            }
            result?;
        }

        Ok(messages)
    }

    /// Hands a datagram to the association in the making for `remote` (RFC 6347 4.2.8). When
    /// its handshake completes, the client has shown with a verified Finished that it is the
    /// peer, and the association takes the established one's place; if it fails, it goes and
    /// the established one is as it was.
    fn read_pending(
        &mut self,
        now: Instant,
        remote: SocketAddr,
        ecn: Option<EcnCodepoint>,
        data: &[u8],
    ) -> Result<Vec<EndpointEvent>> {
        let mut messages = vec![];
        let Some(conn) = self.pending.get_mut(&remote) else {
            return Ok(messages);
        };
        let result = Self::read_into(conn, now, data, &mut messages);
        Self::queue_transmits(
            &mut self.transmits,
            conn,
            now,
            self.local_addr,
            remote,
            ecn,
            self.transport_protocol,
        );
        if result.is_err() || conn.is_failed() {
            self.pending.remove(&remote);
            return Ok(vec![]);
        }
        if conn.is_handshake_completed()
            && let Some(mut conn) = self.pending.remove(&remote)
        {
            while let Some(message) = conn.incoming_application_data() {
                messages.push(EndpointEvent::ApplicationData(message));
            }
            self.connections.insert(remote, conn);
        }
        Ok(messages)
    }

    /// Queues application data for `remote`.
    ///
    /// # Errors
    ///
    /// Fails if there is no association with `remote`, if the association is closed, or if
    /// `data` is longer than a record may carry
    /// ([`MAX_RECORD_PAYLOAD`](crate::conn::MAX_RECORD_PAYLOAD)).
    pub fn write(&mut self, now: Instant, remote: SocketAddr, data: &[u8]) -> Result<()> {
        if let Some(conn) = self.connections.get_mut(&remote) {
            conn.write(data)?;
            if conn.is_dtls13() {
                conn.handshake(now)?;
            }
            Self::queue_transmits(
                &mut self.transmits,
                conn,
                now,
                self.local_addr,
                remote,
                None,
                self.transport_protocol,
            );
            Ok(())
        } else {
            Err(Error::InvalidRemoteAddress(remote))
        }
    }

    /// Advances `remote`'s association to `now`: retransmits its handshake flight when the
    /// retransmission timer has expired (RFC 6347 4.2.4), and gives the handshake up at its
    /// deadline ([`ConfigBuilder::with_handshake_timeout`](crate::config::ConfigBuilder::with_handshake_timeout)).
    ///
    /// # Errors
    ///
    /// `ErrHandshakeTimeout` when the handshake did not complete in time; the association has
    /// then failed.
    pub fn handle_timeout(&mut self, remote: SocketAddr, now: Instant) -> Result<()> {
        // An association for an address the client has not verified goes at the end of its
        // time, silently (`UNVERIFIED_ASSOCIATION_LIFETIME`).
        if self
            .pending
            .get(&remote)
            .is_some_and(|conn| Self::unverified_expired(conn, now))
        {
            self.pending.remove(&remote);
        }
        if self
            .connections
            .get(&remote)
            .is_some_and(|conn| Self::unverified_expired(conn, now))
        {
            self.connections.remove(&remote);
            return Ok(());
        }
        // An association in the making beside an established one has its own timers; when it
        // gives up, it goes and nothing else changes.
        if let Some(conn) = self.pending.get_mut(&remote) {
            let result = if conn.next_timeout().is_some_and(|at| now >= at) {
                conn.handle_timeout(now)
            } else {
                Ok(())
            };
            Self::queue_transmits(
                &mut self.transmits,
                conn,
                now,
                self.local_addr,
                remote,
                None,
                self.transport_protocol,
            );
            if result.is_err() {
                self.pending.remove(&remote);
            }
        }
        if let Some(conn) = self.connections.get_mut(&remote) {
            let result = if conn.next_timeout().is_some_and(|at| now >= at) {
                conn.handle_timeout(now)
            } else {
                Ok(())
            };
            Self::queue_transmits(
                &mut self.transmits,
                conn,
                now,
                self.local_addr,
                remote,
                None,
                self.transport_protocol,
            );
            result
        } else {
            Err(Error::InvalidRemoteAddress(remote))
        }
    }

    /// When `remote`'s association next needs [`Self::handle_timeout`]: the retransmission
    /// timer or the handshake deadline, whichever comes first.
    pub fn poll_timeout(&self, remote: &SocketAddr) -> Option<Instant> {
        let next = |conn: &DTLSConn| {
            let expiry = conn
                .unverified_until
                .filter(|_| !conn.is_address_verified());
            match (conn.next_timeout(), expiry) {
                (Some(a), Some(b)) => Some(a.min(b)),
                (a, b) => a.or(b),
            }
        };
        let established = self.connections.get(remote).and_then(next);
        let pending = self.pending.get(remote).and_then(next);
        match (established, pending) {
            (Some(a), Some(b)) => Some(a.min(b)),
            (a, b) => a.or(b),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cipher_suite::CipherSuiteId;
    use crate::config::ConfigBuilder;
    use crate::conn::DEFAULT_MAXIMUM_RETRANSMIT_NUMBER;
    use crate::crypto::Certificate;
    use crypto::{CryptoError, RTCCrypto, RTCCryptoProvider, RTCRandom};

    fn client_addr() -> SocketAddr {
        SocketAddr::from(([127, 0, 0, 1], 4444))
    }

    fn server_addr() -> SocketAddr {
        SocketAddr::from(([127, 0, 0, 1], 4445))
    }

    struct FailingRandom;

    impl RTCRandom for FailingRandom {
        fn fill(&self, _output: &mut [u8]) -> std::result::Result<(), CryptoError> {
            Err(CryptoError::RandomnessFailed)
        }
    }

    struct FailingRandomProvider {
        provider: Arc<dyn RTCCryptoProvider>,
    }

    impl RTCCryptoProvider for FailingRandomProvider {
        fn name(&self) -> &'static str {
            "failing-random"
        }

        fn crypto(&self) -> &dyn RTCCrypto {
            self.provider.crypto()
        }

        fn random(&self) -> &dyn RTCRandom {
            &FailingRandom
        }
    }

    /// Builds a config offering `suites`, with whichever credentials they need โ€” pass both
    /// families to get a server holding a psk callback and certificates both.
    fn config(
        provider: Arc<dyn RTCCryptoProvider>,
        is_client: bool,
        suites: &[CipherSuiteId],
    ) -> Result<Arc<HandshakeConfig>> {
        let mut builder = ConfigBuilder::default()
            .with_crypto_provider(provider.clone())
            .with_cipher_suites(suites.to_vec())
            .with_insecure_skip_verify(true);
        let is_psk = |suite: &CipherSuiteId| {
            matches!(
                suite,
                CipherSuiteId::Tls_Psk_With_Aes_128_Ccm
                    | CipherSuiteId::Tls_Psk_With_Aes_128_Ccm_8
                    | CipherSuiteId::Tls_Psk_With_Aes_128_Gcm_Sha256
            )
        };
        if suites.iter().any(is_psk) {
            builder = builder.with_psk(Some(Arc::new(|_| Ok(vec![0xab, 0xcd, 0xef]))));
            if is_client {
                builder = builder.with_psk_identity_hint(Some(b"rtc-dtls-test".to_vec()));
            }
        }
        if !is_client && suites.iter().any(|suite| !is_psk(suite)) {
            builder = builder.with_certificates(vec![Certificate::generate_self_signed(
                vec!["localhost".to_owned()],
                provider.crypto(),
            )?]);
        }
        Ok(Arc::new(builder.build(is_client, None)?))
    }

    fn transfer(
        source: &mut Endpoint,
        destination: &mut Endpoint,
        source_addr: SocketAddr,
    ) -> Result<Vec<EndpointEvent>> {
        let mut events = Vec::new();
        while let Some(transmit) = source.poll_transmit() {
            events.extend(destination.read(
                Instant::now(),
                source_addr,
                transmit.transport.ecn,
                transmit.message,
            )?);
        }
        Ok(events)
    }

    fn handshake_and_exchange(
        client_provider: Arc<dyn RTCCryptoProvider>,
        server_provider: Arc<dyn RTCCryptoProvider>,
        client_suite: CipherSuiteId,
        server_suites: &[CipherSuiteId],
    ) -> Result<()> {
        let server_config = config(server_provider, false, server_suites)?;
        let mut server = Endpoint::new(server_addr(), TransportProtocol::UDP, Some(server_config));
        exchange_with_server(&mut server, client_provider, client_addr(), client_suite)
    }

    /// Drives one client through a handshake and a record exchange against an existing server,
    /// so several clients can be served by the one endpoint and configuration.
    fn exchange_with_server(
        server: &mut Endpoint,
        client_provider: Arc<dyn RTCCryptoProvider>,
        client_addr: SocketAddr,
        client_suite: CipherSuiteId,
    ) -> Result<()> {
        let client_config = config(client_provider, true, &[client_suite])?;
        let mut client = Endpoint::new(client_addr, TransportProtocol::UDP, None);
        client.connect(Instant::now(), server_addr(), client_config, None)?;

        let mut client_complete = false;
        let mut server_complete = false;
        for _ in 0..32 {
            for event in transfer(&mut client, server, client_addr)? {
                server_complete |= matches!(event, EndpointEvent::HandshakeComplete);
            }
            for event in transfer(server, &mut client, server_addr())? {
                client_complete |= matches!(event, EndpointEvent::HandshakeComplete);
            }
            if client_complete && server_complete {
                break;
            }
        }
        assert!(
            client_complete && server_complete,
            "DTLS handshake did not complete for a {client_suite:?} client"
        );

        client.write(Instant::now(), server_addr(), b"provider-backed DTLS")?;
        let transmit = client
            .poll_transmit()
            .expect("application write produces a DTLS record");
        let replay = transmit.message.clone();
        let events = server.read(
            Instant::now(),
            client_addr,
            transmit.transport.ecn,
            transmit.message,
        )?;
        assert!(events.into_iter().any(|event| matches!(
            event,
            EndpointEvent::ApplicationData(data) if data.as_ref() == b"provider-backed DTLS"
        )));
        assert!(
            server
                .read(Instant::now(), client_addr, None, replay)?
                .is_empty()
        );
        Ok(())
    }

    /// A plaintext (epoch 0) record, as anyone who can spoof the peer's address can send: it
    /// needs no keys.
    fn plaintext_record_datagram(content_type: u8, body: &[u8], sequence_number: u64) -> BytesMut {
        use crate::content::ContentType;
        use crate::record_layer::record_layer_header::{PROTOCOL_VERSION1_2, RecordLayerHeader};

        let header = RecordLayerHeader {
            content_type: ContentType::Alert,
            protocol_version: PROTOCOL_VERSION1_2,
            epoch: 0,
            sequence_number,
            content_len: body.len() as u16,
        };
        let mut raw = vec![];
        header.marshal(&mut raw).expect("a record header marshals");
        // `ContentType` folds unknown values into `Invalid`, so the type byte is written raw.
        raw[0] = content_type;
        raw.extend_from_slice(body);
        BytesMut::from(&raw[..])
    }

    #[cfg(feature = "crypto-ring")]
    #[test]
    fn ring_provider_completes_handshake_and_record_exchange() -> Result<()> {
        let provider: Arc<dyn RTCCryptoProvider> = Arc::new(crypto::providers::RingProvider::new());
        handshake_and_exchange(
            provider.clone(),
            provider,
            CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_128_Gcm_Sha256,
            &[CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_128_Gcm_Sha256],
        )
    }

    #[cfg(feature = "crypto-aws-lc-rs")]
    #[test]
    fn aws_lc_rs_provider_completes_handshake_and_record_exchange() -> Result<()> {
        let provider: Arc<dyn RTCCryptoProvider> =
            Arc::new(crypto::providers::AwsLcRsProvider::new());
        handshake_and_exchange(
            provider.clone(),
            provider,
            CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_128_Gcm_Sha256,
            &[CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_128_Gcm_Sha256],
        )
    }

    #[cfg(all(feature = "crypto-ring", feature = "crypto-aws-lc-rs"))]
    #[test]
    fn ring_and_aws_lc_rs_complete_cross_provider_handshakes() -> Result<()> {
        let ring: Arc<dyn RTCCryptoProvider> = Arc::new(crypto::providers::RingProvider::new());
        let aws: Arc<dyn RTCCryptoProvider> = Arc::new(crypto::providers::AwsLcRsProvider::new());
        for suite in [
            CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_128_Gcm_Sha256,
            CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_128_Ccm,
            CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_128_Ccm_8,
            CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_256_Cbc_Sha,
            CipherSuiteId::Tls_Ecdhe_Ecdsa_With_ChaCha20_Poly1305_Sha256,
            CipherSuiteId::Tls_Psk_With_Aes_128_Gcm_Sha256,
            CipherSuiteId::Tls_Psk_With_Aes_128_Ccm,
            CipherSuiteId::Tls_Psk_With_Aes_128_Ccm_8,
        ] {
            handshake_and_exchange(ring.clone(), aws.clone(), suite, &[suite])?;
            handshake_and_exchange(aws.clone(), ring.clone(), suite, &[suite])?;
        }
        Ok(())
    }

    #[test]
    fn failing_random_provider_aborts_client_hello_cleanly() -> Result<()> {
        let base = crypto::default_provider().map_err(|error| Error::Crypto(error.to_string()))?;
        let provider: Arc<dyn RTCCryptoProvider> =
            Arc::new(FailingRandomProvider { provider: base });
        let config = config(
            provider,
            true,
            &[CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_128_Gcm_Sha256],
        )?;
        let mut endpoint = Endpoint::new(client_addr(), TransportProtocol::UDP, None);

        let result = endpoint.connect(Instant::now(), server_addr(), config, None);
        assert!(matches!(result, Err(Error::Crypto(_))));
        Ok(())
    }

    #[cfg(feature = "crypto-ring")]
    #[test]
    fn one_server_config_serves_psk_and_certificate_clients() -> Result<()> {
        let provider: Arc<dyn RTCCryptoProvider> = Arc::new(crypto::providers::RingProvider::new());
        let certificate_and_psk_suites = [
            CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_128_Gcm_Sha256,
            CipherSuiteId::Tls_Psk_With_Aes_128_Ccm_8,
        ];

        let server_config = config(provider.clone(), false, &certificate_and_psk_suites)?;
        let mut server = Endpoint::new(server_addr(), TransportProtocol::UDP, Some(server_config));

        for (index, client_suite) in certificate_and_psk_suites.into_iter().enumerate() {
            let client_addr = SocketAddr::from(([127, 0, 0, 1], 4446 + index as u16));
            exchange_with_server(&mut server, provider.clone(), client_addr, client_suite)?;
        }

        Ok(())
    }

    /// Runs a full handshake to completion and returns both endpoints, drained of any pending
    /// transmit so a later assertion sees only newly generated output.
    #[cfg(feature = "crypto-ring")]
    fn completed_client_and_server() -> Result<(Endpoint, Endpoint)> {
        completed_client_and_server_with(&[CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_128_Gcm_Sha256])
    }

    /// As [`completed_client_and_server`], over `suites`.
    #[cfg(feature = "crypto-ring")]
    fn completed_client_and_server_with(suites: &[CipherSuiteId]) -> Result<(Endpoint, Endpoint)> {
        let provider: Arc<dyn RTCCryptoProvider> = Arc::new(crypto::providers::RingProvider::new());
        let client_config = config(provider.clone(), true, suites)?;
        let server_config = config(provider, false, suites)?;
        let mut client = Endpoint::new(client_addr(), TransportProtocol::UDP, None);
        let mut server = Endpoint::new(server_addr(), TransportProtocol::UDP, Some(server_config));
        client.connect(Instant::now(), server_addr(), client_config, None)?;

        let mut client_complete = false;
        let mut server_complete = false;
        for _ in 0..32 {
            for event in transfer(&mut client, &mut server, client_addr())? {
                server_complete |= matches!(event, EndpointEvent::HandshakeComplete);
            }
            for event in transfer(&mut server, &mut client, server_addr())? {
                client_complete |= matches!(event, EndpointEvent::HandshakeComplete);
            }
            if client_complete && server_complete {
                break;
            }
        }
        assert!(
            client_complete && server_complete,
            "the handshake completed for both sides"
        );
        while client.poll_transmit().is_some() {}
        while server.poll_transmit().is_some() {}
        Ok((client, server))
    }

    /// A 29-byte epoch-0 record whose content type marks it a handshake and whose body is a
    /// well-formed fragment header over a junk payload: [`crate::fragment_buffer::FragmentBuffer`]
    /// classifies the datagram as a handshake record โ€” arming the RFC 6347 4.2.4 retransmission
    /// trigger โ€” although nothing in it is authenticated (epoch 0 carries no MAC).
    fn junk_epoch_zero_handshake_datagram(sequence_number: u64) -> BytesMut {
        use crate::content::ContentType;
        use crate::record_layer::record_layer_header::{PROTOCOL_VERSION1_2, RecordLayerHeader};

        let header = RecordLayerHeader {
            content_type: ContentType::Handshake,
            protocol_version: PROTOCOL_VERSION1_2,
            epoch: 0,
            sequence_number,
            content_len: 16,
        };
        let mut raw = vec![];
        header.marshal(&mut raw).expect("a record header marshals");
        raw.extend_from_slice(&[
            0xff, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00,
            0x00, 0x00,
        ]);
        BytesMut::from(&raw[..])
    }

    /// The `(epoch, record sequence number)` of every record in `datagram`, read from the plaintext
    /// record headers (the epoch-1 Finished body is encrypted, but its header is not).
    fn record_sequence_numbers(datagram: &[u8]) -> Vec<(u16, u64)> {
        use crate::record_layer::record_layer_header::RecordLayerHeader;
        use crate::record_layer::unpack_datagram;

        unpack_datagram(datagram)
            .expect("a datagram splits into records")
            .into_iter()
            .map(|record| {
                let mut reader = record.as_slice();
                let header =
                    RecordLayerHeader::unmarshal(&mut reader).expect("each record has a header");
                (header.epoch, header.sequence_number)
            })
            .collect()
    }

    /// Asserts every record in `retransmit` carries a sequence number strictly greater than any
    /// record of the same epoch in `original` โ€” i.e. the flight was regenerated, not replayed
    /// verbatim (a replay would be dropped by the peer's replay window, RFC 6347 4.1.2.6).
    fn assert_fresh_sequence_numbers(original: &[BytesMut], retransmit: &[BytesMut]) {
        use std::collections::HashMap;

        let by_epoch = |flight: &[BytesMut]| {
            let mut per_epoch: HashMap<u16, Vec<u64>> = HashMap::new();
            for datagram in flight {
                for (epoch, sequence_number) in record_sequence_numbers(datagram) {
                    per_epoch.entry(epoch).or_default().push(sequence_number);
                }
            }
            per_epoch
        };

        let original = by_epoch(original);
        let retransmit = by_epoch(retransmit);
        assert!(
            retransmit.contains_key(&1),
            "the retransmitted flight carries the encrypted Finished (epoch 1)"
        );
        for (epoch, retransmit_seqs) in &retransmit {
            if let Some(original_seqs) = original.get(epoch) {
                let max_original = original_seqs.iter().copied().max().unwrap_or(0);
                let min_retransmit = retransmit_seqs.iter().copied().min().unwrap_or(0);
                assert!(
                    min_retransmit > max_original,
                    "epoch {epoch}: retransmitted record seq {min_retransmit} must be fresh, not a replay of {max_original}"
                );
            }
        }
    }

    /// RFC 6347 4.2.4: the sender of the last flight has to retransmit it when the peer repeats its
    /// own final flight, because it cannot know its flight arrived. Here the server's last flight
    /// (ChangeCipherSpec + Finished) is lost in transit, the client retransmits Flight 5 on its own
    /// timer, and the server answers with a fresh flight (fresh record sequence numbers, not a
    /// replay) so the client completes.
    #[cfg(feature = "crypto-ring")]
    #[test]
    fn a_completed_server_retransmits_a_fresh_last_flight_so_the_client_completes() -> Result<()> {
        let provider: Arc<dyn RTCCryptoProvider> = Arc::new(crypto::providers::RingProvider::new());
        let suites = [CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_128_Gcm_Sha256];
        let client_config = config(provider.clone(), true, &suites)?;
        let server_config = config(provider, false, &suites)?;
        let mut client = Endpoint::new(client_addr(), TransportProtocol::UDP, None);
        let mut server = Endpoint::new(server_addr(), TransportProtocol::UDP, Some(server_config));
        client.connect(Instant::now(), server_addr(), client_config, None)?;

        // Drive until the server completes. Its last flight is queued at that point, not yet taken.
        let mut server_complete = false;
        for _ in 0..32 {
            for event in transfer(&mut client, &mut server, client_addr())? {
                server_complete |= matches!(event, EndpointEvent::HandshakeComplete);
            }
            if server_complete {
                break;
            }
            transfer(&mut server, &mut client, server_addr())?;
        }
        assert!(server_complete, "the server side never completed");

        // Lose it: capture the server's queued last flight (to compare sequence numbers) but
        // deliver none of it.
        let mut original_last_flight = vec![];
        while let Some(transmit) = server.poll_transmit() {
            original_last_flight.push(transmit.message);
        }
        assert!(
            !original_last_flight.is_empty(),
            "the server had a last flight to lose"
        );

        // The client is still waiting for that flight; its retransmit timer fires and it repeats
        // Flight 5.
        let deadline = client
            .poll_timeout(&server_addr())
            .expect("a client waiting for the last flight arms a retransmit timer");
        client.handle_timeout(server_addr(), deadline)?;
        let mut client_repeat = vec![];
        while let Some(transmit) = client.poll_transmit() {
            client_repeat.push(transmit);
        }
        assert!(
            !client_repeat.is_empty(),
            "the client retransmitted its own flight"
        );

        // RFC 6347 4.2.4 requires the completed server to answer with its last flight again.
        for transmit in client_repeat {
            server.read(
                deadline,
                client_addr(),
                transmit.transport.ecn,
                transmit.message,
            )?;
        }
        let mut retransmit = vec![];
        while let Some(transmit) = server.poll_transmit() {
            retransmit.push(transmit.message);
        }
        assert!(
            !retransmit.is_empty(),
            "a completed server has to retransmit its last flight when the peer repeats its own"
        );
        assert_fresh_sequence_numbers(&original_last_flight, &retransmit);

        // Feed the fresh flight back; the client must now actually complete.
        let mut client_complete = false;
        for datagram in retransmit {
            for event in client.read(deadline, server_addr(), None, datagram)? {
                client_complete |= matches!(event, EndpointEvent::HandshakeComplete);
            }
        }
        assert!(
            client_complete,
            "the client completes once the retransmitted last flight arrives"
        );
        Ok(())
    }

    // Generate the peer's genuine cached flight through the normal retransmission path,
    // including encryption and fresh record sequence numbers.
    #[cfg(feature = "crypto-ring")]
    fn repeat_cached_flight(endpoint: &mut Endpoint, peer: SocketAddr) -> Result<Vec<BytesMut>> {
        let conn = endpoint
            .connections
            .get_mut(&peer)
            .expect("the peer is connected");
        conn.handshake_timeout(Instant::now())?;
        let mut datagrams = vec![];
        while let Some(datagram) = conn.outgoing_raw_packet() {
            datagrams.push(datagram);
        }
        assert!(
            !datagrams.is_empty(),
            "the peer actually repeats its flight"
        );
        Ok(datagrams)
    }

    /// RFC 6347 4.2.4 for the client role: a completed client repeats its own last flight (Flight 5)
    /// when the peer repeats its final flight. Flight 5 carries the client certificate, so it spans
    /// epoch-0 records (certificate/key-exchange/verify/ChangeCipherSpec) plus the epoch-1 Finished,
    /// and each repeat carries fresh record sequence numbers.
    #[cfg(feature = "crypto-ring")]
    #[test]
    fn a_completed_client_retransmits_its_full_last_flight_with_fresh_record_sequence_numbers()
    -> Result<()> {
        let (mut client, mut server) = completed_client_and_server()?;

        for datagram in repeat_cached_flight(&mut server, client_addr())? {
            client.read(Instant::now(), server_addr(), None, datagram)?;
        }
        let mut first = vec![];
        while let Some(transmit) = client.poll_transmit() {
            first.push(transmit.message);
        }
        assert!(!first.is_empty(), "the client retransmits its last flight");
        let epochs: std::collections::HashSet<u16> = first
            .iter()
            .flat_map(|datagram| record_sequence_numbers(datagram))
            .map(|(epoch, _)| epoch)
            .collect();
        assert!(
            epochs.contains(&0) && epochs.contains(&1),
            "the retransmit is the full Flight 5 (epoch-0 records plus the epoch-1 Finished), not a bare answer"
        );

        for datagram in repeat_cached_flight(&mut server, client_addr())? {
            client.read(Instant::now(), server_addr(), None, datagram)?;
        }
        let mut second = vec![];
        while let Some(transmit) = client.poll_transmit() {
            second.push(transmit.message);
        }
        assert!(
            !second.is_empty(),
            "the client retransmits again on the next repeat"
        );
        assert_fresh_sequence_numbers(&first, &second);
        Ok(())
    }

    /// Unauthenticated epoch-0 handshake records must neither provoke a flight nor spend
    /// retries that the real peer may still need. They must not tear down the association.
    #[cfg(feature = "crypto-ring")]
    #[test]
    fn a_completed_client_neither_amplifies_nor_tears_down_when_flooded_with_handshake_records()
    -> Result<()> {
        let (mut client, _server) = completed_client_and_server()?;

        let floods = DEFAULT_MAXIMUM_RETRANSMIT_NUMBER + 5;
        let mut answered = 0usize;
        let mut silent_after_budget = true;
        for index in 0..floods {
            let datagram = junk_epoch_zero_handshake_datagram(10_000 + index as u64);
            let result = client.read(Instant::now(), server_addr(), None, datagram);
            assert!(
                result.is_ok(),
                "read {index} of a junk handshake record must not tear down an established association"
            );
            let mut produced = false;
            while client.poll_transmit().is_some() {
                produced = true;
            }
            if produced {
                answered += 1;
            }
            if index >= DEFAULT_MAXIMUM_RETRANSMIT_NUMBER {
                silent_after_budget &= !produced;
            }
        }
        assert_eq!(answered, 0, "plaintext records must not provoke a flight");
        assert_eq!(
            client.connections[&server_addr()].current_retransmit_count,
            0
        );
        assert!(
            silent_after_budget,
            "the retransmit budget must silence the flood once it is spent"
        );
        Ok(())
    }

    #[cfg(feature = "crypto-ring")]
    #[test]
    fn authenticated_finished_repeats_still_obey_the_retry_budget() -> Result<()> {
        for client_receives in [true, false] {
            let (mut client, mut server) = completed_client_and_server()?;
            let (receiver, sender, receiver_addr, sender_addr) = if client_receives {
                (&mut client, &mut server, client_addr(), server_addr())
            } else {
                (&mut server, &mut client, server_addr(), client_addr())
            };
            let repeats = DEFAULT_MAXIMUM_RETRANSMIT_NUMBER + 5;
            sender
                .connections
                .get_mut(&receiver_addr)
                .unwrap()
                .maximum_retransmit_number = repeats;
            let mut answered = 0;
            for index in 0..repeats {
                for datagram in repeat_cached_flight(sender, receiver_addr)? {
                    receiver.read(Instant::now(), sender_addr, None, datagram)?;
                }
                let mut produced = false;
                while receiver.poll_transmit().is_some() {
                    produced = true;
                }
                if produced {
                    answered += 1;
                }
                if index >= DEFAULT_MAXIMUM_RETRANSMIT_NUMBER {
                    assert!(
                        !produced,
                        "the receiver stops answering after its retry budget"
                    );
                }
            }
            assert_eq!(answered, DEFAULT_MAXIMUM_RETRANSMIT_NUMBER);
            assert!(receiver.connections[&sender_addr].is_handshake_completed());
        }
        Ok(())
    }

    #[cfg(feature = "crypto-ring")]
    #[test]
    fn plaintext_repeats_do_not_change_the_completed_handshake_cache() -> Result<()> {
        use crate::handshake::{HandshakeType, handshake_cache::HandshakeCachePullRule};
        let (mut client, _server) = completed_client_and_server()?;
        let rules = [HandshakeCachePullRule {
            typ: HandshakeType::ServerHelloDone,
            epoch: 0,
            is_client: false,
            optional: false,
        }];
        let before = client.connections[&server_addr()]
            .cache
            .pull_and_merge(&rules);
        assert!(
            !before.is_empty(),
            "the server's original message is cached"
        );
        for sequence in 0u16..32 {
            let mut datagram = vec![22, 0xfe, 0xfd, 0, 0];
            datagram.extend_from_slice(&(1_000 + u64::from(sequence)).to_be_bytes()[2..]);
            datagram.extend_from_slice(&12u16.to_be_bytes());
            datagram.extend_from_slice(&[14, 0, 0, 0]);
            datagram.extend_from_slice(&sequence.to_be_bytes());
            datagram.extend_from_slice(&[0; 6]);
            client.read(
                Instant::now(),
                server_addr(),
                None,
                datagram.as_slice().into(),
            )?;
        }
        assert_eq!(
            client.connections[&server_addr()]
                .cache
                .pull_and_merge(&rules),
            before
        );
        Ok(())
    }

    /// The last-flight retransmission must be gated on this datagram carrying a handshake record,
    /// not on the persisted `handshake_rx` flag. Application data arriving after the handshake โ€”
    /// even with `handshake_rx` left set โ€” must be decrypted and answered with nothing, never with a
    /// spurious flight.
    #[cfg(feature = "crypto-ring")]
    #[test]
    fn application_data_does_not_retrigger_a_completed_client_even_with_a_stale_handshake_flag()
    -> Result<()> {
        let (mut client, mut server) = completed_client_and_server()?;

        // Simulate the leak finding 3 describes: a `handshake_rx` left set from an earlier datagram.
        client
            .connections
            .get_mut(&server_addr())
            .expect("the client holds the association")
            .handshake_rx = Some(());

        server.write(
            Instant::now(),
            client_addr(),
            b"post-handshake application data",
        )?;
        let events = transfer(&mut server, &mut client, server_addr())?;
        assert!(
            events.iter().any(|event| matches!(
                event,
                EndpointEvent::ApplicationData(data) if data.as_ref() == b"post-handshake application data"
            )),
            "the completed client still decrypts application data"
        );
        assert!(
            client.poll_transmit().is_none(),
            "application data must not make a completed client emit a handshake flight"
        );
        Ok(())
    }

    /// A peer's close_notify (RFC 5246 ยง7.2.1) ends the connection gracefully: data that arrived
    /// before it is still delivered, the close is reported as an event rather than an error, the
    /// matching close_notify reply is sent, and the connection is dropped (rtc#255).
    #[cfg(feature = "crypto-ring")]
    #[test]
    fn a_peer_close_notify_is_answered_and_reported() -> Result<()> {
        use crate::content::ContentType;

        let (mut client, mut server) = completed_client_and_server()?;

        client.write(Instant::now(), server_addr(), b"before close")?;
        client.close(Instant::now())?;
        let events = transfer(&mut client, &mut server, client_addr())?;

        assert!(
            matches!(
                events.as_slice(),
                [EndpointEvent::ApplicationData(data), EndpointEvent::PeerClosed]
                    if data.as_ref() == b"before close"
            ),
            "expected the data, then PeerClosed"
        );
        assert!(
            server.connections.is_empty(),
            "the closed connection is removed"
        );

        let reply = server
            .poll_transmit()
            .expect("the close_notify reply is sent");
        assert_eq!(
            ContentType::Alert as u8,
            reply.message[0],
            "the reply is an alert record"
        );
        assert!(server.poll_transmit().is_none());
        Ok(())
    }

    /// Once the handshake has completed, a genuine peer sends nothing but handshake records
    /// (repeating its final flight) in epoch 0, so any other plaintext record can only be forged
    /// or stale. None of them may close the connection, fail the read or provoke an alert:
    /// otherwise anyone able to spoof the peer's address could tear down an authenticated
    /// association with one unauthenticated datagram (RFC 6347 ยง4.1.2.7: invalid records are
    /// silently discarded).
    #[cfg(feature = "crypto-ring")]
    #[test]
    fn a_plaintext_record_cannot_close_an_established_connection() -> Result<()> {
        use crate::alert::{AlertDescription, AlertLevel};

        let (mut client, mut server) = completed_client_and_server()?;

        let close_notify = [
            AlertLevel::Warning as u8,
            AlertDescription::CloseNotify as u8,
        ];
        let fatal = [
            AlertLevel::Fatal as u8,
            AlertDescription::HandshakeFailure as u8,
        ];
        let forgeries: [(&str, u8, &[u8]); 7] = [
            ("close_notify alert", 21, &close_notify),
            ("fatal alert", 21, &fatal),
            ("truncated alert", 21, &[AlertLevel::Fatal as u8]),
            ("application data", 23, b"forged"),
            ("change_cipher_spec", 20, &[0x01]),
            ("malformed change_cipher_spec", 20, &[0x02]),
            ("unknown content type", 99, b"forged"),
        ];
        for (sequence_number, (name, content_type, body)) in (1_000_000..).zip(forgeries) {
            let forged = plaintext_record_datagram(content_type, body, sequence_number);
            let events = server.read(Instant::now(), client_addr(), None, forged)?;
            assert!(
                events.is_empty(),
                "a forged {name} was reported as {} event(s)",
                events.len()
            );
            assert!(
                server.connections.contains_key(&client_addr()),
                "a forged {name} removed the connection"
            );
            assert!(
                server.poll_transmit().is_none(),
                "a forged {name} was answered"
            );
        }

        // and the connection still carries data both ways
        client.write(Instant::now(), server_addr(), b"still here")?;
        let events = transfer(&mut client, &mut server, client_addr())?;
        assert!(
            events.iter().any(|event| matches!(
                event,
                EndpointEvent::ApplicationData(data) if data.as_ref() == b"still here"
            )),
            "the connection stopped carrying data after a forged record"
        );
        server.write(Instant::now(), client_addr(), b"and back")?;
        let events = transfer(&mut server, &mut client, server_addr())?;
        assert!(
            events.iter().any(|event| matches!(
                event,
                EndpointEvent::ApplicationData(data) if data.as_ref() == b"and back"
            )),
            "the connection stopped carrying data back after a forged record"
        );
        Ok(())
    }

    /// Once a PSK handshake has completed, a record that fails to decrypt (which anyone spoofing
    /// the peer's address can send) must be silently discarded, not answered with a fatal alert
    /// (RFC 6347 ยง4.1.2.7).
    #[cfg(feature = "crypto-ring")]
    #[test]
    fn a_record_that_fails_to_decrypt_cannot_close_an_established_psk_connection() -> Result<()> {
        use crate::content::ContentType;
        use crate::record_layer::record_layer_header::{PROTOCOL_VERSION1_2, RecordLayerHeader};

        let (mut client, mut server) =
            completed_client_and_server_with(&[CipherSuiteId::Tls_Psk_With_Aes_128_Gcm_Sha256])?;

        let body = [0x5a; 40];
        let mut forged = vec![];
        RecordLayerHeader {
            content_type: ContentType::ApplicationData,
            protocol_version: PROTOCOL_VERSION1_2,
            epoch: 1,
            sequence_number: 1_000_000,
            content_len: body.len() as u16,
        }
        .marshal(&mut forged)
        .expect("a record header marshals");
        forged.extend_from_slice(&body);

        let events = server.read(
            Instant::now(),
            client_addr(),
            None,
            BytesMut::from(&forged[..]),
        )?;
        assert!(events.is_empty());
        assert!(
            server.poll_transmit().is_none(),
            "a forged record was answered"
        );

        // the connection still carries data
        client.write(Instant::now(), server_addr(), b"still here")?;
        let events = transfer(&mut client, &mut server, client_addr())?;
        assert!(events.iter().any(|event| matches!(
            event,
            EndpointEvent::ApplicationData(data) if data.as_ref() == b"still here"
        )));
        Ok(())
    }

    /// The other half of that rule: during the handshake a PSK peer whose Finished fails to
    /// decrypt holds a different key for its identity, and is still told so with a fatal alert.
    #[cfg(feature = "crypto-ring")]
    #[test]
    fn a_psk_handshake_with_the_wrong_key_is_still_answered_with_an_alert() -> Result<()> {
        use crate::content::ContentType;

        let provider: Arc<dyn RTCCryptoProvider> = Arc::new(crypto::providers::RingProvider::new());
        let suites = [CipherSuiteId::Tls_Psk_With_Aes_128_Gcm_Sha256];
        let client_config = Arc::new(
            ConfigBuilder::default()
                .with_crypto_provider(provider.clone())
                .with_cipher_suites(suites.to_vec())
                .with_psk(Some(Arc::new(|_| Ok(vec![0x01, 0x02, 0x03]))))
                .with_psk_identity_hint(Some(b"rtc-dtls-test".to_vec()))
                .build(true, None)?,
        );
        let server_config = config(provider, false, &suites)?;
        let mut client = Endpoint::new(client_addr(), TransportProtocol::UDP, None);
        let mut server = Endpoint::new(server_addr(), TransportProtocol::UDP, Some(server_config));
        client.connect(Instant::now(), server_addr(), client_config, None)?;

        let mut rejected = None;
        for _ in 0..4 {
            if let Err(err) = transfer(&mut client, &mut server, client_addr()) {
                rejected = Some(err);
                break;
            }
            transfer(&mut server, &mut client, server_addr())?;
        }
        assert!(matches!(rejected, Some(Error::ErrAlertFatalOrClose)));
        let alert = server
            .poll_transmit()
            .expect("the server answers with an alert");
        assert_eq!(alert.message.first(), Some(&(ContentType::Alert as u8)));
        // RFC 6347 4.1.2.1: the alert for a record that fails authentication is
        // bad_record_mac(20), at fatal level (4.1.2.7).
        assert_eq!(&alert.message[13..], &[2, 20]);
        Ok(())
    }
}