rtci-turn 0.4.1

Sans-I/O TURN client (RFC 8656, RFC 6062 TCP allocations) 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
use super::*;
use sansio::Protocol;
use std::collections::HashSet;
use std::net::UdpSocket;

fn create_test_client_with_turn_server() -> Result<(UdpSocket, Client)> {
    let udp_socket = UdpSocket::bind("127.0.0.1:0")?;

    let client = Client::new(
        ClientConfig {
            stun_serv_addr: String::new(),
            turn_serv_addr: format!("127.0.0.1:{}", udp_socket.local_addr()?.port()),
            local_addr: udp_socket.local_addr()?,
            transport_protocol: TransportProtocol::UDP,
            username: "user".to_string(),
            password: "pass".to_string(),
            realm: "test".to_string(),
            software: "TEST SOFTWARE".to_owned(),
            rto_in_ms: 0,
            allocation_refresh_interval_cap: None,
            ..Default::default()
        },
        test_crypto_provider(),
    )?;

    Ok((udp_socket, client))
}

/// Tests may resolve the built-in provider; library code never does.
fn test_crypto_provider() -> std::sync::Arc<dyn crypto::RTCCryptoProvider> {
    crypto::default_provider().expect("a built-in crypto provider must be enabled for tests")
}

fn create_listening_test_client(rto_in_ms: u64) -> Result<(UdpSocket, Client)> {
    let udp_socket = UdpSocket::bind("0.0.0.0:0")?;

    let client = Client::new(
        ClientConfig {
            stun_serv_addr: String::new(),
            turn_serv_addr: String::new(),
            local_addr: udp_socket.local_addr()?,
            transport_protocol: TransportProtocol::UDP,
            username: String::new(),
            password: String::new(),
            realm: String::new(),
            software: "TEST SOFTWARE".to_owned(),
            rto_in_ms,
            allocation_refresh_interval_cap: None,
            ..Default::default()
        },
        test_crypto_provider(),
    )?;

    Ok((udp_socket, client))
}

/// How long a test waits for a datagram on loopback. A lost datagram, or a responder that never
/// answers, fails the test after this instead of blocking the job until CI cancels it.
const READ_TIMEOUT: Duration = Duration::from_secs(5);

/// The next datagram on `conn`, waiting at most [`READ_TIMEOUT`]; `what` names it in the panic.
fn recv_within(conn: &UdpSocket, buffer: &mut [u8], what: &str) -> (usize, SocketAddr) {
    conn.set_read_timeout(Some(READ_TIMEOUT))
        .expect("a UDP socket takes a read timeout");
    match conn.recv_from(buffer) {
        Ok(received) => received,
        Err(err)
            if matches!(
                err.kind(),
                std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
            ) =>
        {
            panic!(
                "no {what} within {READ_TIMEOUT:?} on {:?}",
                conn.local_addr()
            )
        }
        Err(err) => panic!("receiving {what} failed: {err}"),
    }
}

/// A STUN server on a loopback socket of this process: it answers each Binding request it reads
/// with a success response whose XOR-MAPPED-ADDRESS is the address the request came from
/// (RFC 8489 section 14.2), the server-reflexive address a public server would report.
struct LoopbackStunServer {
    socket: UdpSocket,
}

impl LoopbackStunServer {
    fn bind() -> Result<Self> {
        Ok(LoopbackStunServer {
            socket: UdpSocket::bind("127.0.0.1:0")?,
        })
    }

    fn addr(&self) -> Result<SocketAddr> {
        Ok(self.socket.local_addr()?)
    }

    /// Reads one Binding request and answers it; returns the address it was answered at.
    fn answer_one(&self) -> Result<SocketAddr> {
        let mut buffer = vec![0u8; 2048];
        let (n, from) = recv_within(&self.socket, &mut buffer, "Binding request at the server");
        let mut request = Message::new();
        request.raw = buffer[..n].to_vec();
        request.decode()?;
        assert_eq!(
            request.typ, BINDING_REQUEST,
            "the client sends a Binding request"
        );
        let response = test_server::TestServer::new()?.reply(
            &request,
            CLASS_SUCCESS_RESPONSE,
            vec![Box::new(XorMappedAddress {
                ip: from.ip(),
                port: from.port(),
            })],
            None,
        )?;
        self.socket.send_to(&response, from)?;
        Ok(from)
    }
}

/// A client whose STUN server is `stun_server`, on a loopback socket of its own.
fn create_test_client_with_stun_server(stun_server: SocketAddr) -> Result<(UdpSocket, Client)> {
    let udp_socket = UdpSocket::bind("127.0.0.1:0")?;

    let client = Client::new(
        ClientConfig {
            stun_serv_addr: stun_server.to_string(),
            turn_serv_addr: String::new(),
            local_addr: udp_socket.local_addr()?,
            transport_protocol: TransportProtocol::UDP,
            username: String::new(),
            password: String::new(),
            realm: String::new(),
            software: "TEST SOFTWARE".to_owned(),
            rto_in_ms: 0,
            allocation_refresh_interval_cap: None,
            ..Default::default()
        },
        test_crypto_provider(),
    )?;

    Ok((udp_socket, client))
}

/// A host demultiplexing STUN on a socket it shares — a STUN gatherer and this client pointed at
/// one server address — routes a response by transaction id, because nothing else identifies its
/// owner. See webrtc-rs/webrtc#890.
#[test]
fn test_has_transaction_reports_outstanding_requests() -> Result<()> {
    let (_conn, mut client) = create_listening_test_client(0)?;
    let server = "127.0.0.1:3478".parse::<std::net::SocketAddr>().unwrap();

    let unknown = TransactionId::new();
    assert!(
        !client.has_transaction(&unknown),
        "a fresh client is waiting on nothing"
    );

    let tid = client.send_binding_request_to(Instant::now(), server)?;
    assert!(
        client.has_transaction(&tid),
        "the transaction just started is outstanding"
    );
    assert!(
        !client.has_transaction(&unknown),
        "an id this client never sent is not its own"
    );

    Ok(())
}

/// The client sends a Binding request to its configured STUN server and reads its
/// server-reflexive address out of the response. The server is a loopback one in this process:
/// the test needs no network beyond this machine, and every read is bounded.
#[test]
fn test_client_with_stun_send_binding_request() -> Result<()> {
    let server = LoopbackStunServer::bind()?;
    let (conn, mut client) = create_test_client_with_stun_server(server.addr()?)?;
    let local_addr = conn.local_addr()?;

    let tid = client.send_binding_request(Instant::now())?;

    while let Some(transmit) = client.poll_write() {
        assert_eq!(transmit.transport.peer_addr, server.addr()?);
        conn.send_to(&transmit.message, transmit.transport.peer_addr)?;
    }
    let seen_from = server.answer_one()?;
    assert_eq!(
        seen_from, local_addr,
        "the request leaves from the client's socket"
    );

    let mut buffer = vec![0u8; 2048];
    let (n, peer_addr) = recv_within(&conn, &mut buffer, "Binding response at the client");
    client.handle_read(TransportMessage {
        now: Instant::now(),
        transport: TransportContext {
            local_addr,
            peer_addr,
            transport_protocol: TransportProtocol::UDP,
            ecn: None,
        },
        message: BytesMut::from(&buffer[..n]),
    })?;

    match client.poll_event() {
        Some(Event::BindingResponse(id, refl_addr)) => {
            assert_eq!(tid, id);
            assert_eq!(
                refl_addr, local_addr,
                "the reflexive address is the one the server saw"
            );
        }
        other => panic!("expected the Binding response, got {other:?}"),
    }

    assert_eq!(0, client.tr_map.size(), "should be no transaction left");

    client.close()
}

#[test]
fn test_client_with_stun_send_binding_request_to_parallel() -> Result<()> {
    let server = LoopbackStunServer::bind()?;
    let (conn, mut client) = create_listening_test_client(0)?;
    let local_addr = conn.local_addr()?;

    let to = server.addr()?;

    let tid1 = client.send_binding_request_to(Instant::now(), to)?;
    let tid2 = client.send_binding_request_to(Instant::now(), to)?;
    while let Some(transmit) = client.poll_write() {
        conn.send_to(&transmit.message, transmit.transport.peer_addr)?;
    }
    let mut seen_from = HashSet::new();
    for _ in 0..2 {
        seen_from.insert(server.answer_one()?);
    }

    let mut buffer = vec![0u8; 2048];
    for _ in 0..2 {
        let (n, peer_addr) = recv_within(&conn, &mut buffer, "Binding response at the client");
        client.handle_read(TransportMessage {
            now: Instant::now(),
            transport: TransportContext {
                local_addr,
                peer_addr,
                transport_protocol: TransportProtocol::UDP,
                ecn: None,
            },
            message: BytesMut::from(&buffer[..n]),
        })?;
    }

    let mut tids = HashSet::new();
    while let Some(event) = client.poll_event() {
        if let Event::BindingResponse(tid, refl_addr) = event {
            tids.insert(tid);
            assert!(
                seen_from.contains(&refl_addr),
                "{refl_addr} is an address the server saw ({seen_from:?})"
            );
        }
    }

    assert_eq!(2, tids.len());
    assert!(tids.contains(&tid1));
    assert!(tids.contains(&tid2));

    client.close()
}

#[test]
fn test_client_with_stun_send_binding_request_to_timeout() -> Result<()> {
    //env_logger::init();

    let (conn, mut client) = create_listening_test_client(10)?;

    let to = lookup_host(true, "127.0.0.1:9")?;

    let tid = client.send_binding_request_to(Instant::now(), to)?;
    while let Some(transmit) = client.poll_write() {
        conn.send_to(&transmit.message, transmit.transport.peer_addr)?;
    }

    while let Some(to) = client.poll_timeout() {
        client.handle_timeout(to)?;
    }

    if let Some(event) = client.poll_event() {
        match event {
            Event::TransactionTimeout(id) => {
                assert_eq!(tid, id);
            }
            _ => panic!(),
        }
    } else {
        panic!();
    }

    client.close()
}

#[test]
fn test_turn_server_addr_returns_some_when_configured() -> Result<()> {
    let (_conn, mut client) = create_test_client_with_turn_server()?;
    let addr = client.turn_server_addr();
    assert!(
        addr.is_some(),
        "turn_server_addr should return Some when configured"
    );
    assert_eq!(addr.unwrap().ip(), std::net::IpAddr::from([127, 0, 0, 1]));
    client.close()
}

#[test]
fn test_turn_server_addr_returns_none_when_not_configured() -> Result<()> {
    let (_conn, mut client) = create_listening_test_client(0)?;
    let addr = client.turn_server_addr();
    assert!(
        addr.is_none(),
        "turn_server_addr should return None when not configured"
    );
    client.close()
}

#[test]
fn test_turn_server_addr_or_err_returns_ok_when_configured() -> Result<()> {
    let (_conn, mut client) = create_test_client_with_turn_server()?;
    let result = client.turn_server_addr_or_err();
    assert!(
        result.is_ok(),
        "turn_server_addr_or_err should return Ok when configured"
    );
    client.close()
}

#[test]
fn test_turn_server_addr_or_err_returns_err_when_not_configured() -> Result<()> {
    let (_conn, mut client) = create_listening_test_client(0)?;
    let result = client.turn_server_addr_or_err();
    assert!(
        result.is_err(),
        "turn_server_addr_or_err should return Err when not configured"
    );
    assert_eq!(result.unwrap_err(), Error::ErrNilTurnSocket);
    client.close()
}

#[test]
fn test_local_addr_returns_bound_address() -> Result<()> {
    let (conn, mut client) = create_test_client_with_turn_server()?;
    let expected = conn.local_addr()?;
    assert_eq!(
        client.local_addr(),
        expected,
        "local_addr should match the configured address"
    );
    client.close()
}
/// The allocation-refresh timer is seeded from the instant passed to `RelayState::new` and
/// compared against the instant passed to `handle_timeout`, so a refresh can be observed by
/// arithmetic on a base instant with no wall-clock time passing and no sleeping.
#[test]
fn test_relay_refresh_timers_run_on_injected_time() -> Result<()> {
    let base = Instant::now();
    let t = |secs| base + Duration::from_secs(secs);

    let udp_socket = UdpSocket::bind("0.0.0.0:0")?;
    let mut client = Client::new(
        ClientConfig {
            stun_serv_addr: String::new(),
            turn_serv_addr: "127.0.0.1:3478".to_owned(),
            local_addr: udp_socket.local_addr()?,
            transport_protocol: TransportProtocol::UDP,
            username: "user".to_owned(),
            password: "pass".to_owned(),
            realm: "realm".to_owned(),
            software: "TEST SOFTWARE".to_owned(),
            rto_in_ms: 0,
            allocation_refresh_interval_cap: None,
            ..Default::default()
        },
        test_crypto_provider(),
    )?;

    // Stand in for a granted allocation, seeded at t(0) with a 10-minute lifetime.
    let lifetime = Duration::from_secs(600);
    let relayed_addr: RelayedAddr = "127.0.0.1:50000".parse().unwrap();
    client.relays.insert(
        relayed_addr,
        RelayState::new(
            t(0),
            relayed_addr,
            credential::Credential::established(),
            lifetime,
            None,
        ),
    );

    // The allocation is refreshed at half its lifetime; permissions sooner, at 120s.
    assert_eq!(client.relay(relayed_addr)?.poll_timeout(), Some(t(120)));

    // One second before the allocation deadline nothing is sent for it. (The permission
    // refresh at t(120) has already fired by then, so drain whatever it queued first.)
    client.relay(relayed_addr)?.handle_timeout(t(120));
    while client.poll_write().is_some() {}
    client.relay(relayed_addr)?.handle_timeout(t(299));
    assert!(
        client.poll_write().is_none(),
        "no refresh is due one second before the deadline"
    );

    // At the deadline the Refresh request goes out, stamped with the caller's instant.
    client.relay(relayed_addr)?.handle_timeout(t(300));
    let transmit = client
        .poll_write()
        .expect("the allocation must be refreshed at half its lifetime");
    assert_eq!(
        transmit.now,
        t(300),
        "the request carries the instant the caller supplied, not an ambient reading"
    );

    let mut msg = Message::new();
    msg.raw = transmit.message.to_vec();
    msg.decode()?;
    assert_eq!(msg.typ.method, METHOD_REFRESH);

    // The late permission refresh at t(299) is rescheduled from the time it was handled, so its
    // next deadline is t(419). The allocation remains due at t(600).
    assert_eq!(client.relay(relayed_addr)?.poll_timeout(), Some(t(419)));

    client.relay(relayed_addr)?.handle_timeout(t(600));
    let transmit = client
        .poll_write()
        .expect("the allocation must be refreshed again a half-lifetime later");
    assert_eq!(transmit.now, t(600));

    client.close()
}

/// Applications may refresh an otherwise idle allocation more frequently than half its server
/// lifetime so the client-to-server NAT mapping does not sit idle for several minutes.
#[test]
fn test_allocation_refresh_interval_cap_is_applied() -> Result<()> {
    let base = Instant::now();
    let t = |secs| base + Duration::from_secs(secs);

    let udp_socket = UdpSocket::bind("0.0.0.0:0")?;
    let mut client = Client::new(
        ClientConfig {
            stun_serv_addr: String::new(),
            turn_serv_addr: "127.0.0.1:3478".to_owned(),
            local_addr: udp_socket.local_addr()?,
            transport_protocol: TransportProtocol::UDP,
            username: "user".to_owned(),
            password: "pass".to_owned(),
            realm: "realm".to_owned(),
            software: "TEST SOFTWARE".to_owned(),
            rto_in_ms: 0,
            allocation_refresh_interval_cap: Some(Duration::from_secs(30)),
            ..Default::default()
        },
        test_crypto_provider(),
    )?;

    let relayed_addr: RelayedAddr = "127.0.0.1:50000".parse().unwrap();
    let mut response = Message::new();
    response.build(&[
        Box::new(TransactionId::new()),
        Box::new(MessageType::new(METHOD_ALLOCATE, CLASS_SUCCESS_RESPONSE)),
        Box::new(RelayedAddress {
            ip: relayed_addr.ip(),
            port: relayed_addr.port(),
        }),
        Box::new(crate::proto::lifetime::Lifetime(Duration::from_secs(600))),
    ])?;
    client.handle_allocate_response(
        base,
        Response::unchecked(&response),
        allocation::AllocateState::authenticated(),
    )?;

    for expected_secs in [30, 60, 90, 120, 150, 180] {
        assert_eq!(
            client.relay(relayed_addr)?.poll_timeout(),
            Some(t(expected_secs))
        );
        client.relay(relayed_addr)?.handle_timeout(t(expected_secs));

        let transmit = client
            .poll_write()
            .expect("the configured cadence must emit an allocation Refresh");
        let mut message = Message::new();
        message.raw = transmit.message.to_vec();
        message.decode()?;
        assert_eq!(message.typ.method, METHOD_REFRESH);
    }

    assert_eq!(client.relay(relayed_addr)?.poll_timeout(), Some(t(210)));

    client.close()
}

/// Handling an overdue relay timer once must put every refreshed deadline back in the future.
/// A runtime may be suspended for longer than several refresh intervals on a mobile platform;
/// replaying each missed interval makes a Sans-I/O driver spin through historical deadlines.
#[test]
fn test_overdue_relay_refreshes_are_rescheduled_from_now() -> Result<()> {
    let base = Instant::now();
    let t = |secs| base + Duration::from_secs(secs);

    let udp_socket = UdpSocket::bind("0.0.0.0:0")?;
    let mut client = Client::new(
        ClientConfig {
            stun_serv_addr: String::new(),
            turn_serv_addr: "127.0.0.1:3478".to_owned(),
            local_addr: udp_socket.local_addr()?,
            transport_protocol: TransportProtocol::UDP,
            username: "user".to_owned(),
            password: "pass".to_owned(),
            realm: "realm".to_owned(),
            software: "TEST SOFTWARE".to_owned(),
            rto_in_ms: 0,
            allocation_refresh_interval_cap: None,
            ..Default::default()
        },
        test_crypto_provider(),
    )?;

    let relayed_addr: RelayedAddr = "127.0.0.1:50000".parse().unwrap();
    client.relays.insert(
        relayed_addr,
        RelayState::new(
            t(0),
            relayed_addr,
            credential::Credential::established(),
            Duration::from_secs(600),
            None,
        ),
    );

    let resumed_at = t(1000);
    client.relay(relayed_addr)?.handle_timeout(resumed_at);

    assert_eq!(
        client.relay(relayed_addr)?.poll_timeout(),
        Some(t(1120)),
        "one timeout pass must move the permission and allocation deadlines past now"
    );

    client.close()
}

/// A relay whose lifetime has gone to zero must not hand the caller a deadline that never
/// advances.
///
/// This is the root cause behind [webrtc#862](https://github.com/webrtc-rs/webrtc/issues/862).
/// `Relay::handle_timeout` advances the allocation timer by adding to the timer's **own**
/// previous value rather than to `now`:
///
/// ```ignore
/// relay.refresh_alloc_timer = relay.refresh_alloc_timer.add(relay.lifetime / 2);
/// ```
///
/// so the step size is `lifetime / 2`. `lifetime` is assigned straight from the server's
/// LIFETIME attribute on every refresh response, with no floor — and `Relay::close` refreshes
/// with `LIFETIME=0`, which is how RFC 5766 deallocates. Once the server echoes that back the
/// step becomes zero, the timer is frozen, and because nothing ever removes the entry from
/// `client.relays` the relay keeps reporting it forever.
///
/// The peer-connection driver treats an expired deadline as "handle it and loop again", so a
/// frozen expired deadline is an unbounded hot loop — starving the very `Close` that triggered
/// it. That matches the report: cleanup never completes and the process will not exit.
#[test]
fn test_zero_lifetime_relay_does_not_freeze_its_deadline() -> Result<()> {
    let base = Instant::now();
    let t = |secs| base + Duration::from_secs(secs);

    let udp_socket = UdpSocket::bind("0.0.0.0:0")?;
    let mut client = Client::new(
        ClientConfig {
            stun_serv_addr: String::new(),
            turn_serv_addr: "127.0.0.1:3478".to_owned(),
            local_addr: udp_socket.local_addr()?,
            transport_protocol: TransportProtocol::UDP,
            username: "user".to_owned(),
            password: "pass".to_owned(),
            realm: "realm".to_owned(),
            software: "TEST SOFTWARE".to_owned(),
            rto_in_ms: 0,
            allocation_refresh_interval_cap: None,
            ..Default::default()
        },
        test_crypto_provider(),
    )?;

    let relayed_addr: RelayedAddr = "127.0.0.1:50000".parse().unwrap();
    client.relays.insert(
        relayed_addr,
        RelayState::new(
            t(0),
            relayed_addr,
            credential::Credential::established(),
            Duration::from_secs(600),
            None,
        ),
    );

    // What the server's response to `close()`'s LIFETIME=0 refresh does.
    client.relays.get_mut(&relayed_addr).unwrap().lifetime = Duration::from_secs(0);

    // Drive past both timers, exactly as the driver does: read the deadline, handle it,
    // read again. The deadline must move, or the caller is told to act on the same instant
    // forever.
    let mut previous = client.relay(relayed_addr)?.poll_timeout();
    for iteration in 0..10 {
        let now = t(1000 + iteration);
        client.relay(relayed_addr)?.handle_timeout(now);
        let next = client.relay(relayed_addr)?.poll_timeout();

        assert!(
            next != previous || next.is_none(),
            "iteration {iteration}: deadline did not advance ({previous:?} -> {next:?}) while \
             `now` is {:?} past it. The driver reads this as a zero delay, calls handle_timeout \
             and loops — forever.",
            now.saturating_duration_since(previous.unwrap_or(now)),
        );
        previous = next;
    }

    Ok(())
}

#[test]
fn test_refresh_response_reschedules_shorter_lifetime_from_response_time() -> Result<()> {
    let base = Instant::now();
    let t = |secs| base + Duration::from_secs(secs);
    let udp_socket = UdpSocket::bind("0.0.0.0:0")?;
    let mut client = Client::new(
        ClientConfig {
            stun_serv_addr: String::new(),
            turn_serv_addr: "127.0.0.1:3478".to_owned(),
            local_addr: udp_socket.local_addr()?,
            transport_protocol: TransportProtocol::UDP,
            username: "user".to_owned(),
            password: "pass".to_owned(),
            realm: "realm".to_owned(),
            software: "TEST SOFTWARE".to_owned(),
            rto_in_ms: 0,
            allocation_refresh_interval_cap: None,
            ..Default::default()
        },
        test_crypto_provider(),
    )?;
    let relayed_addr: RelayedAddr = "127.0.0.1:50000".parse().unwrap();
    client.relays.insert(
        relayed_addr,
        RelayState::new(
            t(0),
            relayed_addr,
            credential::Credential::established(),
            Duration::from_secs(600),
            None,
        ),
    );
    assert_eq!(client.relay(relayed_addr)?.poll_timeout(), Some(t(120)));

    let mut response = Message::new();
    response.build(&[
        Box::new(TransactionId::new()),
        Box::new(MessageType::new(METHOD_REFRESH, CLASS_SUCCESS_RESPONSE)),
        Box::new(crate::proto::lifetime::Lifetime(Duration::from_secs(60))),
    ])?;
    client
        .relay(relayed_addr)?
        .handle_refresh_allocation_response(t(30), response)?;

    assert_eq!(
        client.relay(relayed_addr)?.poll_timeout(),
        Some(t(60)),
        "a shorter server lifetime must move the allocation refresh deadline earlier"
    );
    Ok(())
}

#[test]
fn test_refresh_response_reschedule_applies_interval_cap() -> Result<()> {
    let base = Instant::now();
    let t = |secs| base + Duration::from_secs(secs);
    let udp_socket = UdpSocket::bind("0.0.0.0:0")?;
    let mut client = Client::new(
        ClientConfig {
            stun_serv_addr: String::new(),
            turn_serv_addr: "127.0.0.1:3478".to_owned(),
            local_addr: udp_socket.local_addr()?,
            transport_protocol: TransportProtocol::UDP,
            username: "user".to_owned(),
            password: "pass".to_owned(),
            realm: "realm".to_owned(),
            software: "TEST SOFTWARE".to_owned(),
            rto_in_ms: 0,
            allocation_refresh_interval_cap: Some(Duration::from_secs(20)),
            ..Default::default()
        },
        test_crypto_provider(),
    )?;
    let relayed_addr: RelayedAddr = "127.0.0.1:50000".parse().unwrap();
    client.relays.insert(
        relayed_addr,
        RelayState::new(
            t(0),
            relayed_addr,
            credential::Credential::established(),
            Duration::from_secs(600),
            Some(Duration::from_secs(20)),
        ),
    );

    let mut response = Message::new();
    response.build(&[
        Box::new(TransactionId::new()),
        Box::new(MessageType::new(METHOD_REFRESH, CLASS_SUCCESS_RESPONSE)),
        Box::new(crate::proto::lifetime::Lifetime(Duration::from_secs(60))),
    ])?;
    client
        .relay(relayed_addr)?
        .handle_refresh_allocation_response(t(30), response)?;

    assert_eq!(client.relay(relayed_addr)?.poll_timeout(), Some(t(50)));
    Ok(())
}

/// A server confirming deallocation must leave no relay behind.
///
/// `close()` refreshes the allocation with `LIFETIME=0`; the server echoes that back to confirm
/// the allocation is gone. Before the fix for
/// [webrtc#862](https://github.com/webrtc-rs/webrtc/issues/862) the response handler stored the
/// zero and nothing else — the entry stayed in `client.relays` forever, still reporting refresh
/// deadlines for an allocation that no longer existed, and still trying to refresh it.
///
/// Flooring the refresh step stops the *hot loop*; only removing the relay stops the dead
/// allocation. Both are needed, and this covers the second.
#[test]
fn test_zero_lifetime_response_drops_the_relay() -> Result<()> {
    let base = Instant::now();
    let t = |secs| base + Duration::from_secs(secs);

    let udp_socket = UdpSocket::bind("0.0.0.0:0")?;
    let mut client = Client::new(
        ClientConfig {
            stun_serv_addr: String::new(),
            turn_serv_addr: "127.0.0.1:3478".to_owned(),
            local_addr: udp_socket.local_addr()?,
            transport_protocol: TransportProtocol::UDP,
            username: "user".to_owned(),
            password: "pass".to_owned(),
            realm: "realm".to_owned(),
            software: "TEST SOFTWARE".to_owned(),
            rto_in_ms: 0,
            allocation_refresh_interval_cap: None,
            ..Default::default()
        },
        test_crypto_provider(),
    )?;

    let relayed_addr: RelayedAddr = "127.0.0.1:50000".parse().unwrap();
    client.relays.insert(
        relayed_addr,
        RelayState::new(
            t(0),
            relayed_addr,
            credential::Credential::established(),
            Duration::from_secs(600),
            None,
        ),
    );
    assert!(client.relay(relayed_addr)?.poll_timeout().is_some());

    // What the TURN server sends back when it honours `close()`'s LIFETIME=0 refresh.
    let mut res = Message::new();
    res.build(&[
        Box::new(TransactionId::new()),
        Box::new(MessageType::new(METHOD_REFRESH, CLASS_SUCCESS_RESPONSE)),
        Box::new(crate::proto::lifetime::Lifetime(Duration::from_secs(0))),
    ])?;

    client
        .relay(relayed_addr)?
        .handle_refresh_allocation_response(t(1), res)?;

    assert!(
        !client.relays.contains_key(&relayed_addr),
        "a deallocated allocation must not stay in the relay map — it would keep reporting \
         refresh deadlines and keep trying to refresh something that no longer exists"
    );

    Ok(())
}

/// An Allocate success response carrying `LIFETIME=0` is rejected, not accepted as a
/// degenerate allocation.
///
/// RFC 5766 §6.2 has the server take `min(client proposed, server maximum)` and fall back to
/// the *default* lifetime (600 s) whenever that does not exceed it, so a successful Allocate
/// never returns a lifetime below the default — zero is a protocol violation. Zero is
/// meaningful only on the Refresh path (§7), where it means the allocation was deleted.
///
/// Accepting it would insert a `RelayState` whose `refresh_alloc_timer` is `now.add(0)` —
/// already expired at construction — for an allocation that does not exist. That relay then
/// reports an expired refresh deadline forever, which is the hot loop in
/// [webrtc#862](https://github.com/webrtc-rs/webrtc/issues/862), reached here without any
/// close being involved.
#[test]
fn test_zero_lifetime_allocate_response_is_an_error() -> Result<()> {
    let base = Instant::now();
    let udp_socket = UdpSocket::bind("0.0.0.0:0")?;
    let mut client = Client::new(
        ClientConfig {
            stun_serv_addr: String::new(),
            turn_serv_addr: "127.0.0.1:3478".to_owned(),
            local_addr: udp_socket.local_addr()?,
            transport_protocol: TransportProtocol::UDP,
            username: "user".to_owned(),
            password: "pass".to_owned(),
            realm: "realm".to_owned(),
            software: "TEST SOFTWARE".to_owned(),
            rto_in_ms: 0,
            allocation_refresh_interval_cap: None,
            ..Default::default()
        },
        test_crypto_provider(),
    )?;

    let mut res = Message::new();
    res.build(&[
        Box::new(TransactionId::new()),
        Box::new(MessageType::new(METHOD_ALLOCATE, CLASS_SUCCESS_RESPONSE)),
        Box::new(RelayedAddress {
            ip: "127.0.0.1".parse().unwrap(),
            port: 50000,
        }),
        Box::new(crate::proto::lifetime::Lifetime(Duration::from_secs(0))),
    ])?;

    client.handle_allocate_response(
        base,
        Response::unchecked(&res),
        allocation::AllocateState::authenticated(),
    )?;

    assert!(
        client.relays.is_empty(),
        "a zero-lifetime Allocate response must not create a relay — the allocation does not \
         exist, and the relay would report an already-expired refresh deadline forever"
    );

    match client.poll_event() {
        Some(Event::AllocateError(_, _)) => Ok(()),
        other => {
            panic!("expected AllocateError for a zero-lifetime Allocate response, got {other:?}")
        }
    }
}

/// Over a TCP connection to the server the relay is still UDP: `REQUESTED-TRANSPORT` names what
/// the allocation relays, not how the client reaches the server (RFC 8656 §7.1). Deriving it from
/// the control transport asks a TCP client's server for an RFC 6062 TCP allocation instead.
#[test]
fn test_allocate_over_tcp_requests_a_udp_relay() -> Result<()> {
    let mut client = Client::new(
        ClientConfig {
            turn_serv_addr: "127.0.0.1:3478".to_owned(),
            local_addr: "127.0.0.1:50000".parse().unwrap(),
            transport_protocol: TransportProtocol::TCP,
            ..Default::default()
        },
        test_crypto_provider(),
    )?;
    client.allocate(Instant::now())?;

    let transmit = client.poll_write().expect("an Allocate request");
    assert_eq!(
        transmit.transport.transport_protocol,
        TransportProtocol::TCP,
        "the request itself still travels over TCP"
    );
    let mut msg = Message::new();
    msg.raw = transmit.message.to_vec();
    msg.decode()?;
    let mut requested = RequestedTransport::default();
    requested.get_from(&msg)?;
    assert_eq!(requested.protocol, PROTO_UDP, "the relay is UDP");
    Ok(())
}

/// Over a reliable transport a request is sent once and answered or timed out as a whole: TCP
/// already retransmits, and repeating the request on top of it only sends the server duplicates
/// (RFC 8489 §6.2.2). The wait is Ti, 39.5 seconds, not the UDP schedule's ~8.
#[test]
fn test_a_request_over_tcp_is_sent_once_and_times_out_at_ti() -> Result<()> {
    let start = Instant::now();
    let mut client = Client::new(
        ClientConfig {
            turn_serv_addr: "127.0.0.1:3478".to_owned(),
            local_addr: "127.0.0.1:50000".parse().unwrap(),
            transport_protocol: TransportProtocol::TCP,
            ..Default::default()
        },
        test_crypto_provider(),
    )?;
    let tid = client.allocate(start)?;
    assert!(client.poll_write().is_some(), "the request goes out once");

    // Walk every deadline the client asks for, up to just short of Ti.
    let ti = Duration::from_millis(39_500);
    let mut sends = 0;
    while let Some(deadline) = client.poll_timeout() {
        if deadline >= start + ti {
            break;
        }
        client.handle_timeout(deadline)?;
        while client.poll_write().is_some() {
            sends += 1;
        }
    }
    assert_eq!(sends, 0, "nothing is retransmitted over TCP");
    assert!(
        client.poll_event().is_none(),
        "no timeout before Ti has passed"
    );

    client.handle_timeout(start + ti)?;
    assert!(client.poll_write().is_none(), "not even at the deadline");
    assert!(
        matches!(client.poll_event(), Some(Event::TransactionTimeout(id)) if id == tid),
        "at Ti the request has timed out, under the id allocate() handed out"
    );
    Ok(())
}

/// UDP keeps its schedule: the first retransmission is due one RTO after the request.
#[test]
fn test_a_request_over_udp_is_still_retransmitted() -> Result<()> {
    let start = Instant::now();
    let mut client = Client::new(
        ClientConfig {
            turn_serv_addr: "127.0.0.1:3478".to_owned(),
            local_addr: "127.0.0.1:50000".parse().unwrap(),
            transport_protocol: TransportProtocol::UDP,
            ..Default::default()
        },
        test_crypto_provider(),
    )?;
    client.allocate(start)?;
    assert!(client.poll_write().is_some());
    let first = client.poll_timeout().expect("a retransmit deadline");
    assert!(
        first < start + Duration::from_secs(1),
        "{:?}",
        first - start
    );
    client.handle_timeout(first)?;
    assert!(client.poll_write().is_some(), "UDP retransmits");
    Ok(())
}

/// A timed-out Allocate is reported under the id [`Client::allocate`] returned — the one the
/// caller has to match it with. An anonymous Allocate goes out under the id before it, so a
/// caller that only knows what `allocate()` told it would never recognise the timeout and
/// could wait on that allocation for ever; the responses already follow this convention.
#[test]
fn test_an_allocate_that_is_never_answered_times_out_under_the_id_allocate_returned() -> Result<()>
{
    for transport_protocol in [TransportProtocol::UDP, TransportProtocol::TCP] {
        let start = Instant::now();
        let mut client = Client::new(
            ClientConfig {
                turn_serv_addr: "127.0.0.1:3478".to_owned(),
                local_addr: "127.0.0.1:50000".parse().unwrap(),
                transport_protocol,
                ..Default::default()
            },
            test_crypto_provider(),
        )?;
        let tid = client.allocate(start)?;
        while client.poll_write().is_some() {}

        // Every deadline the client asks for, until it has nothing left to wait on.
        let mut timeout = None;
        while let Some(deadline) = client.poll_timeout() {
            client.handle_timeout(deadline)?;
            while client.poll_write().is_some() {}
            while let Some(event) = client.poll_event() {
                if let Event::TransactionTimeout(id) = event {
                    timeout = Some((id, deadline));
                }
            }
        }
        let (id, at) = timeout.expect("a server that never answers times the request out");
        assert_eq!(
            id, tid,
            "{transport_protocol:?}: the timeout must name the allocation its caller knows"
        );
        assert!(
            at <= start + Duration::from_millis(39_500),
            "{transport_protocol:?}: timed out at {:?}",
            at - start
        );
    }
    Ok(())
}

/// An error reply to the anonymous Allocate that carries no NONCE, or no REALM — a 403, a 486,
/// or a server that simply left the attribute out — is reported as an
/// [`Event::AllocateError`], and that too has to name the allocation its caller knows: the id
/// [`Client::allocate`] returned, as a response and now a timeout do. It named the anonymous
/// request instead, so a caller matching on what `allocate()` told it never saw the error,
/// and waited on the allocation for ever.
#[test]
fn test_an_error_reply_without_a_nonce_is_reported_under_the_id_allocate_returned() -> Result<()> {
    use stun::error_code::{CODE_FORBIDDEN, CODE_UNAUTHORIZED, ErrorCode};

    // Neither attribute, and a 401 that remembered the nonce but not the realm. (Not a 400:
    // RFC 8489 section 9.2.5 has an unsigned 400 "discarded, as if it were never received",
    // so it reports nothing; `test_an_unsigned_400_to_the_first_allocate_is_never_received`.)
    let replies: [(ErrorCode, Option<Nonce>); 2] = [
        (CODE_FORBIDDEN, None),
        (
            CODE_UNAUTHORIZED,
            Some(Nonce::new(ATTR_NONCE, "nonce".to_owned())),
        ),
    ];
    for (code, nonce) in replies {
        let start = Instant::now();
        let local_addr: SocketAddr = "127.0.0.1:50000".parse().unwrap();
        let server_addr: SocketAddr = "127.0.0.1:3478".parse().unwrap();
        let mut client = Client::new(
            ClientConfig {
                turn_serv_addr: server_addr.to_string(),
                local_addr,
                transport_protocol: TransportProtocol::UDP,
                ..Default::default()
            },
            test_crypto_provider(),
        )?;
        let tid = client.allocate(start)?;
        let request = client
            .poll_write()
            .expect("the anonymous Allocate goes out");
        let mut sent = Message::new();
        sent.raw = request.message.to_vec();
        sent.decode()?;

        let mut attributes: Vec<Box<dyn Setter>> = vec![
            Box::new(sent.transaction_id),
            Box::new(MessageType::new(METHOD_ALLOCATE, CLASS_ERROR_RESPONSE)),
            Box::new(ErrorCodeAttribute {
                code,
                reason: b"no".to_vec(),
            }),
        ];
        if let Some(nonce) = nonce {
            attributes.push(Box::new(nonce));
        }
        attributes.push(Box::new(FINGERPRINT));
        let mut reply = Message::new();
        reply.build(&attributes)?;

        client.handle_read(TransportMessage {
            now: start,
            transport: TransportContext {
                local_addr,
                peer_addr: server_addr,
                transport_protocol: TransportProtocol::UDP,
                ecn: None,
            },
            message: BytesMut::from(&reply.raw[..]),
        })?;

        let mut error = None;
        while let Some(event) = client.poll_event() {
            if let Event::AllocateError(id, err) = event {
                error = Some((id, err));
            }
        }
        let (id, _) = error.expect("a reply the client cannot authenticate with is an error");
        assert_eq!(
            id, tid,
            "{}: the error must name the allocation its caller knows",
            code.0
        );
    }
    Ok(())
}

/// A Data indication (or ChannelData) that does not come from the TURN server is not relayed
/// peer data: anyone could send one to the client's socket.
#[test]
fn test_data_from_a_non_server_address_is_ignored() -> Result<()> {
    let (conn, mut client) = create_test_client_with_turn_server()?;
    let local_addr = conn.local_addr()?;
    let server_addr = client.turn_server_addr().expect("configured");
    let stray: SocketAddr = "127.0.0.1:9".parse().unwrap();
    assert_ne!(stray, server_addr);
    test_server::hold_permission(&mut client, Instant::now(), "10.0.0.1".parse().unwrap());

    let indication = |from: SocketAddr| -> Result<TransportMessage<BytesMut>> {
        let mut msg = Message::new();
        msg.build(&[
            Box::new(MessageType::new(METHOD_DATA, CLASS_INDICATION)),
            Box::new(TransactionId::new()),
            Box::new(PeerAddress {
                ip: "10.0.0.1".parse().unwrap(),
                port: 5000,
            }),
            Box::new(Data(b"hello".to_vec())),
        ])?;
        Ok(TransportMessage {
            now: Instant::now(),
            transport: TransportContext {
                local_addr,
                peer_addr: from,
                transport_protocol: TransportProtocol::UDP,
                ecn: None,
            },
            message: BytesMut::from(&msg.raw[..]),
        })
    };

    client.handle_read(indication(stray)?)?;
    assert!(
        client.poll_event().is_none(),
        "a Data indication from a stray address was delivered as relayed data"
    );

    client.handle_read(indication(server_addr)?)?;
    assert!(
        matches!(
            client.poll_event(),
            Some(Event::DataIndicationOrChannelData(..))
        ),
        "a Data indication from the TURN server is still delivered"
    );
    client.close()
}

/// A server-side view of the exchange in `test_responses_without_valid_integrity_are_dropped`.
struct FakeTurnServer {
    local_addr: SocketAddr,
    server_addr: SocketAddr,
    key: Vec<u8>,
}

impl FakeTurnServer {
    /// The next request the client sent, decoded.
    fn next_request(&self, client: &mut Client) -> Message {
        let transmit = client.poll_write().expect("the client sent a request");
        let mut msg = Message::new();
        msg.raw = transmit.message.to_vec();
        msg.decode().expect("the client's request decodes");
        msg
    }

    /// Answers `request` with `class` and `attrs`, signed with `key` when given.
    fn answer(
        &self,
        client: &mut Client,
        request: &Message,
        class: MessageClass,
        attrs: Vec<Box<dyn Setter>>,
        key: Option<&[u8]>,
    ) -> Result<()> {
        let provider = test_crypto_provider();
        let mut setters: Vec<Box<dyn Setter + '_>> = vec![
            Box::new(request.transaction_id),
            Box::new(MessageType::new(request.typ.method, class)),
        ];
        setters.extend(attrs);
        if let Some(key) = key {
            setters.push(Box::new(MessageIntegrity::new_raw_integrity_with_provider(
                key.to_vec(),
                provider.crypto(),
            )));
        }
        setters.push(Box::new(FINGERPRINT));
        let mut reply = Message::new();
        reply.build(&setters)?;
        client.handle_read(TransportMessage {
            now: Instant::now(),
            transport: TransportContext {
                local_addr: self.local_addr,
                peer_addr: self.server_addr,
                transport_protocol: TransportProtocol::UDP,
                ecn: None,
            },
            message: BytesMut::from(&reply.raw[..]),
        })
    }
}

/// Responses to authenticated TURN requests (Allocate after the 401, Refresh,
/// CreatePermission, ChannelBind) must carry a MESSAGE-INTEGRITY made with the long-term key.
/// One that is unsigned or signed with another key is dropped, leaving the transaction open;
/// only 401 and 438 error responses may come unsigned.
#[test]
fn test_responses_without_valid_integrity_are_dropped() -> Result<()> {
    let local_addr: SocketAddr = "127.0.0.1:50000".parse().unwrap();
    let server_addr: SocketAddr = "127.0.0.1:3478".parse().unwrap();
    let relayed_addr: SocketAddr = "192.0.2.15:50000".parse().unwrap();
    let peer_addr: SocketAddr = "198.51.100.7:4000".parse().unwrap();
    let mut client = Client::new(
        ClientConfig {
            turn_serv_addr: server_addr.to_string(),
            local_addr,
            transport_protocol: TransportProtocol::UDP,
            username: "user".to_owned(),
            password: "pass".to_owned(),
            ..Default::default()
        },
        test_crypto_provider(),
    )?;
    let server = FakeTurnServer {
        local_addr,
        server_addr,
        key: MessageIntegrity::long_term_integrity_key(
            "user".to_owned(),
            "realm".to_owned(),
            "pass".to_owned(),
            test_crypto_provider().crypto(),
        )?,
    };
    let wrong_key = MessageIntegrity::long_term_integrity_key(
        "user".to_owned(),
        "realm".to_owned(),
        "guess".to_owned(),
        test_crypto_provider().crypto(),
    )?;
    let forgeries: [Option<&[u8]>; 2] = [None, Some(&wrong_key)];

    // The anonymous Allocate is answered with the 401 nonce exchange, unsigned as servers do.
    let tid = client.allocate(Instant::now())?;
    let attempt = server.next_request(&mut client);
    server.answer(
        &mut client,
        &attempt,
        CLASS_ERROR_RESPONSE,
        vec![
            Box::new(ErrorCodeAttribute {
                code: stun::error_code::CODE_UNAUTHORIZED,
                reason: b"Unauthorized".to_vec(),
            }),
            Box::new(Nonce::new(ATTR_NONCE, "nonce".to_owned())),
            Box::new(Realm::new(ATTR_REALM, "realm".to_owned())),
        ],
        None,
    )?;
    let allocate = server.next_request(&mut client);
    assert_eq!(allocate.transaction_id, tid);
    assert!(allocate.contains(ATTR_MESSAGE_INTEGRITY));

    let allocate_success = || -> Vec<Box<dyn Setter>> {
        vec![
            Box::new(RelayedAddress {
                ip: relayed_addr.ip(),
                port: relayed_addr.port(),
            }),
            Box::new(crate::proto::lifetime::Lifetime(Duration::from_secs(600))),
        ]
    };
    for forged in forgeries {
        server.answer(
            &mut client,
            &allocate,
            CLASS_SUCCESS_RESPONSE,
            allocate_success(),
            forged,
        )?;
        assert!(
            client.poll_event().is_none(),
            "a forged Allocate success response was accepted"
        );
        server.answer(
            &mut client,
            &allocate,
            CLASS_ERROR_RESPONSE,
            vec![Box::new(ErrorCodeAttribute {
                code: stun::error_code::CODE_FORBIDDEN,
                reason: b"Forbidden".to_vec(),
            })],
            forged,
        )?;
        assert!(
            client.poll_event().is_none(),
            "a forged Allocate error response was accepted"
        );
        assert!(client.has_transaction(&tid), "the Allocate stays open");
    }
    server.answer(
        &mut client,
        &allocate,
        CLASS_SUCCESS_RESPONSE,
        allocate_success(),
        Some(&server.key),
    )?;
    assert!(matches!(
        client.poll_event(),
        Some(Event::AllocateResponse(id, addr)) if id == tid && addr == relayed_addr
    ));

    // CreatePermission.
    let tid = client
        .relay(relayed_addr)?
        .create_permission(Instant::now(), peer_addr)?
        .expect("a new permission is requested");
    let create_permission = server.next_request(&mut client);
    for forged in forgeries {
        server.answer(
            &mut client,
            &create_permission,
            CLASS_SUCCESS_RESPONSE,
            vec![],
            forged,
        )?;
        server.answer(
            &mut client,
            &create_permission,
            CLASS_ERROR_RESPONSE,
            vec![Box::new(ErrorCodeAttribute {
                code: stun::error_code::CODE_FORBIDDEN,
                reason: b"Forbidden".to_vec(),
            })],
            forged,
        )?;
        assert!(
            client.poll_event().is_none(),
            "a forged CreatePermission response was accepted"
        );
        assert!(client.has_transaction(&tid));
    }
    server.answer(
        &mut client,
        &create_permission,
        CLASS_SUCCESS_RESPONSE,
        vec![],
        Some(&server.key),
    )?;
    assert!(matches!(
        client.poll_event(),
        Some(Event::CreatePermissionResponse(id, addr)) if id == tid && addr == peer_addr
    ));

    // ChannelBind, started by the first send to the permitted peer (which also sends the data
    // as a Send indication meanwhile).
    client
        .relay(relayed_addr)?
        .send_to(Instant::now(), b"hi", peer_addr)?;
    let channel_bind = server.next_request(&mut client);
    assert_eq!(channel_bind.typ.method, METHOD_CHANNEL_BIND);
    while client.poll_write().is_some() {}
    let binding_state = |client: &Client| {
        client
            .relays
            .get(&relayed_addr)
            .and_then(|relay| relay.binding_mgr.find_by_addr(&peer_addr))
            .map(|b| b.state())
    };
    for forged in forgeries {
        server.answer(
            &mut client,
            &channel_bind,
            CLASS_SUCCESS_RESPONSE,
            vec![],
            forged,
        )?;
        assert_eq!(
            binding_state(&client),
            Some(binding::BindingState::Request),
            "a forged ChannelBind success response was accepted"
        );
        server.answer(
            &mut client,
            &channel_bind,
            CLASS_ERROR_RESPONSE,
            vec![Box::new(ErrorCodeAttribute {
                code: stun::error_code::CODE_FORBIDDEN,
                reason: b"Forbidden".to_vec(),
            })],
            forged,
        )?;
        assert_eq!(
            binding_state(&client),
            Some(binding::BindingState::Request),
            "a forged ChannelBind error response was accepted"
        );
    }
    server.answer(
        &mut client,
        &channel_bind,
        CLASS_SUCCESS_RESPONSE,
        vec![],
        Some(&server.key),
    )?;
    assert_eq!(binding_state(&client), Some(binding::BindingState::Ready));

    // Refresh: a forged LIFETIME=0 would make the client drop a live allocation.
    client.refresh_allocations(Instant::now())?;
    let refresh = server.next_request(&mut client);
    assert_eq!(refresh.typ.method, METHOD_REFRESH);
    for forged in forgeries {
        server.answer(
            &mut client,
            &refresh,
            CLASS_SUCCESS_RESPONSE,
            vec![Box::new(crate::proto::lifetime::Lifetime(Duration::ZERO))],
            forged,
        )?;
        assert!(
            client.relay(relayed_addr).is_ok(),
            "a forged Refresh response released the allocation"
        );
        assert!(client.has_transaction(&refresh.transaction_id));
    }

    // A 438 is answered unsigned by servers and still updates the nonce.
    server.answer(
        &mut client,
        &refresh,
        CLASS_ERROR_RESPONSE,
        vec![
            Box::new(ErrorCodeAttribute {
                code: stun::error_code::CODE_STALE_NONCE,
                reason: b"Stale Nonce".to_vec(),
            }),
            Box::new(Nonce::new(ATTR_NONCE, "fresh".to_owned())),
        ],
        None,
    )?;
    assert!(!client.has_transaction(&refresh.transaction_id));
    assert_eq!(
        client
            .relays
            .get(&relayed_addr)
            .and_then(|r| r.credential.nonce().map(str::to_owned)),
        Some("fresh".to_owned())
    );

    Ok(())
}