rtci 0.5.0

A sans-I/O WebRTC implementation: peer connections with ICE, DTLS-SRTP, SCTP data channels, RTP/RTCP and JSEP negotiation
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
//! RFC 8842 section 5.5, the NOTE: "When a new DTLS association is being established, each
//! endpoint needs to be prepared to receive data on both the new and old DTLS associations as
//! long as both are alive." Section 5.1 says how they are told apart over UDP: "The only way to
//! demultiplex packets associated with a previously established DTLS association and the new
//! DTLS association is on the basis of the 5-tuple."
//!
//! The ICE handler reads a DTLS datagram that arrived on a local address of the replaced
//! association as `DTLSMessage::PreviousAssociation`; these tests hand the DTLS handler such
//! datagrams directly. The handler is the DTLS server of both associations; each association's
//! peer is an endpoint of its own (the peer's new association is a new endpoint too).

use super::*;
use crate::peer_connection::handler::previous_association_path::{
    PreviousAssociationPath, PreviousPathRoute,
};
use crate::peer_connection::transport::dtls::fingerprint::RTCDtlsFingerprint;
use crate::peer_connection::transport::dtls::parameters::RTCDtlsParameters;
use crate::peer_connection::transport::dtls::{
    DtlsAssociationUpdate, DtlsRemoteUpdate, PREVIOUS_ASSOCIATION_MAX, RTCDtlsTransportConfig,
};
use crate::peer_connection::transport::ice::role::RTCIceRole;
use crate::peer_connection::transport::{RTCTransportId, TransportKind};
use bytes::BytesMut;
use dtls::config::{ConfigBuilder, ExtendedMasterSecretType};
use dtls::endpoint::Endpoint;
use sansio::Protocol;
use std::time::Duration;

/// The address the peers know the handler by (the handler knows each by the placeholder).
fn handler_addr() -> SocketAddr {
    "10.0.0.1:4000".parse().unwrap()
}

/// The handler's side: its context and stats.
struct Side {
    ctx: DtlsHandlerContext,
    stats: RTCStatsAccumulator,
    /// Application data the handler delivered, in order.
    delivered: Vec<Vec<u8>>,
    /// What the handler sent on the replaced association's path, in order.
    sent_on_previous: Vec<BytesMut>,
    /// The events it raised.
    events: Vec<RTCEventInternal>,
}

impl Side {
    /// A DTLS transport started as the server, its peer the client.
    fn server() -> Result<Self> {
        let provider = crypto::default_provider().expect("a built-in crypto provider");
        let mut transport = DtlsTransport::new(RTCDtlsTransportConfig {
            id: RTCTransportId::new(0x0123_4567_89ab_cdef, TransportKind::Dtls),
            ice_transport_id: RTCTransportId::new(0x0123_4567_89ab_cdef, TransportKind::Ice),
            certificates: vec![],
            answering_dtls_role: Default::default(),
            srtp_protection_profiles: vec![],
            use_srtp_always: true,
            dtls_cipher_suites: vec![],
            allow_insecure_verification_algorithm: false,
            disable_certificate_fingerprint_verification: true,
            replay_protection: Default::default(),
            crypto_provider: provider,
        })?;
        transport.start(RTCIceRole::Controlling, remote(None))?;
        assert_eq!(transport.role(), RTCDtlsRole::Server);
        Ok(Self {
            ctx: DtlsHandlerContext::new(transport),
            stats: RTCStatsAccumulator::default(),
            delivered: vec![],
            sent_on_previous: vec![],
            events: vec![],
        })
    }

    fn handler(&mut self) -> DtlsHandler<'_> {
        DtlsHandler::new(&mut self.ctx, &mut self.stats)
    }

    /// Hands the handler what `peer` sent: as datagrams of the replaced association
    /// (`previous`), or as any other. Then takes what the handler delivered and raised; what it
    /// sent on the current association goes to `current_peer`, if given.
    fn read_from(
        &mut self,
        now: Instant,
        peer: &mut Endpoint,
        previous: bool,
        current_peer: Option<&mut Endpoint>,
    ) {
        while let Some(transmit) = peer.poll_transmit() {
            let message = if previous {
                DTLSMessage::PreviousAssociation(transmit.message)
            } else {
                DTLSMessage::Raw(transmit.message)
            };
            let _ = self.handler().handle_read(TaggedRTCMessageInternal {
                now,
                transport: TransportContext::default(),
                message: RTCMessageInternal::Dtls(message),
            });
        }
        self.take(now, current_peer);
    }

    /// Takes what the handler delivered, raised and sent; `true` when it sent anything on the
    /// current association (to `current_peer`, if given).
    fn take(&mut self, now: Instant, mut current_peer: Option<&mut Endpoint>) -> bool {
        while let Some(read) = self.handler().poll_read() {
            if let RTCMessageInternal::Dtls(DTLSMessage::Raw(data)) = read.message {
                self.delivered.push(data.to_vec());
            }
        }
        while let Some(event) = self.handler().poll_event() {
            self.events.push(event.event);
        }
        let mut sent = false;
        while let Some(written) = self.handler().poll_write() {
            match written.message {
                RTCMessageInternal::Dtls(DTLSMessage::PreviousAssociation(data)) => {
                    self.sent_on_previous.push(data)
                }
                RTCMessageInternal::Dtls(DTLSMessage::Raw(data)) => {
                    sent = true;
                    if let Some(peer) = current_peer.as_deref_mut() {
                        let _ = peer.read(now, handler_addr(), None, data);
                    }
                }
                _ => {}
            }
        }
        sent
    }

    /// Runs a handshake between the handler and `peer` (which has connected), the peer's
    /// datagrams read as the current association's, until neither sends anything. `true` once
    /// the handler reported it complete.
    fn handshake(&mut self, now: Instant, peer: &mut Endpoint) -> bool {
        let before = self.completions();
        for _ in 0..20 {
            let mut progressed = false;
            while let Some(transmit) = peer.poll_transmit() {
                progressed = true;
                let _ = self.handler().handle_read(TaggedRTCMessageInternal {
                    now,
                    transport: TransportContext::default(),
                    message: RTCMessageInternal::Dtls(DTLSMessage::Raw(transmit.message)),
                });
            }
            progressed |= self.take(now, Some(peer));
            if !progressed {
                break;
            }
        }
        self.completions() > before
    }

    fn completions(&self) -> usize {
        self.events
            .iter()
            .filter(|event| matches!(event, RTCEventInternal::DTLSHandshakeComplete(..)))
            .count()
    }

    /// A remote description that asks for a new association (a changed fingerprint, RFC 8842
    /// section 3.1) with an ICE restart, the replaced association kept until `keep_until`.
    fn new_association(&mut self, fingerprint: &str, keep_until: Option<Instant>) {
        let update = self
            .ctx
            .dtls_transport
            .update_remote(
                RTCIceRole::Controlling,
                remote(Some(fingerprint)),
                None,
                DtlsRemoteUpdate {
                    ice_restart: true,
                    keep_previous_until: keep_until,
                    ..Default::default()
                },
            )
            .expect("the new association's config");
        assert_eq!(update, DtlsAssociationUpdate::New, "a changed fingerprint");
        assert_eq!(self.ctx.dtls_transport.role(), RTCDtlsRole::Server);
    }
}

/// The peer's parameters: the client, with `fingerprint` (verification is off in these tests:
/// the value only tells the associations apart).
fn remote(fingerprint: Option<&str>) -> RTCDtlsParameters {
    RTCDtlsParameters {
        role: RTCDtlsRole::Client,
        fingerprints: fingerprint
            .map(|value| RTCDtlsFingerprint {
                algorithm: "sha-256".to_owned(),
                value: value.to_owned(),
            })
            .into_iter()
            .collect(),
    }
}

/// A peer client that has sent its ClientHello to the handler.
fn peer_client(now: Instant) -> Result<Endpoint> {
    let provider = crypto::default_provider().expect("a built-in crypto provider");
    let certificate =
        dtls::crypto::Certificate::generate_self_signed(vec!["peer".into()], provider.crypto())?;
    let config = Arc::new(
        ConfigBuilder::default()
            .with_crypto_provider(provider)
            .with_certificates(vec![certificate])
            .with_insecure_skip_verify(true)
            .with_extended_master_secret(ExtendedMasterSecretType::Require)
            .build(true, None)?,
    );
    let mut peer = Endpoint::new(
        TransportContext::default().peer_addr,
        shared::TransportProtocol::UDP,
        None,
    );
    peer.connect(now, handler_addr(), config, None)?;
    Ok(peer)
}

/// The handler connected to `old`, its first association.
fn connected(now: Instant) -> Result<(Side, Endpoint)> {
    let mut side = Side::server()?;
    let mut old = peer_client(now)?;
    assert!(side.handshake(now, &mut old), "the first association");
    assert_eq!(
        side.ctx.dtls_transport.state(),
        RTCDtlsTransportState::Connected
    );
    // The first association carries data.
    old.write(now, handler_addr(), b"before")?;
    side.read_from(now, &mut old, false, None);
    assert_eq!(
        side.delivered,
        [b"before".to_vec()],
        "the first association"
    );
    side.delivered.clear();
    Ok((side, old))
}

/// While the new association's handshake runs, what the peer still sends on the replaced one
/// (on its 5-tuple) is read and delivered, before and during the new handshake.
#[test]
fn records_of_the_replaced_association_are_read_while_the_new_handshake_runs() -> Result<()> {
    let now = Instant::now();
    let (mut side, mut old) = connected(now)?;
    side.new_association("01", Some(now + PREVIOUS_ASSOCIATION_MAX));
    assert_eq!(
        side.ctx.dtls_transport.state(),
        RTCDtlsTransportState::Connecting,
        "the new association's handshake is due"
    );

    // The peer has not switched yet.
    old.write(now, handler_addr(), b"on the old association")?;
    side.read_from(now, &mut old, true, None);
    assert_eq!(
        side.delivered,
        [b"on the old association".to_vec()],
        "a record of the replaced association, read while the new one forms"
    );

    // The new handshake begins (the peer's ClientHello and the handler's answer on the new
    // path); the old association still delivers.
    let mut new = peer_client(now)?;
    side.read_from(now, &mut new, false, Some(&mut new_peer_sink()));
    assert_eq!(
        side.ctx.dtls_transport.state(),
        RTCDtlsTransportState::Connecting
    );
    old.write(now, handler_addr(), b"both alive")?;
    side.read_from(now, &mut old, true, None);
    assert_eq!(
        side.delivered,
        [b"on the old association".to_vec(), b"both alive".to_vec()],
        "while both are alive"
    );
    assert!(side.ctx.dtls_transport.previous_association.is_open());
    assert!(
        side.sent_on_previous.is_empty(),
        "nothing is sent on the replaced association while it is kept"
    );
    Ok(())
}

/// An endpoint that takes the handler's answers in a step where the test does not need them.
fn new_peer_sink() -> Endpoint {
    Endpoint::new(
        TransportContext::default().peer_addr,
        shared::TransportProtocol::UDP,
        None,
    )
}

/// Once the new association's handshake completes the replaced one is closed: its
/// `close_notify` goes out on its path, its endpoint (and its keys) are gone, and what still
/// comes on its 5-tuple is refused.
#[test]
fn once_the_new_handshake_completes_the_replaced_association_is_closed() -> Result<()> {
    let now = Instant::now();
    let (mut side, mut old) = connected(now)?;
    side.new_association("01", Some(now + PREVIOUS_ASSOCIATION_MAX));
    assert!(side.ctx.dtls_transport.previous_association.is_open());

    let mut new = peer_client(now)?;
    assert!(side.handshake(now, &mut new), "the new association");
    assert_eq!(
        side.ctx.dtls_transport.state(),
        RTCDtlsTransportState::Connected
    );
    assert!(
        matches!(
            side.ctx.dtls_transport.previous_association,
            PreviousAssociation::Closed
        ),
        "the replaced association is closed and its endpoint dropped"
    );
    assert_eq!(
        side.poll_timeout_of_previous(),
        None,
        "no timer of it is left"
    );

    // A record the peer sent on the old association before it saw the close.
    old.write(now, handler_addr(), b"too late")?;
    let late: Vec<BytesMut> = std::iter::from_fn(|| old.poll_transmit())
        .map(|t| t.message)
        .collect();
    assert!(
        !late.is_empty(),
        "the peer's old association wrote a record"
    );

    // The close_notify went out on the replaced association's path, and the peer's old
    // association takes it as its end.
    assert!(
        !side.sent_on_previous.is_empty(),
        "a close_notify on the replaced association"
    );
    let mut closed = false;
    for datagram in std::mem::take(&mut side.sent_on_previous) {
        closed |= old
            .read(now, handler_addr(), None, datagram)?
            .iter()
            .any(|event| matches!(event, dtls::endpoint::EndpointEvent::PeerClosed));
    }
    assert!(closed, "the peer's old association was closed by it");

    for datagram in late {
        let _ = side.handler().handle_read(TaggedRTCMessageInternal {
            now,
            transport: TransportContext::default(),
            message: RTCMessageInternal::Dtls(DTLSMessage::PreviousAssociation(datagram)),
        });
    }
    side.take(now, None);
    assert!(
        side.delivered.is_empty(),
        "a record of the closed association is refused: {:?}",
        side.delivered
    );
    // The new association carries data.
    new.write(now, handler_addr(), b"on the new association")?;
    side.read_from(now, &mut new, false, None);
    assert_eq!(side.delivered, [b"on the new association".to_vec()]);
    Ok(())
}

impl Side {
    /// The replaced association's part of the handler's timer, if one is kept.
    fn poll_timeout_of_previous(&self) -> Option<Instant> {
        self.ctx.dtls_transport.previous_association.until()
    }
}

/// The bound: the replaced association is kept at most `PREVIOUS_ASSOCIATION_MAX` from its
/// replacement, whatever the new handshake does, and a peer that asks for yet another new
/// association meanwhile does not extend it (at most one is kept). Then it is closed, its
/// keys go with its endpoint, and its records are refused.
#[test]
fn the_replaced_association_is_kept_no_longer_than_its_bound() -> Result<()> {
    let start = Instant::now();
    let (mut side, mut old) = connected(start)?;
    let bound = start + PREVIOUS_ASSOCIATION_MAX;
    side.new_association("01", Some(bound));
    assert_eq!(side.poll_timeout_of_previous(), Some(bound));
    assert!(
        side.handler().poll_timeout().is_some_and(|at| at <= bound),
        "the handler wakes for the bound"
    );

    // Another new association before the first one's handshake completed: the established
    // one is still the one kept, with its own bound.
    let later = start + Duration::from_secs(10);
    side.new_association("02", Some(later + PREVIOUS_ASSOCIATION_MAX));
    assert_eq!(
        side.poll_timeout_of_previous(),
        Some(bound),
        "renegotiating does not extend the bound"
    );

    // Just inside the bound it still delivers.
    let inside = bound - Duration::from_millis(1);
    side.handler().handle_timeout(inside)?;
    side.take(inside, None);
    old.write(inside, handler_addr(), b"inside the bound")?;
    side.read_from(inside, &mut old, true, None);
    assert_eq!(side.delivered, [b"inside the bound".to_vec()]);

    // At the bound it is closed.
    side.handler().handle_timeout(bound)?;
    side.take(bound, None);
    assert!(
        matches!(
            side.ctx.dtls_transport.previous_association,
            PreviousAssociation::Closed
        ),
        "closed at its bound, its endpoint dropped"
    );
    assert!(
        !side.sent_on_previous.is_empty(),
        "its close_notify on its path"
    );
    old.write(bound, handler_addr(), b"past the bound")?;
    side.read_from(bound, &mut old, true, None);
    assert_eq!(
        side.delivered,
        [b"inside the bound".to_vec()],
        "refused past the bound"
    );
    Ok(())
}

/// The replaced association's path as the ICE handler holds it, and its protocol.
struct OnPath {
    path: PreviousAssociationPath,
    protocol: shared::TransportProtocol,
}

impl OnPath {
    fn new(protocol: shared::TransportProtocol) -> Self {
        Self {
            path: PreviousAssociationPath::new(ice::agent::MediaPath {
                local_addr: "10.0.0.1:5000".parse().unwrap(),
                peer_addr: "10.0.0.2:5000".parse().unwrap(),
                transport_protocol: protocol,
            }),
            protocol,
        }
    }

    /// What the ICE handler hands the DTLS handler for a datagram that arrived on this path
    /// (`IceHandler::read`, `PreviousAssociationPath::route_read`).
    fn routed(&mut self, datagram: BytesMut) -> DTLSMessage {
        let on_path = TransportContext {
            local_addr: "10.0.0.1:5000".parse().unwrap(),
            peer_addr: "10.0.0.2:5000".parse().unwrap(),
            transport_protocol: self.protocol,
            ecn: None,
        };
        match self.path.route_read(&on_path, &datagram) {
            Some(PreviousPathRoute::Previous) => DTLSMessage::PreviousAssociation(datagram),
            Some(PreviousPathRoute::Either) => DTLSMessage::PreviousPath(datagram),
            Some(PreviousPathRoute::Current) => DTLSMessage::Raw(datagram),
            None => panic!("the datagram is on the path"),
        }
    }
}

impl Side {
    /// Hands the handler what `peer` sent on the replaced association's path, routed as the
    /// ICE handler routes it; what the handler sends on the current association goes to
    /// `current_peer`. Returns whether the handler sent anything on it.
    fn read_on_path(
        &mut self,
        now: Instant,
        peer: &mut Endpoint,
        path: &mut OnPath,
        current_peer: Option<&mut Endpoint>,
    ) -> bool {
        let mut read = false;
        while let Some(transmit) = peer.poll_transmit() {
            read = true;
            let message = path.routed(transmit.message);
            let _ = self.handler().handle_read(TaggedRTCMessageInternal {
                now,
                transport: TransportContext::default(),
                message: RTCMessageInternal::Dtls(message),
            });
        }
        self.take(now, current_peer) || read
    }

    /// A handshake with `peer` whose every datagram arrives on the replaced association's path.
    fn handshake_on_path(&mut self, now: Instant, peer: &mut Endpoint, path: &mut OnPath) -> bool {
        let before = self.completions();
        for _ in 0..20 {
            let mut sent = false;
            while let Some(transmit) = peer.poll_transmit() {
                sent = true;
                let message = path.routed(transmit.message);
                let _ = self.handler().handle_read(TaggedRTCMessageInternal {
                    now,
                    transport: TransportContext::default(),
                    message: RTCMessageInternal::Dtls(message),
                });
            }
            let answered = self.take(now, Some(peer));
            if !sent && !answered {
                break;
            }
        }
        self.completions() > before
    }
}

/// A new association on the 5-tuple the replaced one runs on, over UDP (neither side allocated a
/// new 3-tuple: `with_dtls_new_association_on_previous_addresses(true)` on both sides, or a new
/// association without an ICE restart). RFC 8842 section 5.1 has no 5-tuple to tell them apart
/// by; the records do: the new handshake's records in the clear go to the new association, a
/// protected record is the replaced association's when it authenticates under its keys, else
/// the new one's. Both deliver while both are alive; once the new one is established the
/// replaced one is closed and its records are refused.
#[test]
fn on_a_shared_udp_five_tuple_each_association_reads_its_own_records() -> Result<()> {
    let now = Instant::now();
    let (mut side, mut old) = connected(now)?;
    side.new_association("01", Some(now + PREVIOUS_ASSOCIATION_MAX));
    let mut path = OnPath::new(shared::TransportProtocol::UDP);

    old.write(now, handler_addr(), b"old, before the new handshake")?;
    side.read_on_path(now, &mut old, &mut path, None);
    assert_eq!(
        side.delivered,
        [b"old, before the new handshake".to_vec()],
        "a protected record of the replaced association, read by it"
    );

    // The new handshake runs on the same 5-tuple; the old association still delivers during
    // it.
    let mut new = peer_client(now)?;
    let first: Vec<BytesMut> = std::iter::from_fn(|| new.poll_transmit())
        .map(|t| t.message)
        .collect();
    for datagram in first {
        let message = path.routed(datagram);
        assert!(
            matches!(message, DTLSMessage::Raw(_)),
            "the ClientHello, in the clear, is the new association's"
        );
        let _ = side.handler().handle_read(TaggedRTCMessageInternal {
            now,
            transport: TransportContext::default(),
            message: RTCMessageInternal::Dtls(message),
        });
    }
    side.take(now, Some(&mut new));
    old.write(now, handler_addr(), b"old, during the new handshake")?;
    side.read_on_path(now, &mut old, &mut path, None);
    assert_eq!(side.delivered.len(), 2, "both alive: {:?}", side.delivered);

    assert!(
        side.handshake_on_path(now, &mut new, &mut path),
        "the new association's handshake completes on the shared 5-tuple"
    );
    assert!(matches!(
        side.ctx.dtls_transport.previous_association,
        PreviousAssociation::Closed
    ));
    old.write(now, handler_addr(), b"old, too late")?;
    side.read_on_path(now, &mut old, &mut path, None);
    new.write(now, handler_addr(), b"new")?;
    side.read_on_path(now, &mut new, &mut path, None);
    assert_eq!(
        side.delivered,
        [
            b"old, before the new handshake".to_vec(),
            b"old, during the new handshake".to_vec(),
            b"new".to_vec()
        ],
        "the replaced association's late record is refused, the new one's delivered"
    );
    Ok(())
}

/// The replaced association ran on an ICE-TCP connection, and the new one's handshake comes on
/// the same connection. RFC 8842 section 5.1, an ordered transport: "sending packets for the new
/// DTLS association after all packets associated with a previously established DTLS
/// association have been sent". What comes before the new association's first record is the
/// replaced association's; from that record on, everything is the new one's, even a record the
/// replaced association could read.
#[test]
fn on_a_tcp_connection_the_records_before_the_new_handshake_are_the_old_associations() -> Result<()>
{
    let now = Instant::now();
    let (mut side, mut old) = connected(now)?;
    side.new_association("01", Some(now + PREVIOUS_ASSOCIATION_MAX));
    let mut path = OnPath::new(shared::TransportProtocol::TCP);

    old.write(now, handler_addr(), b"before the new association")?;
    side.read_on_path(now, &mut old, &mut path, None);
    assert_eq!(side.delivered, [b"before the new association".to_vec()]);

    // The new association's first record on the connection.
    let mut new = peer_client(now)?;
    let first: Vec<BytesMut> = std::iter::from_fn(|| new.poll_transmit())
        .map(|t| t.message)
        .collect();
    assert!(!first.is_empty(), "the new peer's ClientHello");
    for datagram in first {
        let message = path.routed(datagram);
        assert!(
            matches!(message, DTLSMessage::Raw(_)),
            "the new association's first record is the current association's"
        );
        let _ = side.handler().handle_read(TaggedRTCMessageInternal {
            now,
            transport: TransportContext::default(),
            message: RTCMessageInternal::Dtls(message),
        });
    }
    side.take(now, Some(&mut new));
    assert!(side.ctx.dtls_transport.previous_association.is_open());

    // Out of order: a record of the replaced association after the new one began on the
    // connection is not the replaced association's any more.
    old.write(now, handler_addr(), b"out of order")?;
    side.read_on_path(now, &mut old, &mut path, None);
    assert_eq!(
        side.delivered,
        [b"before the new association".to_vec()],
        "not read by the replaced association"
    );

    assert!(
        side.handshake_on_path(now, &mut new, &mut path),
        "the new association's handshake completes on the connection"
    );
    new.write(now, handler_addr(), b"new")?;
    side.read_on_path(now, &mut new, &mut path, None);
    assert_eq!(
        side.delivered,
        [b"before the new association".to_vec(), b"new".to_vec()]
    );
    Ok(())
}

/// RFC 8446 appendix E.1.4: exporter secrets "SHOULD be erased as soon as possible", and,
/// the labels being known, each inner value "as soon as it is known that it will not be
/// needed again". The engine's one export of an association is its DTLS-SRTP keys, at the
/// handshake's completion: once the association is up, nothing more can be exported from the
/// handler's side, while the peer endpoint, which erases nothing by itself, still can.
#[test]
fn the_exporter_secret_is_erased_once_the_handshake_completes() -> Result<()> {
    let now = Instant::now();
    let (side, old) = connected(now)?;
    let state = side
        .ctx
        .dtls_transport
        .dtls_endpoint
        .as_ref()
        .and_then(|endpoint| endpoint.get_connection_state(TransportContext::default().peer_addr))
        .expect("the handler's association");
    assert_eq!(
        state.negotiated_version(),
        Some(dtls::config::DtlsVersion::Dtls1_3)
    );
    assert!(matches!(
        state.export_keying_material("EXTRACTOR-dtls_srtp", &[], 60),
        Err(Error::ExporterSecretForgotten)
    ));
    assert!(
        old.get_connection_state(handler_addr())
            .expect("the peer's association")
            .export_keying_material("EXTRACTOR-dtls_srtp", &[], 60)
            .is_ok(),
        "the peer endpoint still exports"
    );
    Ok(())
}