geiserx_ts_runtime 0.55.1

tailscale runtime
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
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
//! Direct (disco) UDP underlay manager.
//!
//! This actor owns the single [`MagicSock`] that carries WireGuard datagrams directly over
//! UDP to peers' reachable endpoints, discovering and confirming paths with the disco
//! protocol. It mirrors [`crate::multiderp::Multiderp`] but for the direct underlay: it
//! registers one [`DirectTransport`] with the dataplane and bridges packets between that
//! transport and the dataplane's underlay channels.
//!
//! # Anti-leak posture
//!
//! A peer is reported as having a direct path *only* when [`MagicSock::best_addr`] returns
//! `Some` (i.e. a disco pong confirmed the path and its trust has not expired). The route
//! layer upgrades such peers from DERP to direct and auto-downgrades them back to DERP when
//! trust lapses. There is never a silent host-network dial, so the real origin IP cannot leak
//! when direct connectivity is unavailable.

use core::{net::SocketAddr, time::Duration};
use std::{
    collections::{HashMap, HashSet},
    sync::{
        Arc, RwLock,
        atomic::{AtomicBool, Ordering},
    },
};

use kameo::{
    actor::ActorRef,
    message::{Context, Message},
};
use tokio::{sync::Mutex, task::JoinSet};
use ts_keys::{DiscoPublicKey, NodePublicKey};
use ts_magicsock::{BindingVerifier, DirectTransport, MagicSock, SelfEndpoint};
use ts_transport::{
    BatchRecvIter, PeerId, PeerLookup, UnderlayTransport, UnderlayTransportExt, UnderlayTransportId,
};

use crate::{
    Env, Error,
    dataplane::{
        DatapathActivity, DataplaneActor, NewUnderlayTransport, UnderlayFromDataplane,
        UnderlayToDataplane,
    },
    multiderp::{self, Multiderp},
    peer_tracker::{DiscoKeyMatch, PeerDb, PeerState},
};

/// A peer sent us a disco frame sealed under one of its two known disco keys, and it was **not**
/// the key we are currently sending to.
///
/// Published by the disco ingress gate ([`verify_binding`]) and consumed by the peer tracker, which
/// makes that key active (Go [`endpoint.checkAndUpdateDiscoKey`], which compare-and-swaps
/// `endpointDisco.tsmpActive` and then calls `changedActiveDiscoLocked`). Receiving under a key
/// proves the peer holds its private half and is what the peer is really using, so it beats what
/// control last said.
///
/// Only frames that have already passed the disco<->node-key binding check are reported, so this
/// cannot be used by a third party to steer a peer onto a different key. The peer tracker refuses
/// any key that is neither of the peer's two slots regardless.
///
/// [`endpoint.checkAndUpdateDiscoKey`]: https://github.com/tailscale/tailscale/blob/9ea7cba44591e0cd840c6c94d23274dd222059bf/wgengine/magicsock/endpoint.go
#[derive(Debug, Clone, Copy)]
pub struct DiscoKeyObserved {
    /// The peer the frame was attributed to.
    pub peer: PeerId,
    /// The sender disco key the frame was sealed under — the peer's currently-inactive key.
    pub key: DiscoPublicKey,
}

/// The channel the disco ingress gate reports an inactive-key sighting on.
///
/// [`verify_binding`] runs inside a synchronous verifier callback on the packet path, so it cannot
/// `await` a bus publish; it hands the sighting to [`run_disco_key_observer`], which does. Sending
/// is non-blocking and lossy-by-drop only if the forwarder has stopped, which is shutdown.
type DiscoKeyObserver = tokio::sync::mpsc::UnboundedSender<DiscoKeyObserved>;

/// Forward inactive-key sightings from the packet path onto the bus for the peer tracker.
///
/// The tracker is the sole owner of the two-slot disco state, so the switch itself — and the
/// republish that makes the direct manager invalidate the path built under the old key — happens
/// there. Duplicates are expected and harmless: several frames can arrive under the old key before
/// the switch lands, and the tracker no-ops once the key is already active.
async fn run_disco_key_observer(
    mut observed: tokio::sync::mpsc::UnboundedReceiver<DiscoKeyObserved>,
    env: Env,
    mut shutdown: tokio::sync::watch::Receiver<bool>,
) {
    while !*shutdown.borrow() {
        let msg = tokio::select! {
            _ = shutdown.changed() => break,
            msg = observed.recv() => match msg {
                Some(msg) => msg,
                // Every sender is gone: the verifier closure (and so the socket) has been dropped.
                None => break,
            },
        };

        if let Err(e) = env.publish(msg).await {
            tracing::error!(error = %e, "publishing an observed peer disco key");
        }
    }
}

/// How often to (re)ping candidate endpoints. [`MagicSock::send_pings`] only pings paths that
/// need (re)confirmation, so this interval just bounds how quickly an expired path
/// (`TRUST_DURATION`) is re-confirmed.
///
/// No-flap timing invariant (spans crates): the magicsock best-path refresh lead
/// `REFRESH_BEFORE_EXPIRY` (3.5s) must exceed this interval plus a realistic best-path RTT, so the
/// best is re-pinged and re-confirmed before `TRUST_DURATION` (6.5s) lapses and `best_addr` goes
/// `None`. Raising this interval shrinks that slack; keep it in step with the magicsock `path.rs`
/// constants (which carry the reciprocal note).
const PING_INTERVAL: Duration = Duration::from_secs(2);

/// Bounds for the **randomized** delay between periodic STUN Binding Request sweeps to the derp map's
/// STUN servers (from the one bound underlay socket, to learn our reflexive/public address even
/// before any peer pongs — complementing the pong-harvest path on the same socket without a second
/// egress). Each sweep waits a fresh uniform delay in `[MIN, MAX)`, matching Go magicsock which arms
/// its `periodicReSTUNTimer` with `tstime.RandomDurationBetween(20s, 26s)` per cycle
/// (`magicsock.go`). The jitter — and the sub-30s ceiling — are deliberate: a fixed 30s beat is a
/// traffic-analysis fingerprint, and 30s is a common UDP NAT mapping timeout on Linux, so Go keeps
/// every interval strictly under it. A real `tailscaled` shows a jittered ~23s mean here, not a
/// deterministic 30.0s tick.
const STUN_PROBE_INTERVAL_MIN: Duration = Duration::from_secs(20);
const STUN_PROBE_INTERVAL_MAX: Duration = Duration::from_secs(26);

/// A uniform random delay in `[STUN_PROBE_INTERVAL_MIN, STUN_PROBE_INTERVAL_MAX)`, the analog of Go
/// `tstime.RandomDurationBetween(min, max)` (`min + rand.N(max-min)`): both are uniform over the
/// half-open interval. Uses the non-crypto thread RNG (`rand`), like the other timing jitters in this
/// crate (e.g. the multiderp reconnect backoff) — this is timing jitter, not key material, so it
/// deliberately does not use the ring/crypto RNG.
///
/// `random_range` panics on an empty range, so the bounds must stay ordered `MIN < MAX` (they are
/// distinct compile-time constants today). If these ever become equal or runtime-configurable, guard
/// the `MIN == MAX` case first (Go's `RandomDurationBetween` returns `min` there rather than panicking).
fn stun_probe_delay() -> Duration {
    rand::random_range(STUN_PROBE_INTERVAL_MIN..STUN_PROBE_INTERVAL_MAX)
}

/// How often to re-evaluate our own candidate endpoints and (if changed) advertise them to
/// control. Reflexive addresses accrue asynchronously as disco pongs arrive, so we poll and
/// only publish when the set actually differs from what we last advertised.
const ADVERTISE_INTERVAL: Duration = Duration::from_secs(5);

/// Our magicsock candidate endpoints, published for [`crate::control_runner::ControlRunner`] to
/// forward to the control server so peers can learn where to attempt direct connections.
///
/// All addresses originate from the single bound underlay socket — there is no second egress.
#[derive(Clone)]
pub struct EndpointAdvertisement {
    pub endpoints: Arc<Vec<SelfEndpoint>>,
}

/// The IPv4 bind address for the direct underlay socket (unit tests).
///
/// IPv4-only and ephemeral-port: per the anti-leak rules this socket is the only egress path for
/// the direct underlay, and IPv6 is disabled in our default deployment. The production bind no
/// longer parses this string (it constructs the address from
/// [`Ipv4Addr::UNSPECIFIED`](core::net::Ipv4Addr) and the resolved port in [`bind_underlay_addr`]);
/// the constant is retained as the canonical `0.0.0.0:0` literal the socket tests bind directly.
#[cfg(test)]
const BIND_ADDR: &str = "0.0.0.0:0";

/// Bind a [`MagicSock`] to the given UNSPECIFIED-address family at `listen_port`, falling back to an
/// OS-chosen ephemeral port (`:0`) if `listen_port` is non-zero and already taken.
///
/// The single port-collision fallback the initial bind shares with [`rebind_socket`]'s
/// `Err(_) if prefer_port != 0 => bind(0)`: a pinned [`Config::wireguard_listen_port`] that happens
/// to be taken must not fail bring-up. `listen_port == 0` (ephemeral) needs no fallback — there is
/// nothing more permissive to retry — so its error propagates unchanged. `our_disco` is cloned per
/// attempt because [`MagicSock::bind`] consumes it (it is no longer `Copy`); `our_node_key` is a
/// `Copy` public key.
async fn bind_unspecified_with_fallback(
    ip: core::net::IpAddr,
    listen_port: u16,
    our_disco: &ts_keys::DiscoPrivateKey,
    our_node_key: NodePublicKey,
) -> Result<MagicSock, ts_magicsock::Error> {
    let pinned = SocketAddr::new(ip, listen_port);
    match MagicSock::bind(pinned, our_disco.clone(), our_node_key).await {
        Ok(sock) => Ok(sock),
        // Pinned port taken (or otherwise unbindable): fall back to an ephemeral port so a port
        // collision never takes the node down. Only when a port was actually pinned.
        Err(_) if listen_port != 0 => {
            tracing::warn!(
                %pinned,
                "underlay bind on pinned port failed; falling back to an ephemeral port",
            );
            MagicSock::bind(SocketAddr::new(ip, 0), our_disco.clone(), our_node_key).await
        }
        Err(e) => Err(e),
    }
}

/// Choose the underlay UDP socket and the address it bound to, honoring the (default-off)
/// `enable_ipv6` overlay gate and the (default-ephemeral) `listen_port` pin.
///
/// `listen_port` is [`Config::wireguard_listen_port`](ts_control::Config::wireguard_listen_port)
/// resolved to a `u16` (`0` = OS-chosen ephemeral, today's behavior; non-zero = pin that port with
/// an ephemeral fallback if it is taken — see [`bind_unspecified_with_fallback`]). It governs only
/// the bound port; the bind *family* still follows `enable_ipv6`:
///
/// - `enable_ipv6 == false` (default): bind `0.0.0.0:listen_port` (`0.0.0.0:0` = byte-for-byte the
///   historical IPv4-only ephemeral path). This upholds the sacred IPv4-only invariant of the
///   privacy-proxy deployment.
/// - `enable_ipv6 == true`: attempt a dual-stack bind on `[::]:listen_port` so a single socket
///   serves both native v6 and v4-mapped traffic. **Fail inert, never panic**: if the v6 bind fails
///   (e.g. a host with `net.ipv6.conf.all.disable_ipv6=1`), warn and fall back to the IPv4 bind so
///   the node still comes up — protective if the gate is mis-flagged on a hardened box.
///
/// A successful pinned port carries across a later [`MagicSock::rebind`], which re-prefers the
/// socket's current local port.
///
/// NOTE (dep gap reported to the architect): [`MagicSock::bind`] takes only a [`SocketAddr`] and
/// constructs the `tokio::net::UdpSocket` itself, so this site cannot set `IPV6_V6ONLY` explicitly
/// (that would require `socket2::Socket`/`libc`, neither of which is a dependency of `ts_runtime`,
/// or a change to `ts_magicsock`). The dual-stack socket therefore relies on the kernel's
/// `IPV6_V6ONLY` default, which is dual-stack on Linux (our deployment) but v6-only on macOS. To
/// force `set_only_v6(false)` portably, either `socket2` must become a dependency or `MagicSock`
/// must expose a bind that accepts a pre-configured socket.
async fn bind_underlay_addr(
    enable_ipv6: bool,
    listen_port: u16,
    our_disco: ts_keys::DiscoPrivateKey,
    our_node_key: NodePublicKey,
) -> Result<MagicSock, ts_magicsock::Error> {
    use core::net::{Ipv4Addr, Ipv6Addr};

    // IPv4-only default: the historical family, now honoring the pinned port (`0` = ephemeral, i.e.
    // byte-for-byte the original `0.0.0.0:0`).
    if !enable_ipv6 {
        return bind_unspecified_with_fallback(
            Ipv4Addr::UNSPECIFIED.into(),
            listen_port,
            &our_disco,
            our_node_key,
        )
        .await;
    }

    // Overlay IPv6 enabled: try the dual-stack bind (same port pin + ephemeral fallback) first.
    match bind_unspecified_with_fallback(
        Ipv6Addr::UNSPECIFIED.into(),
        listen_port,
        &our_disco,
        our_node_key,
    )
    .await
    {
        Ok(sock) => Ok(sock),
        Err(e) => {
            // Inert fallback: the host likely has IPv6 disabled at the kernel. Come up IPv4-only
            // (still honoring the pinned port) rather than crash — protective on a hardened proxy
            // box even if the gate is set.
            tracing::warn!(
                error = %e,
                "dual-stack underlay bind failed (host IPv6 disabled?); falling back to IPv4-only",
            );
            bind_unspecified_with_fallback(
                Ipv4Addr::UNSPECIFIED.into(),
                listen_port,
                &our_disco,
                our_node_key,
            )
            .await
        }
    }
}

/// Owns the direct (disco) UDP underlay and bridges it to the dataplane.
///
/// `sock`/`transport_id` are `Option`: if the underlay UDP socket fails to bind at startup the
/// manager stays **inert** (both `None`) rather than panicking, and the runtime continues
/// DERP-only. DERP-only is the anti-leak-safe fallback — there is simply no direct path to offer,
/// so no peer is ever upgraded off DERP and the real origin IP cannot leak.
pub struct DirectManager {
    sock: Option<Arc<MagicSock>>,
    transport_id: Option<UnderlayTransportId>,
    peer_db: Arc<RwLock<Option<Arc<PeerDb>>>>,
    /// Retained so the `RebindAndReprobe` handler can fetch the current v4 STUN servers
    /// ([`Multiderp::stun_servers_v4`]) and fire an immediate STUN sweep right after the rebind —
    /// the same source the periodic [`run_stun_prober`] uses. Held here (not just cloned into the
    /// prober task) because the on-demand sweep runs inside the actor handler.
    multiderp: ActorRef<Multiderp>,
    /// Where the next STUN sweep resumes in the derp map's v4 server list. Shared with the periodic
    /// [`run_stun_prober`] task so an on-demand sweep and the periodic one advance one rotation
    /// between them rather than both re-probing the same head. The mutex is also what serializes
    /// the two: it is held for a whole round, not just around the cursor read. See
    /// [`probe_stun_servers_once`].
    stun_cursor: Arc<Mutex<usize>>,
    /// Control's `debug-always-stun` node attribute (Go `controlknobs.Knobs.ForceBackgroundSTUN`),
    /// re-read off the self node on every netmap. Shared with the periodic [`run_stun_prober`] task,
    /// which is the only reader: it is the sole override on that sweep's idle stop condition (see
    /// [`should_do_periodic_restun`]). An `AtomicBool` rather than a bus message or an actor `ask`
    /// because the reader is a plain task and the value is one independent bit.
    force_background_stun: Arc<AtomicBool>,
    #[allow(dead_code)]
    tasks: JoinSet<()>,
}

#[kameo::messages]
impl DirectManager {
    /// The id of the single direct underlay transport registered with the dataplane.
    ///
    /// `Some` once the actor has started and the underlay socket bound; `None` if the bind failed
    /// at startup, in which case the route updater stays DERP-only (fail-closed). The `Option`
    /// also satisfies kameo's `Reply` bound (a bare newtype is not a reply).
    #[message]
    pub fn direct_transport_id(&self) -> Option<UnderlayTransportId> {
        self.transport_id
    }

    /// Of the given peers, the current trusted direct UDP endpoint (`MagicSock::best_addr`) for each
    /// that has one — Go's per-peer `CurAddr`. A peer appears in the map only if its disco key is
    /// known and `best_addr` returns `Some` right now (live query — never cached — so trust expiry
    /// downgrades immediately); an absent peer is relayed via DERP.
    #[message]
    pub fn best_addrs(&self, ids: Vec<PeerId>) -> HashMap<PeerId, SocketAddr> {
        let mut addrs = HashMap::new();

        // No bound underlay socket (bind failed => inert, DERP-only): no peer has a direct path.
        let Some(sock) = self.sock.as_ref() else {
            return addrs;
        };

        let db = poisoned_read(&self.peer_db);
        let Some(db) = db.as_ref() else {
            return addrs;
        };

        for id in ids {
            let Some((_, node)) = db.get(&id) else {
                continue;
            };
            let Some(disco) = node.disco_key else {
                continue;
            };
            if let Some(addr) = sock.best_addr(&disco) {
                addrs.insert(id, addr);
            }
        }

        addrs
    }

    /// The current trusted direct endpoint **and its last-measured RTT** for the peer with this
    /// disco key, or `None` if it has no direct path right now (relayed via DERP, or the underlay is
    /// inert). The latency is the most recent confirming pong's RTT — up to one probe interval
    /// stale, not a fresh on-demand measurement. Keyed by disco (the caller resolves the peer's
    /// disco key from its node) so no `PeerId`↔node-id ambiguity enters here. Backs `Device`'s
    /// direct-path report.
    #[message]
    pub fn direct_path_latency(&self, disco: DiscoPublicKey) -> Option<(SocketAddr, Duration)> {
        self.sock.as_ref()?.best_addr_and_latency(&disco)
    }

    /// Hand out the underlay [`MagicSock`] handle (or `None` if the bind failed / inert DERP-only
    /// mode). This is a cheap synchronous clone so the caller can run an **awaiting** operation —
    /// `MagicSock::ping_now`, which sends a disco ping and awaits the pong for up to a timeout — OFF
    /// this actor's mailbox. Doing the await here (in a `#[message]`) would block the DirectManager
    /// for the whole ping timeout, serializing every other message behind it.
    #[message]
    pub fn sock_handle(&self) -> Option<Arc<MagicSock>> {
        self.sock.clone()
    }

    /// Of the given peers, return those that currently have a trusted direct path — the key set of
    /// [`best_addrs`](Self::best_addrs). A peer is included only if its disco key is known and
    /// [`MagicSock::best_addr`] returns `Some` for it right now (live query — never cached — so trust
    /// expiry downgrades immediately).
    #[message]
    pub fn peers_with_direct_path(&self, ids: Vec<PeerId>) -> HashSet<PeerId> {
        self.best_addrs(ids).into_keys().collect()
    }

    /// Re-bind the underlay UDP socket after a network/link change (the engine half of
    /// `Device::rebind`). Delegates to [`MagicSock::rebind`], which swaps the socket and resets the
    /// stale local mapping (clears reflexive + confirmed best paths, keeps candidates) so peers
    /// re-probe over the new socket and fail closed to DERP meanwhile. No-op (`Ok`) when the underlay
    /// bind failed at startup (DERP-only inert mode — there is no socket to rebind).
    #[message]
    pub async fn rebind(&self) -> Result<(), ts_magicsock::Error> {
        match self.sock.as_ref() {
            Some(sock) => sock.rebind().await,
            None => Ok(()),
        }
    }

    /// Re-bind the underlay socket AND immediately re-probe connectivity, atomically in the actor —
    /// the auto-recovery path the [`NetmonSupervisor`](crate::netmon::NetmonSupervisor) fires on a
    /// coalesced link change. This is the engine half of "react to a network change": after a Wi-Fi
    /// switch / sleep-wake the old socket's NAT mapping and learned paths are stale, and the bare
    /// [`rebind`](Self::rebind) only swaps the socket then waits out the periodic ping (2s) / STUN
    /// (~23s) timers before anything re-confirms. This message collapses that wait:
    ///
    /// 1. [`MagicSock::rebind`] — swap the socket; clear reflexive + every confirmed best path
    ///    (keeping candidates), so peers fail closed to DERP and re-probe over the new socket.
    /// 2. [`MagicSock::send_pings`] — re-ping all candidates **now** on the freshly-swapped socket,
    ///    so a still-reachable peer re-confirms its direct path immediately instead of after up to a
    ///    full `PING_INTERVAL`.
    /// 3. An immediate STUN sweep to the derp map's v4 STUN servers (same source + gate as the
    ///    periodic [`run_stun_prober`]): re-learn our reflexive/public address on the new socket
    ///    now, rather than waiting out the jittered ~23s timer.
    ///
    /// Doing all three inside the actor handler keeps them ordered against every other message the
    /// actor handles (it processes one at a time). The periodic pinger and prober are *tasks*, not
    /// actor messages, so the mailbox does not order this against them; step 3 takes the shared STUN
    /// cursor lock, which is what serializes it against a periodic sweep already in flight (see
    /// [`probe_stun_servers_once`]).
    ///
    /// A no-op (`Ok`) when the underlay bind failed at startup (DERP-only inert mode — there is no
    /// socket to rebind/probe). The STUN sweep is best-effort and never fails the message: if
    /// multiderp is unavailable or the peer-count gate is closed it is simply skipped (pong-harvest
    /// still re-learns reflexives as the re-ping pongs arrive), mirroring how [`run_stun_prober`]
    /// treats those cases.
    ///
    /// The bare [`rebind`](Self::rebind) message and the `Device::rebind` path are left UNCHANGED so
    /// a manual embedder's rebind stays a first-class, probe-free socket swap.
    #[message]
    pub async fn rebind_and_reprobe(&self) -> Result<(), ts_magicsock::Error> {
        let Some(sock) = self.sock.as_ref() else {
            // Inert / DERP-only: nothing to rebind or probe.
            return Ok(());
        };

        // 1. Swap the socket + reset stale local mapping (clears best paths, keeps candidates).
        sock.rebind().await?;

        // 2. Re-ping all candidates now on the new socket (every best is None post-rebind, so this
        //    re-pings everything under the normal cadence gates). A send error is non-fatal: the
        //    periodic pinger backstops it.
        if let Err(e) = sock.send_pings().await {
            tracing::trace!(error = %e, "rebind-and-reprobe: re-ping after rebind");
        }

        // 3. Immediate STUN sweep on the new socket, gated exactly like the periodic prober (skip
        //    while there are no peers — Go's len(peerSet)==0 stop). Best-effort throughout: a stale
        //    derp/multiderp or empty server list just skips this round; pong-harvest from the
        //    re-pings above still re-learns reflexives.
        self.stun_sweep_once(sock).await;

        Ok(())
    }

    /// Force an immediate STUN/endpoint re-probe **without** rebinding the underlay socket — the
    /// engine half of `Device::re_stun` (Go magicsock's `Conn.ReSTUN`). This is the STUN sweep of
    /// [`rebind_and_reprobe`](Self::rebind_and_reprobe) (step 3) on its own: it does NOT swap the
    /// socket and does NOT re-ping peers, so the existing socket, its NAT mapping, and every learned
    /// path are preserved — it only re-learns our reflexive (public) address right now instead of
    /// waiting out the jittered ~23s periodic [`run_stun_prober`] timer.
    ///
    /// Lighter than [`rebind`](Self::rebind)/[`rebind_and_reprobe`](Self::rebind_and_reprobe): use it
    /// when our public endpoint may have changed (e.g. a NAT rebinding) but the socket itself is
    /// fine. A no-op (`Ok`) when the underlay bind failed at startup (DERP-only inert mode — no
    /// socket to probe from). Best-effort and gated exactly like the periodic prober (skipped while
    /// there are no peers — Go's `len(peerSet)==0` stop): a stale derp/multiderp or empty server list
    /// simply skips this round.
    #[message]
    pub async fn re_stun(&self) -> Result<(), ts_magicsock::Error> {
        let Some(sock) = self.sock.as_ref() else {
            // Inert / DERP-only: no socket to STUN from.
            return Ok(());
        };
        self.stun_sweep_once(sock).await;
        Ok(())
    }

    /// One immediate STUN sweep from the bound socket, gated like the periodic prober (skip while
    /// there are no peers — Go's `len(peerSet)==0` stop). Best-effort: a stale/unavailable multiderp
    /// or an empty v4-STUN-server list just skips this round (pong-harvest still re-learns
    /// reflexives). Shared by [`rebind_and_reprobe`](Self::rebind_and_reprobe) (after the rebind +
    /// re-ping) and [`re_stun`](Self::re_stun) (on its own, no rebind), so the gate + server fetch +
    /// per-server fan-out live in one place.
    async fn stun_sweep_once(&self, sock: &MagicSock) {
        if stun_probe_should_run(&self.peer_db) {
            match self.multiderp.ask(multiderp::StunServersV4).await {
                Ok((servers,)) => probe_stun_servers_once(sock, &servers, &self.stun_cursor).await,
                Err(e) => {
                    tracing::trace!(error = %e, "stun sweep: querying stun servers");
                }
            }
        }
    }
}

/// The disco<->node-key binding verifier installed on the [`MagicSock`] (see
/// [`ts_magicsock::BindingVerifier`]). A live read of the peer db (it is replaced as netmaps
/// arrive), so revocations take effect immediately.
///
/// - For a disco **Ping** (`claimed_node_key == Some`): returns `true` only if a peer with this
///   disco key exists in the netmap *and* its control-advertised node key equals the claimed one.
///   A peer must not open a direct path under a node key control did not bind to its disco key.
/// - For a **CallMeMaybe** (`claimed_node_key == None`, no node key on the wire): returns `true`
///   only if the disco key is a current netmap member. This stops an unknown/spoofed disco key
///   from steering us into host-probing attacker-chosen endpoints.
///
/// **Either** of a peer's two known disco keys is accepted — Go
/// [`endpoint.checkAndUpdateDiscoKey`], which every inbound disco comparison in
/// `Conn.handleDiscoMessage` goes through. A peer mid-rotation is still sending under the key it
/// has not switched away from, and refusing that frame costs it its direct path until control
/// catches up. A key belonging to neither slot of any peer is still refused, which is the whole
/// security value of the check.
///
/// When the frame arrived under the peer's *inactive* key — and only after it has passed the
/// binding check above — the sighting is reported on `observed` so the peer tracker can make that
/// key the one we send to (Go's compare-and-swap of `endpointDisco.tsmpActive`). The switch and the
/// path invalidation it triggers both happen there; see [`DiscoKeyObserved`].
///
/// [`endpoint.checkAndUpdateDiscoKey`]: https://github.com/tailscale/tailscale/blob/9ea7cba44591e0cd840c6c94d23274dd222059bf/wgengine/magicsock/endpoint.go
fn verify_binding(
    peer_db: &RwLock<Option<Arc<PeerDb>>>,
    observed: &DiscoKeyObserver,
    disco: &DiscoPublicKey,
    claimed_node_key: Option<&NodePublicKey>,
) -> bool {
    // Resolve and copy out what the decision needs, so the read lock is released before the
    // sighting is reported (the observer channel is unbounded and never blocks, but holding the
    // peer-db lock across an unrelated send is a deadlock shape worth not having).
    let resolved = {
        let db = poisoned_read(peer_db);
        let db = db.as_ref().and_then(|db| db.peer_by_known_disco_key(disco));
        db.map(|(peer, node, matched)| (peer, node.node_key, matched))
    };
    let Some((peer, node_key, matched)) = resolved else {
        return false;
    };

    let bound = match claimed_node_key {
        // Ping: the claimed node key must be exactly the one control bound to this disco key.
        Some(claimed) => node_key == *claimed,
        // CallMeMaybe: membership is enough — the disco key resolving to a netmap peer above
        // already proves it.
        None => true,
    };
    if !bound {
        return false;
    }

    if matched == DiscoKeyMatch::Inactive {
        // Best effort: a closed channel means the runtime is shutting down. The frame is still
        // accepted — attribution is correct either way, only the active-key switch is missed.
        let _ = observed.send(DiscoKeyObserved { peer, key: *disco });
    }

    true
}

/// Read an [`RwLock`] guarding the peer db, recovering from poisoning rather than propagating the
/// panic. The peer db is a snapshot replaced wholesale on each netmap update with no cross-field
/// invariant a mid-write panic could leave half-applied, so reading the inner value is safe. A
/// single panic while a writer held this lock must not poison it and cascade-kill the pinger, the
/// binding verifier, and the relayed-disco demux — that would take the dataplane down instead of
/// failing closed to DERP.
fn poisoned_read(
    lock: &RwLock<Option<Arc<PeerDb>>>,
) -> std::sync::RwLockReadGuard<'_, Option<Arc<PeerDb>>> {
    lock.read().unwrap_or_else(|poisoned| poisoned.into_inner())
}

/// Write-lock counterpart of [`poisoned_read`]. Same rationale: recover the inner snapshot rather
/// than let one panicking writer poison the lock and cascade-kill every reader.
fn poisoned_write(
    lock: &RwLock<Option<Arc<PeerDb>>>,
) -> std::sync::RwLockWriteGuard<'_, Option<Arc<PeerDb>>> {
    lock.write()
        .unwrap_or_else(|poisoned| poisoned.into_inner())
}

/// Bidirectional [`PeerId`] <-> [`DiscoPublicKey`] lookup backed by a snapshot of the peer db.
///
/// Uses the owned (`Arc<RwLock<...>>`) form rather than a borrow, because the direct socket
/// lives for the whole runtime and the lookup must outlive any single call.
struct DiscoPeerLookup(Arc<RwLock<Option<Arc<PeerDb>>>>);

impl PeerLookup<PeerId, DiscoPublicKey> for DiscoPeerLookup {
    fn lookup_key(&self, id: PeerId) -> Option<DiscoPublicKey> {
        let db = poisoned_read(&self.0);
        let db = db.as_ref()?;
        let (_, node) = db.get(&id)?;
        node.disco_key
    }
}

impl PeerLookup<DiscoPublicKey, PeerId> for DiscoPeerLookup {
    /// Ingress attribution: accepts **either** of the peer's two known disco keys.
    ///
    /// A path opened by a disco ping under the peer's inactive key attributes its source address to
    /// that key (`MagicSock::add_peer_endpoints` records the sender key of the frame that opened
    /// it), so data arriving over that path resolves through the inactive slot until the active-key
    /// switch lands. Resolving only the active key would drop it.
    ///
    /// No active-key switch is reported from here: this is data attributed by *source address*, not
    /// a disco frame, so it is not the proof-of-possession upstream switches on. That signal comes
    /// from [`verify_binding`] alone, matching Go, which drives `checkAndUpdateDiscoKey` from
    /// `Conn.handleDiscoMessage` and `unambiguousNodeKeyOfPingLocked` only.
    fn lookup_key(&self, key: DiscoPublicKey) -> Option<PeerId> {
        let db = poisoned_read(&self.0);
        let db = db.as_ref()?;
        let (id, _, _) = db.peer_by_known_disco_key(&key)?;
        Some(id)
    }
}

/// Bridge packets between the direct transport and the dataplane underlay channels.
///
/// A simplified [`crate::multiderp::run_derp_once`]: no reconnect or home-derp logic, because
/// the single UDP socket is always bound and never needs re-establishment.
async fn run_direct(
    transport: impl UnderlayTransport<PeerKey = PeerId, Error = ts_magicsock::Error>,
    mut from_dataplane: UnderlayFromDataplane,
    to_dataplane: UnderlayToDataplane,
    mut shutdown: tokio::sync::watch::Receiver<bool>,
) {
    while !*shutdown.borrow() {
        tokio::select! {
            _ = shutdown.changed() => break,

            from_direct = transport.recv() => {
                for ret in from_direct.batch_iter() {
                    match ret {
                        Ok((peer_id, pkts)) => {
                            let pkts = pkts.into_iter().collect::<Vec<_>>();
                            if to_dataplane.send((peer_id, pkts)).is_err() {
                                tracing::error!("underlay receive channel closed");
                                return;
                            }
                        }
                        Err(e) => {
                            tracing::trace!(error = %e, "ignoring undecodable direct packet");
                        }
                    }
                }
            }

            from_net = from_dataplane.recv() => {
                let Some(from_net) = from_net else {
                    tracing::warn!("direct underlay queue closed");
                    break;
                };

                if let Err(e) = transport.send([from_net]).await {
                    tracing::trace!(error = %e, "sending direct packet");
                }
            }
        }
    }
}

/// Periodically (re)ping candidate endpoints to confirm and keep direct paths alive.
async fn run_pinger(sock: Arc<MagicSock>, mut shutdown: tokio::sync::watch::Receiver<bool>) {
    let mut interval = tokio::time::interval(PING_INTERVAL);
    // If a tick is missed (e.g. send_pings ran long under load), space the next tick a full period
    // out rather than firing a burst of catch-up ticks back-to-back.
    interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);

    while !*shutdown.borrow() {
        tokio::select! {
            _ = shutdown.changed() => break,
            _ = interval.tick() => {
                if let Err(e) = sock.send_pings().await {
                    tracing::trace!(error = %e, "sending disco pings");
                }
            }
        }
    }
}

/// Periodically send active STUN Binding Requests to the derp map's STUN servers, learning our
/// reflexive (public) address even before any peer pongs.
///
/// Leak-safe by construction: every request is emitted from the *one* bound underlay socket (see
/// [`MagicSock::send_stun_request`]) and only FixedAddr-v4 STUN servers are targeted (UseDns
/// nodes are skipped by [`Multiderp::stun_servers_v4`] to avoid a DNS-leak / second egress). This
/// complements — does not replace — the disco pong-harvest reflexive path; if the derp map lists
/// no v4 STUN servers the request list is empty and we simply fall back to pong-harvest.
async fn run_stun_prober(
    sock: Arc<MagicSock>,
    peer_db: Arc<RwLock<Option<Arc<PeerDb>>>>,
    multiderp: ActorRef<Multiderp>,
    stun_cursor: Arc<Mutex<usize>>,
    activity: DatapathActivity,
    force_background_stun: Arc<AtomicBool>,
    mut shutdown: tokio::sync::watch::Receiver<bool>,
) {
    // Re-randomize the delay every cycle (Go re-arms `periodicReSTUNTimer` with a fresh
    // `RandomDurationBetween(20s, 26s)` each time) rather than using a fixed `interval`, so the
    // sweep cadence is jittered and never a deterministic beat. No leading immediate sweep: the
    // disco pong-harvest path already learns reflexives from the first peer ping, so we wait a full
    // jittered delay before the first active sweep (matching Go, whose periodic timer is armed for a
    // future instant, not fired immediately).
    while !*shutdown.borrow() {
        tokio::select! {
            _ = shutdown.changed() => break,
            _ = tokio::time::sleep(stun_probe_delay()) => {
                // Skip the sweep when any of Go's ported stop conditions holds — no peers, or a
                // datapath idle past `SESSION_ACTIVE_TIMEOUT` without control's override (see
                // [`should_do_periodic_restun`]). On-wire-equivalent to Go stopping its periodic
                // timer, and auto-resumes with no netmap change the moment a peer appears or
                // traffic returns.
                if !should_do_periodic_restun(&peer_db, &activity, &force_background_stun) {
                    continue;
                }

                // Best-effort: if multiderp is unavailable just skip this round (pong-harvest
                // still runs), matching how the other loops treat multiderp send errors.
                let servers = match multiderp.ask(multiderp::StunServersV4).await {
                    Ok((servers,)) => servers,
                    Err(e) => {
                        tracing::trace!(error = %e, "querying stun servers from multiderp");
                        continue;
                    }
                };
                probe_stun_servers_once(&sock, &servers, &stun_cursor).await;
            }
        }
    }
}

/// How long the datapath may be idle before the periodic STUN sweep stops — Go magicsock's
/// `sessionActiveTimeout` (45s, `wgengine/magicsock/magicsock.go`).
///
/// Deliberately longer than the ~20-26s sweep cadence, so a node carrying any traffic at all keeps
/// STUNning and only a genuinely quiet datapath goes silent.
const SESSION_ACTIVE_TIMEOUT: Duration = Duration::from_secs(45);

/// Whether the periodic STUN sweep has a peer to keep a path open for — Go magicsock's
/// `len(c.peerSet) == 0` stop condition, on its own.
///
/// Returns `true` only when a netmap is loaded *and* it has at least one peer. STUN exists to keep
/// our NAT mapping open so peers can reach us directly; with no configured peer there is nobody to
/// reach, so the sweep is pure waste — and, more importantly for parity, a real `tailscaled` falls
/// quiet on STUN in that state (Go stops its `periodicReSTUNTimer`). A node that keeps emitting
/// Binding Requests every ~23s with no peer is a visible "no peer traffic but steady STUN"
/// fingerprint.
///
/// This is the arm the **on-demand** sweeps ([`DirectManager::re_stun`],
/// [`DirectManager::rebind_and_reprobe`]) use, and only that arm: Go gates on
/// `shouldDoPeriodicReSTUNLocked` inside `periodicReSTUN` alone, so an explicit `Conn.ReSTUN` after
/// a link change re-probes whatever the datapath has been doing. The periodic sweep's full gate is
/// [`should_do_periodic_restun`], which adds the idle arm on top of this one.
///
/// Factored out of [`run_stun_prober`]'s loop so the gate is unit-testable without the actor/timer
/// machinery, mirroring [`probe_stun_servers_once`]. Uses the same `peer_db` snapshot discipline as
/// [`run_call_me_maybe`] (`poisoned_read`, fail-quiet when no netmap is loaded).
fn stun_probe_should_run(peer_db: &RwLock<Option<Arc<PeerDb>>>) -> bool {
    let db = poisoned_read(peer_db);
    db.as_ref().is_some_and(|db| !db.peers().is_empty())
}

/// Whether the **periodic** STUN sweep should run this round — the fork's
/// `shouldDoPeriodicReSTUNLocked`.
///
/// Go's version has four stop conditions. Two are ported here:
///
/// 1. **No peers** — [`stun_probe_should_run`], above.
/// 2. **Datapath idle past [`SESSION_ACTIVE_TIMEOUT`]** — `idleFor > sessionActiveTimeout`, where
///    Go's `idleFunc` is the TUN device's `IdleDuration` (wired in `wgengine/userspace.go`). Here it
///    is [`DatapathActivity::idle_duration`], fed by the one overlay->dataplane seam every datapath
///    send crosses. Without this arm a node with peers and no traffic STUNs the derp map's STUN
///    servers every ~23s for its entire life, which is the same "steady STUN with no peer traffic"
///    fingerprint arm 1 exists to avoid — a real `tailscaled` falls quiet 45s after the last packet.
///
/// The idle arm has exactly one override, ported with it: when control sets the `debug-always-stun`
/// node attribute ([`Node::force_background_stun`](ts_control::Node::force_background_stun), Go's
/// `controlknobs.Knobs.ForceBackgroundSTUN`) an idle datapath no longer stops the sweep. It
/// overrides nothing else — arm 1 returns first, so a peerless node stays quiet either way, exactly
/// as in Go. The override exists because the idle stop takes away today's behaviour, and this is
/// control's only way to ask for it back.
///
/// Go's other two arms are **not** ported:
///
/// * **Zero private key** (`c.privateKey.IsZero()`, "not running") is structurally impossible in
///   this tree and is recorded here rather than implemented: the underlay socket is bound with a
///   real disco/node key pair before [`run_stun_prober`] is ever spawned (see the
///   [`bind_underlay_addr`] call in `on_start`, whose failure path leaves the manager inert with no
///   prober at all), so there is no state in which this task runs without a key.
/// * **Network down / homeless** (`c.networkDown()`, `c.homeless`) needs an OS link-state backend
///   `ts_netmon` does not have yet; it is deliberately left out rather than faked from something
///   weaker, since guessing "the network is down" wrongly would stop STUN on a working node.
fn should_do_periodic_restun(
    peer_db: &RwLock<Option<Arc<PeerDb>>>,
    activity: &DatapathActivity,
    force_background_stun: &AtomicBool,
) -> bool {
    if !stun_probe_should_run(peer_db) {
        return false;
    }

    if activity.idle_duration() > SESSION_ACTIVE_TIMEOUT {
        // Control asked for the background sweep regardless of idleness (Go's
        // `ForceBackgroundSTUN` knob). `Relaxed`: the flag is a single independent bool written by
        // the actor on each netmap and read here on a ~23s cadence; it orders nothing else.
        return force_background_stun.load(Ordering::Relaxed);
    }

    true
}

/// Send one STUN Binding Request per server for as much of `servers` as the socket will admit this
/// round, resuming from — and advancing — `cursor`.
///
/// The round is sized by [`MagicSock::stun_in_flight_remaining`] rather than by the server list.
/// `send_stun_request` records a transaction id per request and drops anything past its in-flight
/// cap *silently*, so a blind `for server in servers` fan-out over a list longer than that cap
/// emits nothing at all for every entry past it. A real derp map lists well over a cap's worth of
/// FixedAddr-v4 STUN servers (one per server node, across every region), the list order is stable,
/// and a round's sends all land inside the same microsecond — no response can free a slot mid-round
/// — so the blind form probed the same head every sweep and never once reached the tail. `cursor`
/// makes the window rotate: each round resumes where the last stopped, so every server in the list
/// is probed within a few rounds and a head of unreachable servers can no longer mask the rest.
///
/// The per-round volume is unchanged (it was already capped, just by a silent drop instead of by
/// the loop bound). A transient io error still just skips that server for this round rather than
/// aborting the sweep.
///
/// `cursor`'s lock is held for the **whole** round — the budget query, the sends it sizes, and the
/// advance — because two sweeps can run at once: the periodic [`run_stun_prober`] task and
/// [`DirectManager::stun_sweep_once`] inside the actor handler are separate tasks, and the actor
/// mailbox orders actor messages only against each other, not against that task. Reading the cursor
/// and writing it back as two steps let the pair interleave, and both interleavings hurt:
///
/// - Both rounds read the same cursor, so both address the same window and the second round's sends
///   are all silently dropped by the now-full in-flight set — an on-demand `re_stun` that emits
///   nothing while the tail it was meant to reach stays unprobed.
/// - The round that started first advances the cursor, then the round that read the stale cursor
///   stores its own `next` over it and *rewinds* the rotation — by however much the first round had
///   already consumed, and all the way to the head when the first round had consumed the whole
///   budget (the late round then sees budget zero, sends nothing, and parks the cursor back at
///   `start`). Either way it reinstates the tail starvation the cursor exists to prevent.
///
/// Holding the lock across the sends also restores the premise
/// [`MagicSock::stun_in_flight_remaining`] documents: with one round at a time we really are the
/// only inserter between the budget query and the sends, so a round sized by that budget still never
/// trips the fail-safe drop. A sweep that arrives while another is in flight waits, then finds the
/// in-flight set full, sends nothing and leaves the cursor where the first round left it — the
/// pre-existing "an on-demand sweep within `STUN_TX_TTL` of a periodic one is a no-op" behaviour,
/// now reached without corrupting the rotation. The wait is bounded by one round of UDP sends.
///
/// Factored out of [`run_stun_prober`]'s sweep loop so the per-sweep fan-out (including the
/// empty-list no-op when the derp map lists no FixedAddr-v4 STUN servers) is unit-testable without
/// the actor/timer machinery.
async fn probe_stun_servers_once(sock: &MagicSock, servers: &[SocketAddr], cursor: &Mutex<usize>) {
    // Control put this node in TCP-443-only mode: netcheck's UDP arm is not planned at all, so the
    // round emits nothing and the rotation does not move. Go's netcheck does the same at the same
    // altitude — `runProbes` skips `makeProbePlan` entirely when the knob is set, and skips the ICMP
    // latency probes with it, leaving a report built from its HTTPS measurements alone. This tree's
    // netcheck (`ts_netcheck`) is HTTPS-only by construction — it has no STUN and no ICMP arm at all
    // — so the DERP-latency report it produces is already exactly that report, and the sweep here is
    // the whole of the UDP half that has to stop.
    //
    // `send_stun_request` refuses again underneath this (with `Error::OnlyTcp443`), which is Go's
    // shape too: both the plan and the send check the knob. Skipping here as well keeps the refusal
    // out of the per-server error log, so a skipped probe is never mistaken for a failed one.
    if sock.only_tcp_443() {
        return;
    }

    let mut cursor = cursor.lock().await;
    let (window, next) = stun_probe_window(servers, *cursor, sock.stun_in_flight_remaining());
    for s in window {
        if let Err(e) = sock.send_stun_request(s).await {
            tracing::trace!(error = %e, server = %s, "sending stun binding request");
        }
    }
    *cursor = next;
}

/// The servers one sweep round should probe — at most `budget` of them, starting at `cursor` and
/// wrapping — together with the cursor the next round resumes from.
///
/// Pure so the rotation is unit-testable without a socket: `budget` is the caller's live in-flight
/// budget ([`MagicSock::stun_in_flight_remaining`]) and `cursor` the value the previous round
/// returned. `cursor` is taken modulo the list length, so a derp map that shrinks between rounds
/// cannot push it out of range. `budget` is clamped to the list length so no server is probed twice
/// in one round. An empty list yields an empty round and resets the cursor.
fn stun_probe_window(
    servers: &[SocketAddr],
    cursor: usize,
    budget: usize,
) -> (Vec<SocketAddr>, usize) {
    if servers.is_empty() {
        return (Vec::new(), 0);
    }
    let start = cursor % servers.len();
    let take = budget.min(servers.len());
    let window = (0..take)
        .map(|i| servers[(start + i) % servers.len()])
        .collect();
    (window, (start + take) % servers.len())
}

/// Periodically re-evaluate our own candidate endpoints and publish them on the bus when they
/// change, so control can be told where peers may reach us directly. Only republishes on a real
/// change to avoid spamming control with redundant side-band map requests.
///
/// Reflexive (STUN-equivalent) endpoints come solely from the disco pong-harvest path on the one
/// bound socket (peers echo our public `src`); we deliberately do **not** run a netcheck-style
/// multi-socket prober for self-endpoint discovery. Such a prober binds its own sockets (including
/// an IPv6 `[::]:0` egress that violates the IPv4-only invariant), so its reflexive mapping would be
/// both a different NAT path and a potential IPv6 leak — which is why the old `ts_netcheck`
/// `StunProber` was removed entirely rather than left dormant in the production binary. Pong-harvest
/// is the leak-safe, parity-correct source for Tier 1.
async fn run_advertiser(
    sock: Arc<MagicSock>,
    env: Env,
    mut shutdown: tokio::sync::watch::Receiver<bool>,
) {
    let mut interval = tokio::time::interval(ADVERTISE_INTERVAL);
    interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
    let mut last: Vec<SelfEndpoint> = Vec::new();

    while !*shutdown.borrow() {
        tokio::select! {
            _ = shutdown.changed() => break,
            _ = interval.tick() => {
                let mut eps = sock.self_endpoints();
                eps.sort_by_key(|e| (e.addr, e.ty as u8));
                if eps == last {
                    continue;
                }
                last = eps.clone();

                if let Err(e) = env
                    .publish(EndpointAdvertisement {
                        endpoints: Arc::new(eps),
                    })
                    .await
                {
                    tracing::error!(error = %e, "publishing endpoint advertisement");
                }
            }
        }
    }
}

/// Periodically send a `CallMeMaybe` over DERP to each peer that has no confirmed direct path
/// yet, prompting it to disco-ping our candidate endpoints so a direct path can open. Gated on
/// [`MagicSock::best_addr`] being `None`: once a path is confirmed we stop relaying to that peer,
/// so this never spams DERP for peers that are already direct.
///
/// We only target peers that have a disco key. The relay region is the peer's netmap home region
/// when control supplied one, else the inferred region from [`Multiderp::region_for_peer`] (an
/// observed route, or our own home region as a last resort) — the same connectivity-floor inference
/// the route updater uses, so a peer whose netmap carried no region can still be prompted to open a
/// direct path (issue #24: without this the WireGuard floor came up over DERP but the direct upgrade
/// was never even attempted for a no-region peer). The frame carries our
/// [`MagicSock::self_endpoints`] — the same set advertised to control — so no host-identifying
/// address beyond that is disclosed.
async fn run_call_me_maybe(
    sock: Arc<MagicSock>,
    peer_db: Arc<RwLock<Option<Arc<PeerDb>>>>,
    multiderp: ActorRef<Multiderp>,
    mut shutdown: tokio::sync::watch::Receiver<bool>,
) {
    let mut interval = tokio::time::interval(ADVERTISE_INTERVAL);
    interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);

    while !*shutdown.borrow() {
        tokio::select! {
            _ = shutdown.changed() => break,
            _ = interval.tick() => {
                // A CallMeMaybe is only actionable to a remote peer if we have a reflexive
                // (STUN-discovered) candidate it can actually reach across the internet; a purely
                // local LAN address is useless to relay over DERP. Skip the whole cadence until we
                // have one, so peers that can never go direct don't incur perpetual relay load.
                // Snapshot self_endpoints once per tick (it locks the reflexive set internally).
                let have_reflexive = sock
                    .self_endpoints()
                    .iter()
                    .any(|e| e.ty == ts_magicsock::SelfEndpointType::Stun);
                if !have_reflexive {
                    continue;
                }

                // Snapshot the targets under the read lock, then release it before any await.
                // `region` is the netmap home region when control gave one, else `None` to be
                // resolved via the fallback below (outside the lock — it's an actor `ask`). We keep
                // the peer either way so a no-region peer is still prompted to go direct.
                let targets: Vec<(ts_keys::NodePublicKey, DiscoPublicKey, Option<ts_derp::RegionId>)> = {
                    let db = poisoned_read(&peer_db);
                    let Some(db) = db.as_ref() else { continue; };

                    db.peers()
                        .values()
                        .filter_map(|node| {
                            let disco = node.disco_key?;
                            // Only prompt peers that don't already have a confirmed direct path.
                            if sock.best_addr(&disco).is_some() {
                                return None;
                            }
                            Some((node.node_key, disco, node.derp_region))
                        })
                        .collect()
                };

                for (node_key, disco, netmap_region) in targets {
                    // Resolve the relay region: netmap home region, else the inferred fallback
                    // (observed route / our home region) — the same floor the route updater uses.
                    let region = match netmap_region {
                        Some(region) => Some(region),
                        None => {
                            // PeerId lookup + region inference both live in multiderp; ask it.
                            match multiderp.ask(multiderp::RegionForNode { node: node_key }).await {
                                Ok(region) => region,
                                Err(e) => {
                                    tracing::trace!(error = %e, "inferring call-me-maybe relay region");
                                    None
                                }
                            }
                        }
                    };
                    let Some(region) = region else {
                        // No region from netmap, no observed route, no home region yet: nothing to
                        // relay through this round. Recovered on the next cadence once one appears.
                        continue;
                    };

                    let frame = match sock.seal_call_me_maybe(&disco) {
                        Ok(frame) => frame,
                        Err(e) => {
                            tracing::trace!(error = %e, "sealing call-me-maybe");
                            continue;
                        }
                    };

                    if let Err(e) = multiderp
                        .tell(multiderp::SendDisco {
                            peer: node_key,
                            region,
                            frame,
                        })
                        .await
                    {
                        tracing::trace!(error = %e, "relaying call-me-maybe to multiderp");
                    }
                }
            }
        }
    }
}

impl kameo::Actor for DirectManager {
    type Args = (Env, ActorRef<DataplaneActor>, ActorRef<Multiderp>);
    type Error = Error;

    async fn on_start(
        (env, dataplane, multiderp): Self::Args,
        slf: ActorRef<Self>,
    ) -> Result<Self, Self::Error> {
        env.subscribe::<Arc<PeerState>>(&slf).await?;
        // The self node, for control's `debug-always-stun` knob — the only override on the periodic
        // sweep's idle stop. Peers arrive via `PeerState`; the cap map does not.
        env.subscribe::<Arc<ts_control::StateUpdate>>(&slf).await?;

        let peer_db: Arc<RwLock<Option<Arc<PeerDb>>>> = Default::default();
        // Off until control says otherwise: the attribute is a debugging escape hatch, and its
        // absence is the quiet (idle-stops-the-sweep) default.
        let force_background_stun = Arc::new(AtomicBool::new(false));
        // One rotation shared by the periodic prober task and the actor's on-demand sweeps, so the
        // two advance through the derp map's STUN servers together instead of each restarting at
        // the head (see `probe_stun_servers_once`).
        let stun_cursor: Arc<Mutex<usize>> = Default::default();
        let mut tasks = JoinSet::new();

        // The disco<->node-key binding verifier: an inbound disco ping must present the node key
        // control bound to its disco key, or `handle_disco` drops it (fail closed). Closed over a
        // live handle to `peer_db` so it tracks netmap changes (revocations take effect at once).
        //
        // A frame that arrives under the peer's *other* known disco key is accepted too, and the
        // sighting is forwarded to the peer tracker over `observed_tx` so that key becomes the one
        // we send to (Go `endpoint.checkAndUpdateDiscoKey`).
        let (observed_tx, observed_rx) = tokio::sync::mpsc::unbounded_channel();
        tasks.spawn(run_disco_key_observer(
            observed_rx,
            env.clone(),
            env.shutdown.clone(),
        ));

        let verifier_db = peer_db.clone();
        let binding_verifier: BindingVerifier = Arc::new(move |disco, claimed_node_key| {
            verify_binding(&verifier_db, &observed_tx, disco, claimed_node_key)
        });

        // Bind the direct underlay UDP socket. A bind failure is transient/environmental (e.g. no
        // ephemeral ports available); rather than panicking the actor we degrade to **DERP-only**
        // and stay inert. DERP-only is the anti-leak-safe fallback (no direct path is ever offered,
        // so the real origin IP can't leak), mirroring the MagicDNS responder's bind-failure
        // posture. The route updater treats a `None` transport id as "stay on DERP" (fail-closed).
        //
        // `enable_ipv6` (default `false`) gates the bind family: IPv4-only `0.0.0.0:0` historically,
        // or a dual-stack `[::]:0` with an inert IPv4 fallback when the overlay opts into IPv6. See
        // [`bind_underlay_addr`].
        let sock = match bind_underlay_addr(
            env.enable_ipv6,
            // The pinned WireGuard/disco port (`Config::wireguard_listen_port`), or `0` for an
            // OS-chosen ephemeral port (today's default). A pinned-but-taken port falls back to
            // ephemeral inside `bind_underlay_addr` so a collision never fails bring-up.
            env.wireguard_listen_port.unwrap_or(0),
            // `.clone()`: the disco private key is no longer `Copy` and `env` is shared (`Arc`),
            // so clone it out for the bind. `node_keys.public` is a `Copy` public key.
            env.keys.disco_keys.private.clone(),
            env.keys.node_keys.public,
        )
        .await
        {
            Ok(sock) => Arc::new(
                sock.with_enable_ipv6(env.enable_ipv6)
                    .with_binding_verifier(binding_verifier),
            ),
            Err(e) => {
                tracing::error!(
                    error = %e,
                    enable_ipv6 = env.enable_ipv6,
                    "direct underlay udp bind failed; direct manager inert, staying DERP-only",
                );
                return Ok(Self {
                    sock: None,
                    transport_id: None,
                    peer_db,
                    multiderp,
                    stun_cursor,
                    force_background_stun,
                    tasks,
                });
            }
        };

        let (transport_id, from_dataplane, to_dataplane) =
            dataplane.ask(NewUnderlayTransport).await?;

        let transport =
            DirectTransport::new(sock.clone()).with_key_lookup(DiscoPeerLookup(peer_db.clone()));

        tasks.spawn(run_direct(
            transport,
            from_dataplane,
            to_dataplane,
            env.shutdown.clone(),
        ));
        tasks.spawn(run_pinger(sock.clone(), env.shutdown.clone()));
        tasks.spawn(run_advertiser(
            sock.clone(),
            env.clone(),
            env.shutdown.clone(),
        ));
        // Active STUN probing shares the one bound socket; clone the multiderp ref before it is
        // moved into run_call_me_maybe below. `peer_db`, the datapath idleness clock and the
        // `debug-always-stun` flag are cloned in so the prober can evaluate Go's
        // `shouldDoPeriodicReSTUNLocked` stop conditions itself (see `should_do_periodic_restun`).
        tasks.spawn(run_stun_prober(
            sock.clone(),
            peer_db.clone(),
            multiderp.clone(),
            stun_cursor.clone(),
            env.datapath_activity.clone(),
            force_background_stun.clone(),
            env.shutdown.clone(),
        ));

        // Hand the bound socket to multiderp so a peer's `CallMeMaybe` relayed to us over DERP is
        // demuxed into the magicsock (and can open a direct path) instead of being forwarded to the
        // dataplane as junk. Best-effort: if multiderp has stopped we stay relay-blind for inbound
        // CallMeMaybe but everything else is unaffected.
        if let Err(e) = multiderp
            .tell(multiderp::SetDirectSock { sock: sock.clone() })
            .await
        {
            tracing::warn!(error = %e, "could not install direct socket on multiderp");
        }

        // Clone for the struct field (the on-demand STUN sweep in `RebindAndReprobe` needs it)
        // before `run_call_me_maybe` consumes the original.
        let multiderp_for_field = multiderp.clone();
        tasks.spawn(run_call_me_maybe(
            sock.clone(),
            peer_db.clone(),
            multiderp,
            env.shutdown.clone(),
        ));

        Ok(Self {
            sock: Some(sock),
            transport_id: Some(transport_id),
            peer_db,
            multiderp: multiderp_for_field,
            stun_cursor,
            force_background_stun,
            tasks,
        })
    }
}

/// A peer whose *active* disco key changed between two consecutive peer-db snapshots.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct DiscoKeyRotation {
    node_key: NodePublicKey,
    previous: DiscoPublicKey,
    current: DiscoPublicKey,
}

/// The peers whose active disco key changed from `previous` to `current`.
///
/// The active key is decided in `peer_tracker` — control's netmap key, a TSMP-advertised one, or
/// whichever of the two `EndpointDisco` holds active — and reaches this actor only as the resolved
/// `Node::disco_key` on the published snapshot. Diffing two consecutive snapshots therefore catches
/// every transition, whatever decided it, without a second channel that each new decision site would
/// have to remember to use. Snapshots arrive in order through this actor's mailbox, so the previous
/// one is exactly the state the magicsock was last reconciled against.
///
/// Only a genuine rotation is reported — a peer that had a key and now has a *different* one:
///
/// - Nodes are matched by **node key**, mirroring Go's peer map. A peer that rotated its node key is
///   a new endpoint upstream, and gets no path state carried over here either.
/// - Acquiring a first disco key (`None` -> `Some`) is not a rotation: there is no path state
///   established under an earlier key, and any state that does exist under the new key was
///   confirmed under that key by an inbound ping, so invalidating it would drop a good path.
/// - Losing a key (`Some` -> `None`) is not one either: with no active key the peer has no path
///   state to carry, and `MagicSock::retain_peers` drops the old entry on this same update.
fn disco_key_rotations(previous: Option<&PeerDb>, current: &PeerDb) -> Vec<DiscoKeyRotation> {
    let Some(previous) = previous else {
        // First snapshot: nothing was reconciled before it, so nothing can have rotated.
        return Vec::new();
    };

    current
        .peers()
        .values()
        .filter_map(|node| {
            let current_key = node.disco_key?;
            let (_, was) = previous.get(&node.node_key)?;
            let previous_key = was.disco_key?;
            (previous_key != current_key).then_some(DiscoKeyRotation {
                node_key: node.node_key,
                previous: previous_key,
                current: current_key,
            })
        })
        .collect()
}

impl Message<Arc<ts_control::StateUpdate>> for DirectManager {
    type Reply = ();

    /// Track the two node attributes control aims at this node's UDP underlay, both refreshed from
    /// `nm.SelfNode`'s cap map on every netmap exactly as Go refreshes its `controlknobs.Knobs`:
    ///
    /// * `debug-always-stun` (Go `Knobs.ForceBackgroundSTUN`) — the only override on the periodic
    ///   STUN sweep's idle stop condition.
    /// * `only-tcp-443` (Go `Knobs.OnlyTCP443`, pushed to magicsock by `ipn/ipnlocal`'s
    ///   `b.MagicConn().SetOnlyTCP443`) — this network alarms on anything that is not TCP/443, so
    ///   the socket must stop emitting UDP altogether and every peer rides DERP. Pushed onto the
    ///   [`MagicSock`] here because that is the chokepoint the refusal lives at; when the underlay
    ///   bind failed (`sock == None`) the node is already DERP-only and there is nothing to silence.
    ///
    /// A response that carries no self node leaves both flags alone rather than clearing them:
    /// control sends field-level and peer-only updates on the same stream, and reading "this
    /// response had no self node" as "control withdrew the attribute" would silently flip a knob off
    /// mid-session — for `only-tcp-443` that would put UDP back on a network that alarms on it. A
    /// response that *does* restate the self node without the attribute is control withdrawing it,
    /// and UDP resumes with no restart (Go's `SetOnlyTCP443` is live too).
    async fn handle(
        &mut self,
        msg: Arc<ts_control::StateUpdate>,
        _ctx: &mut Context<Self, Self::Reply>,
    ) {
        apply_self_node_knobs(
            msg.node.as_ref(),
            &self.force_background_stun,
            self.sock.as_deref(),
        );
    }
}

/// Apply the self node's control knobs for the direct underlay — the body of the
/// [`ts_control::StateUpdate`] handler above, free-standing and taking exactly what it reads so the
/// wiring is unit-testable without standing up the actor, the dataplane and the DERP mesh behind
/// it. Same reason [`should_do_periodic_restun`] and [`probe_stun_servers_once`] are free functions
/// here.
///
/// `self_node` is `None` when the response carried no self node, and then **neither** knob moves —
/// see the handler's doc for why that is not the same as control withdrawing an attribute.
/// `sock` is `None` when the underlay bind failed at startup: the node is already DERP-only, so
/// there is no UDP to silence and nothing to push the TCP-443-only flag onto.
fn apply_self_node_knobs(
    self_node: Option<&ts_control::Node>,
    force_background_stun: &AtomicBool,
    sock: Option<&MagicSock>,
) {
    let Some(self_node) = self_node else {
        return;
    };

    let force = self_node.force_background_stun();
    if force_background_stun.swap(force, Ordering::Relaxed) != force {
        tracing::info!(
            force_background_stun = force,
            "control changed the background-STUN override; the periodic sweep's idle stop \
             follows it",
        );
    }

    if let Some(sock) = sock {
        sock.set_only_tcp_443(self_node.only_tcp_443());
    }
}

/// Disco-ping every candidate of each peer whose path state was just invalidated by a disco-key
/// rotation, now rather than on the next pinger tick. Returns the number of pings that left the
/// socket (the caller logs it; the count is what the test asserts on).
///
/// This is what keeps a rotation cheap. `PeerPaths::invalidate_disco_path` drops the trust window,
/// so `MagicSock::best_addr` reports no direct path and the route updater relays the peer over DERP
/// until a fresh pong lands. Upstream covers that gap differently — `addrForSendLocked`
/// (`wgengine/magicsock/endpoint.go`) returns the retained-but-untrusted `bestAddr` *and* the DERP
/// address, so a packet goes over both while the path is re-confirmed — which this tree cannot do:
/// the dataplane routes each peer through exactly one underlay transport
/// (`route_updater::overlay_direct`). What it can do is make the re-confirmation prompt. Without
/// this, nothing re-probes a rotated peer until the next `PING_INTERVAL` tick, so the detour is
/// up to a ping interval *plus* the round trip; with it, the pong is in flight before the netmap
/// handler returns.
///
/// It is the same event-driven trigger a `CallMeMaybe` gets, for the same reason: an event has just
/// told us this peer's path must be re-established now. What it borrows from that trigger is the
/// *immediacy*, not the floor bypass — `invalidate_disco_path` has already cleared every
/// `last_ping`, so nothing is floored at this point anyway. Rotations are rare and the fan-out is
/// bounded by the peer's candidate set, so the pings stay well inside a stock client's disco volume.
///
/// A send failure is logged and skipped, never retried here: the periodic pinger is still running
/// and will re-probe the peer on its own cadence, so a transient socket error costs the prompt
/// re-confirmation, not the path.
async fn reprobe_rotated_peers(sock: &MagicSock, rotated: &[DiscoPublicKey]) -> usize {
    let mut sent = 0;
    for peer in rotated {
        match sock.send_pings_to_peer_now(peer).await {
            Ok(n) => sent += n,
            Err(e) => {
                tracing::warn!(
                    error = %e,
                    "re-probing a peer whose disco key changed; it stays on DERP until the \
                     periodic pinger re-confirms a path",
                );
            }
        }
    }
    sent
}

impl Message<Arc<PeerState>> for DirectManager {
    type Reply = ();

    async fn handle(&mut self, msg: Arc<PeerState>, _ctx: &mut Context<Self, Self::Reply>) {
        // Reconcile, don't just add: control is authoritative for each peer's underlay endpoints,
        // so an address it stops advertising must be pruned (otherwise a revoked/reassigned addr
        // stays a ping candidate forever and could be re-confirmed as a direct path). Peers that
        // leave the netmap entirely are dropped so both path and attribution maps stay bounded.
        //
        // When the underlay bind failed at startup (`sock == None`) we're inert/DERP-only: there is
        // no socket to reconcile endpoints against, so skip it. We still keep `peer_db` current for
        // any other consumers and so the manager recovers no worse than the route-updater's
        // DERP-only path.
        if let Some(sock) = self.sock.as_ref() {
            // Control's `silent-disco` attribute, off the self node this snapshot was built from.
            // Pushed BEFORE the reconcile below so a peer whose path state is created by that
            // reconcile is created already silent, rather than heartbeating until the next netmap.
            // This is Go's ordering too: `updateNetmapLocked` carries `debugFlagsLocked()` into the
            // `updateFromNode` that creates or refreshes each endpoint.
            sock.set_silent_disco(msg.silent_disco);

            // A peer whose active disco key changed keeps its path state, minus the trust window —
            // Go `endpoint.changedActiveDiscoLocked`. This must run BEFORE the reconcile and prune
            // below: those are keyed by the peer's *current* disco key, so the old key's entry would
            // otherwise be deleted whole by `retain_peers` and the peer would have to rediscover
            // every endpoint from scratch. See `disco_key_rotations` for why the previous snapshot
            // is the signal.
            let rotations = {
                let previous = poisoned_read(&self.peer_db);
                disco_key_rotations(previous.as_deref(), &msg.peers)
            };
            let mut invalidated = Vec::new();
            for rotation in rotations {
                tracing::info!(
                    node_key = %rotation.node_key,
                    previous = %rotation.previous,
                    current = %rotation.current,
                    "peer disco key changed; invalidating its trusted direct path",
                );
                if sock.changed_active_disco(&rotation.previous, &rotation.current) {
                    invalidated.push(rotation.current);
                }
            }

            let mut live = HashSet::new();
            for node in msg.peers.peers().values() {
                let Some(disco) = node.disco_key else {
                    continue;
                };
                live.insert(disco);
                sock.set_netmap_endpoints(disco, node.underlay_addresses.iter().copied());
            }
            sock.retain_peers(&live);

            // Re-probe every peer whose path was just invalidated, now rather than on the next
            // periodic tick. Deliberately AFTER the reconcile above so the probe targets the
            // candidate set control just authorized: an endpoint this snapshot revoked is already
            // pruned and is not pinged, and one it just added is.
            let pings = reprobe_rotated_peers(sock, &invalidated).await;
            if pings > 0 {
                tracing::debug!(
                    pings,
                    peers = invalidated.len(),
                    "re-probing rotated peers now rather than on the next pinger tick",
                );
            }
        }

        let mut db = poisoned_write(&self.peer_db);
        *db = Some(msg.peers.clone());
    }
}

#[cfg(test)]
mod tests {
    use core::net::Ipv4Addr;

    use ts_control::{Node, StableNodeId, TailnetAddress};
    use ts_keys::{DiscoPrivateKey, NodePrivateKey};

    use super::*;
    use crate::peer_tracker::PeerDb;

    /// Build a minimal netmap peer with the given disco and node keys.
    fn node_with_keys(disco: DiscoPublicKey, node_key: NodePublicKey, stable: &str) -> Node {
        Node {
            id: 1,
            stable_id: StableNodeId(stable.to_string()),
            hostname: "peer".to_string(),
            user_id: 0,
            tailnet: Some("ts.net".to_string()),
            tags: vec![],
            addresses: vec![
                "100.64.0.9/32".parse().unwrap(),
                "fd7a::9/128".parse().unwrap(),
            ],
            tailnet_address: TailnetAddress {
                ipv4: "100.64.0.9/32".parse().unwrap(),
                ipv6: "fd7a::9/128".parse().unwrap(),
            },
            node_key,
            node_key_expiry: None,
            expired: false,
            online: None,
            last_seen: None,
            key_signature: vec![],
            machine_key: None,
            disco_key: Some(disco),
            accepted_routes: vec![],
            underlay_addresses: vec![],
            derp_region: None,
            cap: Default::default(),
            cap_map: Default::default(),
            peerapi_port: None,
            peerapi_dns_proxy: false,
            is_wireguard_only: false,
            exit_node_dns_resolvers: vec![],
            peer_relay: false,
            ssh_host_keys: vec![],
            service_vips: Default::default(),
            unsigned_peer_api_only: false,
        }
    }

    fn db_with(node: Node) -> Arc<RwLock<Option<Arc<PeerDb>>>> {
        let mut db = PeerDb::default();
        db.upsert(&node);
        Arc::new(RwLock::new(Some(Arc::new(db))))
    }

    /// A peer db holding `node` under its active disco key plus `inactive` as the peer's other
    /// known key — the mid-rotation state the peer tracker publishes.
    fn db_with_inactive_key(
        node: Node,
        inactive: DiscoPublicKey,
    ) -> Arc<RwLock<Option<Arc<PeerDb>>>> {
        let mut db = PeerDb::default();
        let id = db.upsert(&node);
        db.set_inactive_disco_key(id, Some(inactive));
        Arc::new(RwLock::new(Some(Arc::new(db))))
    }

    /// An observer channel plus its receiver, for driving [`verify_binding`] in tests.
    fn observer() -> (
        DiscoKeyObserver,
        tokio::sync::mpsc::UnboundedReceiver<DiscoKeyObserved>,
    ) {
        tokio::sync::mpsc::unbounded_channel()
    }

    /// A Ping whose claimed node key matches the netmap binding is accepted; a mismatched node key
    /// (or unknown disco key, or empty netmap) is rejected. This is the disco<->node-key binding
    /// check that stops a peer opening a direct path under a node key control did not bind to it.
    #[test]
    fn verify_binding_ping_requires_exact_node_key() {
        let disco = DiscoPrivateKey::random().public_key();
        let node_key = NodePrivateKey::random().public_key();
        let other_key = NodePrivateKey::random().public_key();

        let db = db_with(node_with_keys(disco, node_key, "n1"));
        let (tx, mut rx) = observer();

        assert!(
            verify_binding(&db, &tx, &disco, Some(&node_key)),
            "correct disco<->node-key binding must be accepted"
        );
        assert!(
            !verify_binding(&db, &tx, &disco, Some(&other_key)),
            "a claimed node key that is not the bound one must be rejected"
        );

        let unknown_disco = DiscoPrivateKey::random().public_key();
        assert!(
            !verify_binding(&db, &tx, &unknown_disco, Some(&node_key)),
            "a disco key not in the netmap must be rejected"
        );

        let empty: Arc<RwLock<Option<Arc<PeerDb>>>> = Default::default();
        assert!(
            !verify_binding(&empty, &tx, &disco, Some(&node_key)),
            "with no netmap loaded the verifier fails closed"
        );

        assert!(
            rx.try_recv().is_err(),
            "a frame under the peer's ACTIVE key reports no active-key switch"
        );
    }

    /// A CallMeMaybe carries no node key (claimed=None): membership is sufficient. A member disco
    /// key is accepted; a stranger disco key is rejected. This stops a spoofed disco key from
    /// steering us into host-probing attacker-chosen endpoints.
    #[test]
    fn verify_binding_call_me_maybe_is_membership_only() {
        let disco = DiscoPrivateKey::random().public_key();
        let node_key = NodePrivateKey::random().public_key();

        let db = db_with(node_with_keys(disco, node_key, "n1"));
        let (tx, _rx) = observer();

        assert!(
            verify_binding(&db, &tx, &disco, None),
            "a netmap-member disco key must be accepted for a CallMeMaybe"
        );

        let stranger = DiscoPrivateKey::random().public_key();
        assert!(
            !verify_binding(&db, &tx, &stranger, None),
            "a non-member disco key must be rejected for a CallMeMaybe"
        );
    }

    /// A peer mid-rotation sends disco under the key it has not switched away from. The frame must
    /// be accepted — refusing it costs the peer its direct path until control catches up — and the
    /// sighting must be reported so the peer tracker makes that key the one we send to (Go
    /// `endpoint.checkAndUpdateDiscoKey`).
    #[test]
    fn verify_binding_accepts_the_peers_inactive_disco_key_and_reports_it() {
        let active = DiscoPrivateKey::random().public_key();
        let inactive = DiscoPrivateKey::random().public_key();
        let node_key = NodePrivateKey::random().public_key();

        let db = db_with_inactive_key(node_with_keys(active, node_key, "n1"), inactive);
        let peer = db
            .read()
            .unwrap()
            .as_ref()
            .and_then(|db| db.has(&node_key))
            .expect("the peer is in the db");
        let (tx, mut rx) = observer();

        assert!(
            verify_binding(&db, &tx, &inactive, Some(&node_key)),
            "a ping under the peer's other known disco key must be accepted"
        );
        let seen = rx.try_recv().expect("the sighting is reported");
        assert_eq!(seen.peer, peer);
        assert_eq!(seen.key, inactive);

        // A CallMeMaybe (no node key on the wire) resolves the same way.
        assert!(
            verify_binding(&db, &tx, &inactive, None),
            "a CallMeMaybe under the peer's other known disco key must be accepted"
        );
        assert_eq!(rx.try_recv().expect("reported too").key, inactive);
    }

    /// The refusals that give the two-key check its security value, all against the SAME db that
    /// accepts the inactive key above.
    ///
    /// A third key — one belonging to neither of the peer's two slots — is still refused, and so is
    /// a frame that presents a real inactive key with somebody else's node key. Neither reports a
    /// switch: a refused frame must not be able to move a peer's active key.
    #[test]
    fn verify_binding_refuses_a_key_in_neither_slot() {
        let active = DiscoPrivateKey::random().public_key();
        let inactive = DiscoPrivateKey::random().public_key();
        let third = DiscoPrivateKey::random().public_key();
        let node_key = NodePrivateKey::random().public_key();
        let other_node_key = NodePrivateKey::random().public_key();

        let db = db_with_inactive_key(node_with_keys(active, node_key, "n1"), inactive);
        let (tx, mut rx) = observer();

        assert!(
            !verify_binding(&db, &tx, &third, Some(&node_key)),
            "a disco key in neither slot must be refused even for a known node key"
        );
        assert!(
            !verify_binding(&db, &tx, &third, None),
            "and for a CallMeMaybe, which has no node key to check at all"
        );
        assert!(
            !verify_binding(&db, &tx, &inactive, Some(&other_node_key)),
            "the inactive key is still bound to its own node key"
        );

        assert!(
            rx.try_recv().is_err(),
            "a refused frame must never report an active-key switch"
        );
    }

    /// One probe round to a v4 STUN server emits a well-formed STUN Binding Request from the one
    /// bound underlay socket: 20 bytes, message type `0x0001`, magic cookie `0x2112A442`. This
    /// pins the per-tick fan-out that `run_stun_prober` drives, independent of the interval/actor
    /// machinery.
    #[tokio::test]
    async fn probe_stun_servers_once_sends_binding_request() {
        let sock = Arc::new(
            MagicSock::bind(
                BIND_ADDR.parse().unwrap(),
                DiscoPrivateKey::random(),
                NodePrivateKey::random().public_key(),
            )
            .await
            .unwrap(),
        );

        // A real local v4 sink so the request is actually delivered and observable.
        let sink = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
        let server: SocketAddr = sink.local_addr().unwrap();

        let cursor = Mutex::new(0);
        probe_stun_servers_once(&sock, &[server], &cursor).await;

        let mut buf = [0u8; 64];
        let (n, _from) = tokio::time::timeout(Duration::from_secs(2), sink.recv_from(&mut buf))
            .await
            .expect("a STUN binding request must arrive at the v4 server")
            .unwrap();

        // A STUN Binding Request is 40 bytes: the 20-byte header + SOFTWARE("tailnode") +
        // FINGERPRINT, matching Go net/stun.Request (a bare header is rejected by Tailscale's DERP
        // STUN servers as ErrWrongSoftware). See ts_magicsock::stun::encode_binding_request.
        assert_eq!(
            n, 40,
            "a STUN Binding Request is the 40-byte SOFTWARE+FINGERPRINT form"
        );
        assert_eq!(
            &buf[0..2],
            &0x0001u16.to_be_bytes(),
            "message type must be Binding Request (0x0001)"
        );
        assert_eq!(
            &buf[2..4],
            &0x0014u16.to_be_bytes(),
            "message length must be 0x0014 (the 20 trailing attribute bytes)"
        );
        assert_eq!(
            &buf[4..8],
            &0x2112_A442u32.to_be_bytes(),
            "the STUN magic cookie must be present at bytes[4..8]"
        );
        // SOFTWARE attribute: type 0x8022, len 8, value "tailnode".
        assert_eq!(
            &buf[20..22],
            &0x8022u16.to_be_bytes(),
            "SOFTWARE attribute type"
        );
        assert_eq!(&buf[24..32], b"tailnode", "SOFTWARE value must be tailnode");
        // FINGERPRINT attribute: type 0x8028, len 4.
        assert_eq!(
            &buf[32..34],
            &0x8028u16.to_be_bytes(),
            "FINGERPRINT attribute type"
        );
    }

    /// A server list longer than the socket's in-flight budget must not starve its tail forever.
    ///
    /// This is the regression: `send_stun_request` drops silently once its in-flight set is full, a
    /// real derp map lists far more FixedAddr-v4 STUN servers than that cap, and a round's sends all
    /// land before any response can free a slot — so the old blind `for server in servers` fan-out
    /// probed the same head every sweep and never reached the tail at all. A round must instead stop
    /// at the budget and leave the cursor on the first server it could not reach, so the next round
    /// starts there.
    ///
    /// Asserted through the socket's own budget rather than by receiving the datagrams: the point
    /// under test is where the round stops and resumes, and `stun_in_flight_remaining` is the same
    /// number `send_stun_request` admits against. Which servers a window covers is pinned by
    /// [`stun_probe_window_rotates_across_rounds`]; that a request reaches the wire is pinned by
    /// [`probe_stun_servers_once_sends_binding_request`].
    #[tokio::test]
    async fn probe_stun_servers_once_stops_at_the_in_flight_budget() {
        let sock = Arc::new(
            MagicSock::bind(
                BIND_ADDR.parse().unwrap(),
                DiscoPrivateKey::random(),
                NodePrivateKey::random().public_key(),
            )
            .await
            .unwrap(),
        );

        // The budget the socket will actually admit this round, read from the production accessor
        // rather than hard-coded: the cap lives in ts_magicsock and is private there.
        let budget = sock.stun_in_flight_remaining();
        assert!(budget > 0, "a fresh socket must admit some requests");

        // A server list deliberately longer than that budget — the shape of a real derp map, and
        // the premise of the bug. Real bound sockets so every `send_to` has a live destination.
        let mut sinks = Vec::new();
        for _ in 0..(budget + 4) {
            sinks.push(tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap());
        }
        let servers: Vec<SocketAddr> = sinks.iter().map(|s| s.local_addr().unwrap()).collect();
        assert!(
            servers.len() > budget,
            "the test needs a server list longer than the in-flight budget"
        );

        let cursor = Mutex::new(0);
        probe_stun_servers_once(&sock, &servers, &cursor).await;

        // The round consumed exactly the budget — it neither stopped short nor ran on into the
        // silent-drop path for the remaining servers.
        assert_eq!(
            sock.stun_in_flight_remaining(),
            0,
            "the round must use the whole in-flight budget"
        );
        assert_eq!(
            *cursor.lock().await,
            budget,
            "the cursor must resume at the first server this round could not reach"
        );

        // A later sweep, whose in-flight set has drained (a real round is ~23s later and
        // STUN_TX_TTL is 5s), picks up at that cursor rather than back at the head — so the tail
        // this round starved is what the next round probes first.
        let (next_round, _) = stun_probe_window(&servers, *cursor.lock().await, budget);
        for starved in &servers[budget..] {
            assert!(
                next_round.contains(starved),
                "{starved} was starved this round and must be probed in the next"
            );
        }
    }

    /// Two sweeps that overlap must leave the rotation one round further on — never rewound.
    ///
    /// The periodic `run_stun_prober` task and the actor's on-demand sweep (`re_stun`,
    /// `rebind_and_reprobe`) are separate tasks sharing one cursor, so they can run at the same
    /// time; the actor mailbox orders actor messages against each other, not against that task.
    /// When a round read the cursor, sent, and wrote the cursor back as three separable steps, the
    /// pair could interleave so that both sized a window off the same cursor and the same in-flight
    /// budget — the second round's sends then hit `send_stun_request`'s silent drop — and so that
    /// the round holding the stale cursor wrote its `next` *after* the other round's, rewinding the
    /// rotation by however much the first round had already consumed (all the way to the head when
    /// the first round had consumed the whole budget) and reinstating the tail starvation the
    /// cursor exists to prevent.
    ///
    /// The invariant is one round at a time: whichever sweep wins spends the whole budget and parks
    /// the cursor past it, and the other finds the in-flight set full, sends nothing, and leaves
    /// the cursor where it was. Two worker threads so the overlap is real parallelism, not two
    /// tasks taking turns on one thread.
    ///
    /// Repeated over fresh state because a single overlapping pair can run effectively
    /// sequentially, and the unserialized shape happens to leave the right answer when it does.
    /// Against that shape (cursor read and written back around the sends rather than held across
    /// them) this catches the rewind on the first or second pair, and both flavours of it — the
    /// full rewind to the head and the partial one. Over `ROUNDS` pairs missing it is very
    /// unlikely, but it is still a probabilistic catch rather than a proof: the invariant itself is
    /// held by construction, by the guard living for the whole of `probe_stun_servers_once`.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn concurrent_stun_sweeps_advance_one_rotation_and_never_rewind() {
        // Overlapping pairs to run. Each is a fresh socket and a fresh cursor; the sinks are
        // shared, so a pair costs one UDP bind and a handful of loopback sends.
        const ROUNDS: usize = 25;

        let budget = MagicSock::bind(
            BIND_ADDR.parse().unwrap(),
            DiscoPrivateKey::random(),
            NodePrivateKey::random().public_key(),
        )
        .await
        .unwrap()
        .stun_in_flight_remaining();
        assert!(budget > 0, "a fresh socket must admit some requests");

        // A server list longer than one round's budget — the shape of a real derp map, and the only
        // shape where the rotation (and therefore a rewind of it) is observable. Real bound sockets
        // so every `send_to` has a live destination.
        let mut sinks = Vec::new();
        for _ in 0..(budget + 2) {
            sinks.push(tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap());
        }
        let servers: Arc<Vec<SocketAddr>> =
            Arc::new(sinks.iter().map(|s| s.local_addr().unwrap()).collect());

        for round in 0..ROUNDS {
            let sock = Arc::new(
                MagicSock::bind(
                    BIND_ADDR.parse().unwrap(),
                    DiscoPrivateKey::random(),
                    NodePrivateKey::random().public_key(),
                )
                .await
                .unwrap(),
            );
            let cursor: Arc<Mutex<usize>> = Arc::new(Mutex::new(0));

            let sweeps: Vec<_> = (0..2)
                .map(|_| {
                    let (sock, servers, cursor) = (sock.clone(), servers.clone(), cursor.clone());
                    tokio::spawn(async move {
                        probe_stun_servers_once(&sock, &servers, &cursor).await;
                    })
                })
                .collect();
            for sweep in sweeps {
                sweep.await.unwrap();
            }

            let parked = *cursor.lock().await;
            // The rewind, in both its shapes: back to the head when the late round read a spent
            // budget, and short by whatever the first round had already sent otherwise.
            assert!(
                parked >= budget,
                "round {round}: the rotation rewound by {} — the late sweep wrote a `next` sized \
                 off the cursor the first sweep had already moved past",
                budget - parked
            );
            assert_eq!(
                parked, budget,
                "round {round}: the two sweeps must advance the rotation exactly one round; \
                 anything past the budget is a window nobody actually probed"
            );
            assert_eq!(
                sock.stun_in_flight_remaining(),
                0,
                "round {round}: the pair must spend one round's budget between them, not size two \
                 rounds off the same budget"
            );

            // The next round therefore picks up the tail this pair could not reach, rather than
            // re-probing the head a third time.
            let (next_round, _) = stun_probe_window(&servers, parked, budget);
            for starved in &servers[budget..] {
                assert!(
                    next_round.contains(starved),
                    "round {round}: {starved} was starved by the overlapping pair and must be \
                     probed next round"
                );
            }
        }
    }

    /// A sweep that arrives while another round owns the cursor waits for it, and while it waits it
    /// spends none of the in-flight budget.
    ///
    /// This is the ordering half of the serialization: a round takes the cursor *before* it queries
    /// `stun_in_flight_remaining`, so a second sweep cannot even size a window — let alone send —
    /// while another round holds the cursor. That the exclusion also spans the sends is not
    /// something this test can observe (a narrow lock would park the spawned sweep at the same first
    /// acquisition); it follows from the guard living for the whole of `probe_stun_servers_once`,
    /// and it is what `MagicSock::stun_in_flight_remaining`'s "we are the only inserter" premise
    /// needs. Held from the test itself rather than by a second sweep so the wait is unambiguous.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn stun_sweep_waits_for_the_round_ahead_of_it() {
        let sock = Arc::new(
            MagicSock::bind(
                BIND_ADDR.parse().unwrap(),
                DiscoPrivateKey::random(),
                NodePrivateKey::random().public_key(),
            )
            .await
            .unwrap(),
        );
        let budget = sock.stun_in_flight_remaining();

        // A real bound destination so the send has somewhere to go.
        let sink = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
        let server: SocketAddr = sink.local_addr().unwrap();

        let cursor: Arc<Mutex<usize>> = Arc::new(Mutex::new(0));
        // Stand in for a round already in flight (the periodic prober's, say).
        let round_in_flight = cursor.clone().lock_owned().await;

        let sweep = tokio::spawn({
            let (sock, cursor) = (sock.clone(), cursor.clone());
            async move {
                probe_stun_servers_once(&sock, &[server], &cursor).await;
            }
        });

        // Give the spawned sweep every chance to run past the lock, then check it did not: no
        // transaction recorded (so nothing was sent — `send_stun_request` records before it sends)
        // and the round still parked.
        tokio::time::sleep(Duration::from_millis(300)).await;
        assert!(
            !sweep.is_finished(),
            "a sweep must wait for the round in front of it rather than run beside it"
        );
        assert_eq!(
            sock.stun_in_flight_remaining(),
            budget,
            "a waiting sweep must not have spent any of the budget the round ahead of it is sizing \
             against"
        );

        drop(round_in_flight);

        tokio::time::timeout(Duration::from_secs(2), sweep)
            .await
            .expect("the sweep must proceed once the cursor is released")
            .unwrap();
        assert_eq!(
            sock.stun_in_flight_remaining(),
            budget - 1,
            "the released sweep spends exactly its one request"
        );
    }

    /// The rotation itself: successive rounds over a list longer than one round's budget must cover
    /// every server, with no server probed twice inside a round and no gap between rounds.
    #[test]
    fn stun_probe_window_rotates_across_rounds() {
        // RFC 5737 documentation addresses; 20 servers, 16 per round.
        let servers: Vec<SocketAddr> = (1..=20u8)
            .map(|i| SocketAddr::from((Ipv4Addr::new(192, 0, 2, i), 3478)))
            .collect();
        let budget = 16;

        let (round1, next) = stun_probe_window(&servers, 0, budget);
        assert_eq!(round1, servers[..16], "round 1 probes the head of the list");
        assert_eq!(
            next, 16,
            "round 2 resumes at the first server round 1 skipped"
        );

        let (round2, next) = stun_probe_window(&servers, next, budget);
        let expected2: Vec<SocketAddr> = servers[16..]
            .iter()
            .chain(servers[..12].iter())
            .copied()
            .collect();
        assert_eq!(round2, expected2, "round 2 wraps from the cursor");
        assert_eq!(next, 12);

        // The starved tail of round 1 is covered by round 2 — the whole point.
        for s in &servers[16..] {
            assert!(
                round2.contains(s),
                "{s} was starved in round 1 and must be probed in round 2"
            );
        }
        // Two rounds cover every server at least once.
        for s in &servers {
            assert!(
                round1.contains(s) || round2.contains(s),
                "{s} must be probed within two rounds"
            );
        }
    }

    /// Degenerate windows: no servers, and a budget wider than the list. A budget wider than the
    /// list must not probe a server twice in one round (the cap makes the duplicate a silent drop,
    /// which would starve a real server for its sake).
    #[test]
    fn stun_probe_window_handles_short_lists() {
        let (window, next) = stun_probe_window(&[], 7, 16);
        assert!(window.is_empty(), "an empty derp map probes nothing");
        assert_eq!(next, 0, "an empty list resets the cursor");

        let servers: Vec<SocketAddr> = (1..=3u8)
            .map(|i| SocketAddr::from((Ipv4Addr::new(192, 0, 2, i), 3478)))
            .collect();
        let (window, next) = stun_probe_window(&servers, 2, 16);
        assert_eq!(
            window.len(),
            servers.len(),
            "a budget wider than the list probes each server exactly once"
        );
        assert_eq!(window[0], servers[2], "the round starts at the cursor");
        for s in &servers {
            assert_eq!(
                window.iter().filter(|w| *w == s).count(),
                1,
                "{s} must be probed exactly once per round"
            );
        }
        assert_eq!(next, 2, "a full pass leaves the cursor where it started");

        // An out-of-range cursor (the derp map shrank between rounds) is taken modulo the length.
        let (window, _) = stun_probe_window(&servers, 99, 1);
        assert_eq!(window, vec![servers[99 % 3]]);
    }

    /// With `enable_ipv6 == false` (the default) the underlay socket binds the historical IPv4
    /// path: its local address is in the v4 family (`0.0.0.0`). This pins the sacred default — the
    /// privacy-proxy deployment must stay byte-for-byte IPv4-only when the gate is off.
    #[tokio::test]
    async fn bind_underlay_addr_v4_default_is_unchanged() {
        let sock = bind_underlay_addr(
            false,
            0,
            DiscoPrivateKey::random(),
            NodePrivateKey::random().public_key(),
        )
        .await
        .expect("the IPv4 underlay bind must succeed");

        let local = sock.local_addr().expect("a bound socket has a local addr");
        assert!(
            local.is_ipv4(),
            "with enable_ipv6 == false the underlay must bind the v4 family, got {local}"
        );
        assert_eq!(
            local.ip(),
            "0.0.0.0".parse::<core::net::IpAddr>().unwrap(),
            "the v4 default binds the unspecified v4 address"
        );
    }

    /// A pinned `wireguard_listen_port` (Go `--port`) binds exactly that UDP port when it is free —
    /// the stable-endpoint behavior an operator behind a fixed-pinhole firewall needs. Uses a port
    /// the OS just handed out (then released) to avoid colliding with anything already bound.
    #[tokio::test]
    async fn bind_underlay_addr_pins_requested_port_when_free() {
        // Grab an OS-assigned port, then release it so we can pin it deterministically.
        let probe = tokio::net::UdpSocket::bind("0.0.0.0:0").await.unwrap();
        let want = probe.local_addr().unwrap().port();
        drop(probe);

        let sock = bind_underlay_addr(
            false,
            want,
            DiscoPrivateKey::random(),
            NodePrivateKey::random().public_key(),
        )
        .await
        .expect("pinned-port underlay bind must succeed");

        let local = sock.local_addr().expect("a bound socket has a local addr");
        assert!(local.is_ipv4(), "still the v4 family, got {local}");
        assert_eq!(
            local.port(),
            want,
            "a free pinned port must be bound exactly (got {local})"
        );
    }

    /// A pinned port that is already taken must NOT fail bring-up: the bind falls back to an
    /// OS-chosen ephemeral port (mirroring `rebind_socket`'s `Err(_) if prefer_port != 0 => bind(0)`
    /// fallback), so a port collision can never take the node down. The bound port ends up different
    /// from the (occupied) pinned one.
    #[tokio::test]
    async fn bind_underlay_addr_falls_back_to_ephemeral_when_port_taken() {
        // Occupy a port for the whole test so the pinned bind below must collide.
        let occupier = tokio::net::UdpSocket::bind("0.0.0.0:0").await.unwrap();
        let taken = occupier.local_addr().unwrap().port();

        let sock = bind_underlay_addr(
            false,
            taken,
            DiscoPrivateKey::random(),
            NodePrivateKey::random().public_key(),
        )
        .await
        .expect("a taken pinned port must fall back to ephemeral, never error");

        let local = sock.local_addr().expect("a bound socket has a local addr");
        assert!(local.is_ipv4(), "still the v4 family, got {local}");
        assert_ne!(
            local.port(),
            taken,
            "the occupied port must not be bound; an ephemeral port is used instead"
        );
        assert_ne!(local.port(), 0, "a real ephemeral port must be assigned");
        drop(occupier);
    }

    /// With `enable_ipv6 == true` a dual-stack bind on `[::]:0` is attempted. On a normal dev host
    /// that yields a v6-family socket; if this environment cannot bind v6 at all, the documented
    /// inert fallback returns a v4 socket instead (never a panic, never an error). Either outcome is
    /// acceptable here — the non-flaky guarantee is that a usable socket comes back. The positive
    /// "is v6" assertion is gated on the v6 bind actually succeeding so CI without v6 loopback
    /// doesn't flake.
    #[tokio::test]
    async fn bind_underlay_addr_v6_attempts_dual_stack_or_falls_back() {
        let sock = bind_underlay_addr(
            true,
            0,
            DiscoPrivateKey::random(),
            NodePrivateKey::random().public_key(),
        )
        .await
        .expect("bind must succeed (dual-stack, else inert IPv4 fallback) and never error");

        let local = sock.local_addr().expect("a bound socket has a local addr");

        // Probe whether this host can bind `[::]:0` at all. If it can, the underlay must have taken
        // the dual-stack (v6-family) path; if it can't, the inert fallback must have produced a v4
        // socket. This keeps the assertion deterministic on both v6-capable and v6-disabled hosts.
        match tokio::net::UdpSocket::bind("[::]:0").await {
            Ok(_) => assert!(
                local.is_ipv6(),
                "on a v6-capable host enable_ipv6 == true must bind the v6 (dual-stack) family, \
                 got {local}"
            ),
            Err(_) => assert!(
                local.is_ipv4(),
                "on a host that cannot bind v6 the inert fallback must yield a v4 socket, got \
                 {local}"
            ),
        }
    }

    /// An empty server list (the derp map lists no FixedAddr-v4 STUN servers) is a no-op: nothing is
    /// sent and we silently fall back to pong-harvest. Probing must not require a STUN server.
    #[tokio::test]
    async fn probe_stun_servers_once_empty_list_is_noop() {
        let sock = Arc::new(
            MagicSock::bind(
                BIND_ADDR.parse().unwrap(),
                DiscoPrivateKey::random(),
                NodePrivateKey::random().public_key(),
            )
            .await
            .unwrap(),
        );

        // No servers => no sends, no panic, returns promptly, and the cursor stays parked.
        let cursor = Mutex::new(0);
        probe_stun_servers_once(&sock, &[], &cursor).await;
        assert_eq!(*cursor.lock().await, 0);
    }

    /// Control's `only-tcp-443` stops the STUN sweep whole: no Binding Request leaves the socket and
    /// the rotation does not move, so the round is *skipped* rather than spent. Go's netcheck does
    /// the same at the same altitude — it skips `makeProbePlan` entirely under the knob (and the
    /// ICMP probes with it), leaving a report built from its HTTPS measurements alone.
    ///
    /// Asserted through the socket's in-flight budget, the same observable
    /// `probe_stun_servers_once_stops_at_the_in_flight_budget` uses: a request that reached the wire
    /// is one that recorded a transaction. Withdrawing the attribute resumes the sweep with no
    /// restart, which is the live-setter half of the port.
    #[tokio::test]
    async fn only_tcp_443_skips_the_whole_stun_sweep() {
        let sock = Arc::new(
            MagicSock::bind(
                BIND_ADDR.parse().unwrap(),
                DiscoPrivateKey::random(),
                NodePrivateKey::random().public_key(),
            )
            .await
            .unwrap(),
        );

        // Real bound sinks so every `send_to` has a live destination — the only thing that can stop
        // a request here is the gate.
        let mut sinks = Vec::new();
        for _ in 0..3 {
            sinks.push(tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap());
        }
        let servers: Vec<SocketAddr> = sinks.iter().map(|s| s.local_addr().unwrap()).collect();

        // The budget of a socket with nothing outstanding, read from the production accessor (the
        // cap itself lives in ts_magicsock and is private there). Every recorded request spends one.
        let budget = sock.stun_in_flight_remaining();
        assert!(
            budget > servers.len(),
            "the test needs a budget the whole server list fits inside"
        );

        sock.set_only_tcp_443(true);
        let cursor = Mutex::new(0);
        probe_stun_servers_once(&sock, &servers, &cursor).await;

        assert_eq!(
            sock.stun_in_flight_remaining(),
            budget,
            "under only-tcp-443 no Binding Request may be sent, so no transaction is recorded"
        );
        assert_eq!(
            *cursor.lock().await,
            0,
            "a skipped round must not advance the rotation — the next real round starts here"
        );

        // Control withdraws it on a later netmap: the sweep resumes on the same socket.
        sock.set_only_tcp_443(false);
        probe_stun_servers_once(&sock, &servers, &cursor).await;
        assert_eq!(
            sock.stun_in_flight_remaining(),
            budget - servers.len(),
            "withdrawing the attribute restores STUN with no restart"
        );
        assert_eq!(
            *cursor.lock().await,
            0,
            "the resumed round wrapped the whole (short) list, parking the cursor back at the head"
        );
    }

    /// Control's `only-tcp-443` reaches the underlay socket the way control sends it: as a key on
    /// the **self** node's cap map, read on every netmap by the handler's body
    /// ([`apply_self_node_knobs`]) and pushed onto the [`MagicSock`]. This pins the whole wiring —
    /// the wire key, the accessor and the push — and both directions of it, because Go's
    /// `SetOnlyTCP443` is live: a netmap that restates the self node without the attribute is
    /// control withdrawing it, and UDP must come back with no restart.
    #[tokio::test]
    async fn only_tcp_443_rides_the_self_node_to_the_underlay_socket() {
        let sock = MagicSock::bind(
            BIND_ADDR.parse().unwrap(),
            DiscoPrivateKey::random(),
            NodePrivateKey::random().public_key(),
        )
        .await
        .unwrap();
        let force = AtomicBool::new(false);

        let mut self_node = node_with_keys(
            DiscoPrivateKey::random().public_key(),
            NodePrivateKey::random().public_key(),
            "self",
        );

        apply_self_node_knobs(Some(&self_node), &force, Some(&sock));
        assert!(
            !sock.only_tcp_443(),
            "a self node without the attribute leaves UDP alone"
        );

        self_node
            .cap_map
            .insert("only-tcp-443".to_string(), Vec::new());
        apply_self_node_knobs(Some(&self_node), &force, Some(&sock));
        assert!(
            sock.only_tcp_443(),
            "the only-tcp-443 cap-map key is what silences the underlay socket"
        );

        // A response that carries no self node at all is a field-level or peer-only update, not a
        // withdrawal: reading it as one would put UDP back on a network that alarms on it.
        apply_self_node_knobs(None, &force, Some(&sock));
        assert!(
            sock.only_tcp_443(),
            "a netmap with no self node must leave the flag exactly as it was"
        );

        self_node.cap_map.remove("only-tcp-443");
        apply_self_node_knobs(Some(&self_node), &force, Some(&sock));
        assert!(
            !sock.only_tcp_443(),
            "control restating the self node without the attribute restores UDP, with no restart"
        );
    }

    /// The inert (bind-failed, DERP-only) manager has no socket to push the flag onto, and applying
    /// the knobs must still be a harmless no-op rather than a panic — the same posture
    /// [`DirectManager::rebind`] has. The background-STUN knob still lands, as it does not need one.
    #[test]
    fn applying_the_self_node_knobs_without_a_socket_is_a_noop() {
        let force = AtomicBool::new(false);
        let mut self_node = node_with_keys(
            DiscoPrivateKey::random().public_key(),
            NodePrivateKey::random().public_key(),
            "self",
        );
        self_node
            .cap_map
            .insert("only-tcp-443".to_string(), Vec::new());
        self_node
            .cap_map
            .insert("debug-always-stun".to_string(), Vec::new());

        apply_self_node_knobs(Some(&self_node), &force, None);
        assert!(
            force.load(Ordering::Relaxed),
            "the background-STUN knob needs no socket and must still be applied"
        );
    }

    /// The periodic STUN sweep is gated on having at least one peer — Go magicsock's
    /// `shouldDoPeriodicReSTUNLocked` `len(c.peerSet) == 0` stop condition. With no netmap loaded,
    /// or a netmap with zero peers, the gate is closed (no STUN, so no "peerless but steady STUN"
    /// fingerprint); once a peer is present it opens.
    #[test]
    fn stun_probe_gated_on_peer_presence() {
        // No netmap loaded yet → fail-quiet (closed), like `verify_binding`'s empty case.
        let empty: Arc<RwLock<Option<Arc<PeerDb>>>> = Default::default();
        assert!(
            !stun_probe_should_run(&empty),
            "with no netmap loaded the prober must not STUN"
        );

        // A netmap with zero peers → still closed.
        let no_peers: Arc<RwLock<Option<Arc<PeerDb>>>> =
            Arc::new(RwLock::new(Some(Arc::new(PeerDb::default()))));
        assert!(
            !stun_probe_should_run(&no_peers),
            "an empty peer set must not STUN (Go's len(peerSet)==0 stop)"
        );

        // One peer present → open.
        let disco = DiscoPrivateKey::random().public_key();
        let node_key = NodePrivateKey::random().public_key();
        let with_peer = db_with(node_with_keys(disco, node_key, "n1"));
        assert!(
            stun_probe_should_run(&with_peer),
            "with a peer present the prober resumes STUN"
        );
    }

    /// `re_stun` (Go `Conn.ReSTUN`) is the STUN sweep WITHOUT a rebind: its body is exactly the
    /// shared [`DirectManager::stun_sweep_once`] gate — skip while there are no peers (Go's
    /// `len(peerSet)==0` stop), otherwise fetch the v4 STUN servers and probe each. This pins the two
    /// gate decisions `re_stun` makes (the peer-presence gate it shares with the periodic prober, and
    /// the empty-server-list no-op), independent of the actor machinery — the same way the periodic
    /// prober's per-tick fan-out is pinned by [`probe_stun_servers_once_*`]. The inert (no-socket,
    /// DERP-only) path is the `self.sock.is_none()` early-return, structurally identical to
    /// [`DirectManager::rebind`]'s inert no-op.
    #[tokio::test]
    async fn re_stun_sweep_gate_matches_periodic_prober() {
        // No peers (and no netmap) → the sweep is gated closed, so re_stun probes nothing.
        let no_peers: Arc<RwLock<Option<Arc<PeerDb>>>> = Default::default();
        assert!(
            !stun_probe_should_run(&no_peers),
            "re_stun must skip the sweep with no peers, like the periodic prober"
        );

        // With a peer present the gate opens; an empty derp v4-STUN list is then a clean no-op
        // (probing must never require a STUN server — pong-harvest backstops it).
        let disco = DiscoPrivateKey::random().public_key();
        let node_key = NodePrivateKey::random().public_key();
        let with_peer = db_with(node_with_keys(disco, node_key, "n1"));
        assert!(
            stun_probe_should_run(&with_peer),
            "re_stun sweeps once a peer is present"
        );
        let sock = Arc::new(
            MagicSock::bind(
                BIND_ADDR.parse().unwrap(),
                DiscoPrivateKey::random(),
                NodePrivateKey::random().public_key(),
            )
            .await
            .unwrap(),
        );
        // Empty server list (what an unavailable/stale derp map yields) → no sends, returns promptly.
        probe_stun_servers_once(&sock, &[], &Mutex::new(0)).await;
    }

    /// The datapath idle stop condition — Go magicsock's `idleFor > sessionActiveTimeout` arm of
    /// `shouldDoPeriodicReSTUNLocked`, whose `idleFunc` is the TUN device's `IdleDuration`.
    ///
    /// A node with peers but no traffic must fall quiet 45s after the last datapath send instead of
    /// STUNning the derp map's STUN servers every ~23s forever; that is the same "steady STUN with no
    /// peer traffic" fingerprint the peer-count arm exists to avoid. The clock is backdated rather
    /// than slept through, so this pins the threshold and not the scheduler.
    #[test]
    fn periodic_stun_stops_when_the_datapath_has_been_idle_past_the_session_timeout() {
        let disco = DiscoPrivateKey::random().public_key();
        let node_key = NodePrivateKey::random().public_key();
        let with_peer = db_with(node_with_keys(disco, node_key, "n1"));
        // Control has not set `debug-always-stun`: the idle stop applies.
        let no_override = AtomicBool::new(false);

        // A datapath that just sent → well inside the window, so the sweep runs.
        let busy = DatapathActivity::new();
        assert!(
            should_do_periodic_restun(&with_peer, &busy, &no_override),
            "an active datapath with a peer must keep STUNning"
        );

        // Idle for less than the timeout → still running (the arm is `>`, not `>=`, and 45s is
        // deliberately longer than the ~20-26s sweep cadence).
        let nearly_idle =
            DatapathActivity::idle_for(SESSION_ACTIVE_TIMEOUT - Duration::from_secs(5));
        assert!(
            should_do_periodic_restun(&with_peer, &nearly_idle, &no_override),
            "idle for under sessionActiveTimeout must not stop the sweep"
        );

        // Idle past the timeout → stopped.
        let idle = DatapathActivity::idle_for(SESSION_ACTIVE_TIMEOUT + Duration::from_secs(1));
        assert!(
            !should_do_periodic_restun(&with_peer, &idle, &no_override),
            "a datapath idle past sessionActiveTimeout must stop the periodic sweep"
        );

        // The on-demand sweeps (`re_stun`, `rebind_and_reprobe`) are NOT idle-gated: Go gates only
        // `periodicReSTUN`, so an explicit re-probe after a link change still runs on a quiet node.
        assert!(
            stun_probe_should_run(&with_peer),
            "the on-demand sweep gate must ignore idleness, as Go's Conn.ReSTUN does"
        );
    }

    /// The idle stop's one override — control's `debug-always-stun` node attribute (Go
    /// `controlknobs.Knobs.ForceBackgroundSTUN`). It is what lets control ask for the pre-idle-stop
    /// behaviour back, and it overrides the idle arm ONLY: a peerless node stays quiet with the
    /// attribute set, because Go's peer-count arm returns before the idle arm is reached.
    #[test]
    fn debug_always_stun_overrides_the_idle_stop_and_nothing_else() {
        let disco = DiscoPrivateKey::random().public_key();
        let node_key = NodePrivateKey::random().public_key();
        let with_peer = db_with(node_with_keys(disco, node_key, "n1"));
        let idle = DatapathActivity::idle_for(SESSION_ACTIVE_TIMEOUT + Duration::from_secs(1));

        let forced = AtomicBool::new(true);
        assert!(
            should_do_periodic_restun(&with_peer, &idle, &forced),
            "debug-always-stun must keep the sweep running on an idle datapath"
        );

        // Same attribute, no peers: still quiet. The override must not resurrect the peer-count arm.
        let no_peers: Arc<RwLock<Option<Arc<PeerDb>>>> = Default::default();
        assert!(
            !should_do_periodic_restun(&no_peers, &idle, &forced),
            "debug-always-stun must not make a peerless node STUN"
        );
    }

    /// The attribute reaches the gate the way control sends it: as a key on the **self** node's cap
    /// map. This pins the wire key (`debug-always-stun`) end-to-end through the accessor the direct
    /// manager reads, so a typo in the literal can't silently disable control's only override.
    #[test]
    fn the_override_is_read_off_the_self_nodes_cap_map() {
        let mut self_node = node_with_keys(
            DiscoPrivateKey::random().public_key(),
            NodePrivateKey::random().public_key(),
            "self",
        );
        assert!(
            !self_node.force_background_stun(),
            "a self node without the attribute leaves the idle stop in force"
        );
        self_node
            .cap_map
            .insert("debug-always-stun".to_string(), vec![]);
        assert!(
            self_node.force_background_stun(),
            "the debug-always-stun cap-map key is what turns the override on"
        );
    }

    /// Traffic resuming re-opens the gate immediately, with no netmap change and no waiting for
    /// control — the property that keeps the idle stop from costing connectivity. The reset goes
    /// through the production seam ([`OverlayToDataplane::send`], the one call every datapath send
    /// from the netstack, the TUN pump and the forwarder makes), not through a test-only poke.
    #[test]
    fn traffic_resuming_restarts_the_sweep_without_a_netmap_change() {
        let disco = DiscoPrivateKey::random().public_key();
        let node_key = NodePrivateKey::random().public_key();
        let with_peer = db_with(node_with_keys(disco, node_key, "n1"));
        let no_override = AtomicBool::new(false);

        let activity = DatapathActivity::idle_for(SESSION_ACTIVE_TIMEOUT + Duration::from_secs(1));
        assert!(
            !should_do_periodic_restun(&with_peer, &activity, &no_override),
            "precondition: the idle datapath has stopped the sweep"
        );

        // One packet out of the datapath, through the real overlay->dataplane send. `_down` is held
        // so the channel stays open and the send actually succeeds.
        let (up, _down) = crate::dataplane::OverlayToDataplane::for_test(activity.clone());
        up.send(vec![ts_packet::PacketMut::from(vec![0u8; 20])])
            .expect("the dataplane receiver is still alive");

        assert!(
            should_do_periodic_restun(&with_peer, &activity, &no_override),
            "the sweep must resume on the next tick after traffic returns, with the same netmap"
        );
    }

    /// The periodic STUN delay is a uniform random value in `[20s, 26s)`, matching Go magicsock's
    /// `RandomDurationBetween(20s, 26s)` re-arm — never a fixed 30s beat, and always strictly under
    /// the ~30s UDP-NAT-timeout ceiling. Sampling many draws pins both the bounds and that the value
    /// actually varies (jitter), so a regression to a constant interval is caught.
    #[test]
    fn stun_probe_delay_is_jittered_within_go_bounds() {
        let mut seen = std::collections::HashSet::new();
        for _ in 0..1000 {
            let d = stun_probe_delay();
            assert!(
                d >= STUN_PROBE_INTERVAL_MIN && d < STUN_PROBE_INTERVAL_MAX,
                "delay {d:?} out of [20s, 26s)"
            );
            assert!(
                d < Duration::from_secs(30),
                "delay {d:?} must stay under the 30s UDP-NAT-timeout ceiling"
            );
            seen.insert(d);
        }
        // 1000 draws across a 6s (≈6e9 ns) range must yield many distinct values — a fixed-interval
        // regression would collapse this to 1.
        assert!(
            seen.len() > 100,
            "expected jittered delays, got only {} distinct value(s)",
            seen.len()
        );
    }

    /// Build a peer db from nodes.
    fn db_of(nodes: impl IntoIterator<Item = Node>) -> PeerDb {
        let mut db = PeerDb::default();
        for node in nodes {
            db.upsert(&node);
        }
        db
    }

    /// The signal the disco-path invalidation hangs off: a peer that kept its node key but is now
    /// published under a different disco key has rotated, and its trusted direct path is no longer
    /// backed by anything the peer signs today.
    #[test]
    fn disco_key_rotation_is_detected_across_snapshots() {
        let node_key = NodePrivateKey::random().public_key();
        let old = DiscoPrivateKey::random().public_key();
        let new = DiscoPrivateKey::random().public_key();

        let before = db_of([node_with_keys(old, node_key, "n1")]);
        let after = db_of([node_with_keys(new, node_key, "n1")]);

        assert_eq!(
            disco_key_rotations(Some(&before), &after),
            vec![DiscoKeyRotation {
                node_key,
                previous: old,
                current: new,
            }],
        );

        // Republishing the same snapshot is not a rotation — the reconcile below it runs on every
        // peer state update, so a false positive would drop a healthy path's trust every time.
        assert!(disco_key_rotations(Some(&after), &after).is_empty());
    }

    /// The three non-rotations, each of which would cost a working path if it were treated as one:
    /// a peer that has no previous snapshot, one acquiring its first disco key, and one that rotated
    /// its NODE key (a fresh endpoint upstream, with no path state to carry across).
    #[test]
    fn disco_key_rotations_ignores_non_rotations() {
        let node_key = NodePrivateKey::random().public_key();
        let disco = DiscoPrivateKey::random().public_key();
        let with_key = node_with_keys(disco, node_key, "n1");
        let without_key = Node {
            disco_key: None,
            ..with_key.clone()
        };

        assert!(
            disco_key_rotations(None, &db_of([with_key.clone()])).is_empty(),
            "the first snapshot has nothing to diff against"
        );
        assert!(
            disco_key_rotations(
                Some(&db_of([without_key.clone()])),
                &db_of([with_key.clone()])
            )
            .is_empty(),
            "acquiring a first disco key is not a rotation"
        );
        assert!(
            disco_key_rotations(Some(&db_of([with_key.clone()])), &db_of([without_key])).is_empty(),
            "losing the disco key leaves nothing to carry over"
        );

        let rekeyed = Node {
            node_key: NodePrivateKey::random().public_key(),
            disco_key: Some(DiscoPrivateKey::random().public_key()),
            ..with_key.clone()
        };
        assert!(
            disco_key_rotations(Some(&db_of([with_key])), &db_of([rekeyed])).is_empty(),
            "a node-key rotation is a new endpoint, not a disco-key change on the old one"
        );
    }

    /// Only the peer that rotated is reported: an unrelated peer's confirmed path must not lose its
    /// trust because someone else changed keys.
    #[test]
    fn disco_key_rotations_reports_only_the_peer_that_rotated() {
        let rotator = NodePrivateKey::random().public_key();
        let steady = NodePrivateKey::random().public_key();
        let old = DiscoPrivateKey::random().public_key();
        let new = DiscoPrivateKey::random().public_key();
        let steady_disco = DiscoPrivateKey::random().public_key();

        let before = db_of([
            node_with_keys(old, rotator, "n1"),
            node_with_keys(steady_disco, steady, "n2"),
        ]);
        let after = db_of([
            node_with_keys(new, rotator, "n1"),
            node_with_keys(steady_disco, steady, "n2"),
        ]);

        assert_eq!(
            disco_key_rotations(Some(&before), &after),
            vec![DiscoKeyRotation {
                node_key: rotator,
                previous: old,
                current: new,
            }],
        );
    }

    /// A rotated peer is re-probed the moment its path is invalidated, not on the next pinger tick.
    ///
    /// `PeerPaths::invalidate_disco_path` keeps the best address but drops its trust, so the peer
    /// relays over DERP until a fresh pong lands. Upstream covers that window by dual-sending to the
    /// retained address and DERP (`addrForSendLocked`); this tree routes a peer through one underlay
    /// transport at a time and cannot, so the window has to be short instead — which it only is if
    /// the pings go out on the rotation rather than up to a `PING_INTERVAL` later.
    ///
    /// The assertion is the count of datagrams that actually left the socket, one per candidate the
    /// rotation carried onto the new key. The candidates are control-advertised (the netmap seam
    /// takes an address as given); a peer-learned loopback address would be dropped by the
    /// `is_pingable_candidate` sanitizer, which is not what this test is about.
    #[tokio::test]
    async fn a_rotated_peer_is_reprobed_immediately() {
        let sock = MagicSock::bind(
            "127.0.0.1:0".parse().unwrap(),
            DiscoPrivateKey::random(),
            NodePrivateKey::random().public_key(),
        )
        .await
        .expect("the test underlay socket must bind");

        // Two candidates on loopback so the pings have somewhere real to go.
        let sink = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
        let advertised = sink.local_addr().unwrap();
        let second = SocketAddr::new(advertised.ip(), advertised.port().wrapping_add(1).max(1));

        let old = DiscoPrivateKey::random().public_key();
        let new = DiscoPrivateKey::random().public_key();
        sock.set_netmap_endpoints(old, [advertised, second]);

        assert!(
            sock.changed_active_disco(&old, &new),
            "precondition: the rotation carried the peer's path state onto the new key"
        );

        let pinged = reprobe_rotated_peers(&sock, &[new]).await;
        assert_eq!(
            pinged, 2,
            "every candidate the rotation carried over is re-probed straight away, so the peer \
             re-confirms a direct path in one round trip instead of waiting out a pinger tick"
        );
    }

    /// The empty and unknown cases are quiet no-ops: nothing to re-probe sends nothing, and a key
    /// with no path state behind it (the peer left the netmap between the rotation and the sweep)
    /// is not an error.
    #[tokio::test]
    async fn reprobing_nothing_sends_nothing() {
        let sock = MagicSock::bind(
            "127.0.0.1:0".parse().unwrap(),
            DiscoPrivateKey::random(),
            NodePrivateKey::random().public_key(),
        )
        .await
        .expect("the test underlay socket must bind");

        assert_eq!(reprobe_rotated_peers(&sock, &[]).await, 0);
        assert_eq!(
            reprobe_rotated_peers(&sock, &[DiscoPrivateKey::random().public_key()]).await,
            0,
            "a peer with no path state is skipped rather than failing the sweep"
        );
    }
}