mxc-sdk 1.2.0

Importable library for starting MXC sandboxes in-process, with streaming stdio.
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
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! Private networking for Bubblewrap.

use std::cell::Cell;
use std::fs::{self, File};
use std::io::{ErrorKind, Read, Seek, SeekFrom, Write};
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, ToSocketAddrs};
use std::os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd};
use std::os::unix::process::CommandExt;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, ExitStatus, Stdio};
use std::sync::{mpsc, Condvar, Mutex, PoisonError};
use std::thread;
use std::time::{Duration, Instant};

use crate::mxc_common::filesystem_resolve::{resolve_mount_order, FsIntent};
use crate::mxc_common::filesystem_symlink::resolve_through_symlinks;
use crate::mxc_common::logger::Logger;
use crate::mxc_common::models::{ContainerPolicy, ProxyAddress, ProxyHostPin};
use crate::mxc_common::sandbox_process::group_kill;
use crate::mxc_common::termination_signals;
use nix::errno::Errno;
use nix::fcntl::{fcntl, FcntlArg, FdFlag, OFlag};
use nix::sys::socket::{socket, AddressFamily, SockFlag, SockType};
use nix::sys::wait::{waitid, Id, WaitPidFlag, WaitStatus};
use nix::unistd::{access, dup2, pipe2, AccessFlags, Pid};
use tempfile::TempDir;

use crate::bwrap_common::bwrap_command::{path_is_denied, PolicyMount, COMMAND_TAIL};
use crate::bwrap_common::host_tools::{self, LookupError};
use crate::bwrap_common::identity::{read_as_workload, RootIdentity};
use crate::bwrap_common::network_rules::{
    payload_file_name, render_filter_payloads, EgressPlan, IngressPlan, RuleFamily,
};
use crate::bwrap_common::probe_exec;
use crate::bwrap_common::resolver_file::{resolver_target_is_denied, sandbox_mount_path};

pub(crate) const STARTUP_TIMEOUT: Duration = Duration::from_secs(5);
/// How long a single `iptables` call may block on the host's `/run/xtables.lock`.
///
/// Only the legacy backend takes that lock, and `nsenter --net` leaves the mount
/// namespace alone, so there it is shared with every other sandbox. Waiting is
/// what makes concurrent provisioning work; the ceiling keeps a wedged lock from
/// hanging startup. `nf_tables` takes no lock and ignores the wait.
const XTABLES_LOCK_WAIT: Duration = Duration::from_secs(5);
/// Lock file the legacy `iptables` backend opens before touching any table.
/// `nf_tables` does not use it. See [`iptables_backend_is_usable`].
const XTABLES_LOCK_PATH: &str = "/run/xtables.lock";
/// Budget for the phase that starts slirp and installs the rules.
///
/// The worst-case lock wait for every transaction plus explicit headroom,
/// because the timer starts in [`ProxyNetworkNamespace::attach`] *before* slirp
/// signals readiness and so also covers Bubblewrap loopback setup and slirp
/// startup. A single [`STARTUP_TIMEOUT`] cannot cover this: it would reject a
/// viable sandbox the moment one call waited on a busy host.
///
/// A large policy needs more than one transaction per family, so this scales
/// with the rendered payload count -- but only up to [`RULE_INSTALL_CEILING`].
/// Scaling without a ceiling is what made the previous per-rule budget
/// unusable: a large rule set could push startup past any sane bound. The
/// ceiling keeps a wedged host bounded, and it is generous enough that a
/// policy reaching it is contending for the lock rather than merely large.
///
/// Also clamped to the caller's `script_timeout` when there is one, so setup
/// cannot silently outlast the deadline the request asked for -- it is spent
/// before the child's own timeout exists. The clamp stops at
/// [`RULE_INSTALL_FLOOR`]: setup has an irreducible cost, so a shorter workload
/// timeout bounds the workload, not the sandbox that has to exist to run it.
fn rule_install_timeout(transactions: usize, script_timeout_ms: u32) -> Duration {
    let waits = XTABLES_LOCK_WAIT
        .checked_mul(u32::try_from(transactions).unwrap_or(u32::MAX))
        .unwrap_or(RULE_INSTALL_CEILING);
    let budget = waits
        .saturating_add(RULE_INSTALL_HEADROOM)
        .min(RULE_INSTALL_CEILING);

    if script_timeout_ms == 0 {
        return budget;
    }
    budget
        .min(Duration::from_millis(u64::from(script_timeout_ms)))
        .max(RULE_INSTALL_FLOOR)
}
/// Slack for slirp startup and process spawn inside [`rule_install_timeout`].
const RULE_INSTALL_HEADROOM: Duration = Duration::from_secs(20);
/// Upper bound on [`rule_install_timeout`], however large the policy is.
const RULE_INSTALL_CEILING: Duration = Duration::from_secs(120);
/// Floor the caller-deadline clamp will not go below: slirp startup plus one
/// contended transaction.
const RULE_INSTALL_FLOOR: Duration =
    Duration::from_secs(STARTUP_TIMEOUT.as_secs() + XTABLES_LOCK_WAIT.as_secs());
const SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(2);
/// Ceiling for a single dependency probe. Generous next to a `--version` call,
/// which returns in milliseconds, so only a genuinely wedged binary trips it.
const PROBE_TIMEOUT: Duration = Duration::from_secs(5);
/// Total budget for the advisory pre-flight probe surface.
///
/// The launch path can afford [`PROBE_TIMEOUT`] on each of nine dependencies
/// in turn; [`probe_proxy_enforcement`] cannot, because it runs behind a
/// caller-owned timeout and is fail-closed, so being killed from outside would
/// report the host as *unsupported*.
const PRE_FLIGHT_BUDGET: Duration = Duration::from_secs(3);
const SLIRP_HOST_GATEWAY: &str = "10.0.2.2";
/// The gateway as an address, for rules and pins. Kept in step with
/// [`SLIRP_HOST_GATEWAY`] by [`tests::gateway_constants_agree`].
///
/// `pub(crate)` because the egress renderer needs it too: slirp maps this
/// address onto the host's own loopback, which makes it the single address
/// `ingress.hostLoopback` has to govern.
pub(crate) const SLIRP_HOST_GATEWAY_IP: Ipv4Addr = Ipv4Addr::new(10, 0, 2, 2);
/// The network slirp gives the sandbox, for diagnostics.
const SLIRP_NETWORK: &str = "10.0.2.0/24";
/// Path the hosts-file pin is mounted over inside the sandbox.
const SANDBOX_HOSTS_PATH: &str = "/etc/hosts";
/// Resolver file the sandbox reads, and the start of the resolver pin's
/// symlink walk.
const SANDBOX_RESOLV_CONF_PATH: &str = "/etc/resolv.conf";
/// slirp's built-in DNS forwarder.
///
/// libslirp rewrites a query addressed here to the first IPv4 nameserver in the
/// *host's* `/etc/resolv.conf` and sends it from the host's network namespace,
/// which is what puts a host loopback resolver back in reach of the sandbox.
const SLIRP_DNS_FORWARDER: &str = "10.0.2.3";
/// The forwarder as an address, for the egress check that has to decide whether
/// the chain admits it. Kept in step with [`SLIRP_DNS_FORWARDER`] by
/// [`tests::forwarder_constants_agree`].
pub(crate) const SLIRP_DNS_FORWARDER_IP: Ipv4Addr = Ipv4Addr::new(10, 0, 2, 3);
/// Egress chain installed inside the sandbox's own network namespace.
const EGRESS_CHAIN: &str = "MXC_EGRESS";
/// Chain carrying the inbound posture, hooked into `INPUT`.
const INGRESS_CHAIN: &str = "MXC_INGRESS";
/// Descriptor numbers the supervisor script hardcodes. They must stay single
/// digit and below [`FD_STAGING_BASE`]: dash cannot name a descriptor >= 10 in
/// a redirection, which is the whole reason the parent pins them.
const SUPERVISOR_PID_FD: RawFd = 3;
const SUPERVISOR_EXIT_FD: RawFd = 4;
/// Held open by the supervisor and inherited by slirp, never written to.
///
/// The parent keeps only the read end, so it reaches EOF exactly when both
/// have exited -- an orphaned slirp still carries the sandbox's route, and
/// holding the descriptor is what keeps that case from reading as a loss.
const SUPERVISOR_LIVENESS_FD: RawFd = 5;
/// Descriptors are staged above every target before being landed, so a source
/// already sitting on a target cannot be clobbered mid-remap.
const FD_STAGING_BASE: RawFd = 10;

// The network is marked ready only after every rule has been installed.
const SUPERVISOR_SCRIPT: &str = r#"
set -eu
state_dir="$1"
lock_wait="$2"

# Use the absolute tool paths checked by the parent.
nsenter="$3"
ip="$4"
slirp4netns="$5"
iptables_restore="$6"
ip6tables_restore="$7"
sleep="$8"
unshare="$9"
slirp_sandbox="${10}"

# Dash redirections need fixed single-digit descriptors.
# 3 carries the sandbox PID and reaches EOF if the parent exits before sending it.
# 4 controls slirp's lifetime.
printf ready > "$state_dir/userns.ready"
if ! IFS= read -r child_pid <&3; then
    child_pid="${child_pid:-}"
fi
exec 3<&-
if [ -z "$child_pid" ]; then
    echo "mxc: parent exited before publishing the sandbox PID" >&2
    exit 1
fi

# Wait for Bubblewrap's loopback setup before slirp creates the same address.
ns="/proc/$child_pid/ns/net"
while :; do
    loopback=$("$nsenter" --net="$ns" -- "$ip" -4 -o address show dev lo up) || {
        echo "mxc: failed to query Bubblewrap loopback readiness" >&2
        exit 1
    }
    case "$loopback" in
        *" inet 127.0.0.1/8 "*) break ;;
    esac
    "$sleep" 0.01
done

# Slirp readiness alone must not release the workload.
exec 9> "$state_dir/slirp.internal"

# A root supervisor keeps host privileges, so slirp sheds them before it handles packets.
# Slirp's sandbox detaches its old root, so a private mount namespace keeps host mounts in place.
if [ "$slirp_sandbox" = yes ]; then
    set -- "$unshare" --mount --propagation private -- \
        "$slirp4netns" --enable-sandbox --enable-seccomp
else
    set -- "$slirp4netns"
fi
"$@" --configure --mtu=65520 \
    --ready-fd 9 --exit-fd 4 \
    "$child_pid" tap0 &
slirp_pid=$!
trap 'kill "$slirp_pid" 2>/dev/null || true' TERM INT
while [ ! -s "$state_dir/slirp.internal" ]; do
    if ! kill -0 "$slirp_pid" 2>/dev/null; then
        echo "slirp4netns exited before signalling readiness" >&2
        exit 1
    fi
    "$sleep" 0.01
done

conntrack_hint="mxc: could not install the sandbox network policy. If the error above says \
'Invalid argument', this host is missing the nf_conntrack kernel module that the inbound \
connection-state match requires, and an unprivileged sandbox cannot load it."

# One restore is one bounded kernel transaction, so large rule sets arrive in several.
# The final transaction installs the hooks after the earlier rules exist.
for payload in "$state_dir"/rules.v4.*; do

    # -w waits for the host's legacy xtables lock, which concurrent sandboxes share
    # because nsenter keeps the host's mount namespace. -n preserves earlier transactions.
    "$nsenter" --net="$ns" -- "$iptables_restore" -w "$lock_wait" -n "$payload" || { echo "$conntrack_hint" >&2; exit 1; }
done

# A kernel without IPv6 has no IPv6 payloads.
for payload in "$state_dir"/rules.v6.*; do
    [ -e "$payload" ] || continue
    "$nsenter" --net="$ns" -- "$ip6tables_restore" -w "$lock_wait" -n "$payload" || { echo "$conntrack_hint" >&2; exit 1; }
done

printf ready > "$state_dir/slirp.ready"
wait "$slirp_pid"
"#;

/// The single destination a proxy-only sandbox may reach.
///
/// The address is IPv4 because the rule is emitted with IPv4 `iptables`. A
/// hostname endpoint is resolved on the host and carried here as its address
/// plus the [`ProxyHostPin`] the sandbox needs to agree with it: DNS is closed
/// inside the sandbox, so a hosts-file pin is the only way the workload can
/// reach a name the firewall has authorized.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ProxyEgress {
    ip: Ipv4Addr,
    port: u16,
    pin: Option<ProxyHostPin>,
}

impl ProxyEgress {
    /// The hosts-file pin the sandbox needs, if the endpoint is a hostname.
    pub(crate) fn pin(&self) -> Option<&ProxyHostPin> {
        self.pin.as_ref()
    }

    /// The filtering posture that opens this endpoint and nothing else.
    pub(crate) fn plan(&self) -> EgressPlan {
        EgressPlan::for_proxy(self.ip, self.port)
    }
}

/// The proxy as the sandbox sees it: the URL handed to the workload, and the
/// single endpoint the egress chain opens for it.
///
/// Both come from one host-side lookup. Resolving twice can disagree -- DNS
/// round-robin reorders, or a TTL expires between the calls -- and a sandbox
/// pinned to an address the chain did not authorize cannot reach its proxy at
/// all.
#[derive(Debug)]
pub(crate) struct SandboxProxy {
    address: ProxyAddress,
    egress: ProxyEgress,
}

/// Why [`SandboxProxy::resolve`] failed.
#[derive(Debug)]
pub(crate) enum ProxyResolveError {
    /// The endpoint, or the address it resolves to, cannot be enforced.
    Rejected(String),
    /// The host lookup itself did not produce an answer.
    Lookup(String),
}

impl ProxyResolveError {
    pub(crate) fn message(&self) -> &str {
        match self {
            Self::Rejected(message) | Self::Lookup(message) => message,
        }
    }
}

impl std::fmt::Display for ProxyResolveError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.message())
    }
}

impl From<String> for ProxyResolveError {
    fn from(message: String) -> Self {
        Self::Rejected(message)
    }
}

impl SandboxProxy {
    /// Derive the sandbox-visible proxy from the configured one.
    ///
    /// A hostname keeps its URL and is pinned, rather than being rewritten to
    /// an address: the workload then presents the `Host` header and proxy-auth
    /// realm the operator configured. An IP literal has no name to pin, so a
    /// loopback literal is rewritten to slirp's gateway instead.
    pub(crate) fn resolve(configured: &ProxyAddress) -> Result<Self, ProxyResolveError> {
        Self::resolve_with(configured, resolve_ipv4)
    }

    /// Apply every rejection [`Self::resolve`] can reach without a lookup.
    ///
    /// A hostname's verdict depends on what it resolves to, and that answer is
    /// also the pin the sandbox is given -- so it has to come from the single
    /// lookup `run` performs, not from a second one here. Deferring is detected
    /// rather than predicted: the injected resolver records that it was asked.
    pub(crate) fn check_without_resolving(configured: &ProxyAddress) -> Result<(), String> {
        let (needs_lookup, checked) = Self::inspect_without_resolving(configured);
        if needs_lookup {
            return Ok(());
        }
        checked.map_err(|error| error.message().to_string())
    }

    /// Run the static checks, reporting whether a lookup would have followed.
    ///
    /// A lookup is needed exactly when the endpoint is a hostname, which is
    /// also exactly when a hosts pin is created -- an IP literal resolves to
    /// `Ok(None)` from [`ProxyAddress::host_pin`]. Callers use the flag to
    /// reason about the pin without duplicating that classification.
    fn inspect_without_resolving(
        configured: &ProxyAddress,
    ) -> (bool, Result<(), ProxyResolveError>) {
        let asked_to_resolve = Cell::new(false);
        let checked = Self::resolve_with(configured, |_, _| {
            asked_to_resolve.set(true);
            Err(ProxyResolveError::Lookup(String::new()))
        });

        (asked_to_resolve.get(), checked.map(|_| ()))
    }

    /// [`Self::resolve`] against an injected resolver.
    ///
    /// Resolution is the one step that depends on the host's DNS, so it is a
    /// parameter: the decisions layered on top of it are then testable without
    /// a lookup whose answer the test does not control.
    fn resolve_with(
        configured: &ProxyAddress,
        resolve: impl Fn(&str, u16) -> Result<Ipv4Addr, ProxyResolveError>,
    ) -> Result<Self, ProxyResolveError> {
        if configured.port() == 0 {
            return Err(
                "Bubblewrap: proxy-only egress requires a non-zero proxy port"
                    .to_string()
                    .into(),
            );
        }
        let host = configured.host().trim_matches(['[', ']']);

        // `localhost` is reserved to loopback (RFC 6761), so it is rewritten
        // rather than pinned. A pin is a sandbox-wide mapping: pointing this
        // name at the gateway would redirect the workload's own loopback
        // traffic to the host.
        let is_reserved_loopback_name = host.eq_ignore_ascii_case("localhost");

        if let Ok(ip) = host.parse::<Ipv4Addr>() {
            // A literal cannot be pinned, so loopback and the wildcard are
            // reached by rewriting the URL to the address slirp maps back to
            // the host. `0.0.0.0` names the host just as `127.0.0.1` does.
            return if ip.is_loopback() || ip.is_unspecified() {
                Ok(Self::rewritten(configured)?)
            } else {
                reject_slirp_reserved(ip, host)?;
                Ok(Self {
                    address: configured.clone(),
                    egress: ProxyEgress {
                        ip,
                        port: configured.port(),
                        pin: None,
                    },
                })
            };
        }

        if let Ok(ip) = host.parse::<Ipv6Addr>() {
            // A dual-stack wildcard listener accepts the gateway's IPv4
            // connection, so `::` can be rewritten. `::1` cannot: it listens
            // on the IPv6 loopback only, so the rewrite would hand the sandbox
            // an address nothing answers on -- failing at connect time rather
            // than at policy time.
            if ip.is_unspecified() {
                return Ok(Self::rewritten(configured)?);
            }
            if ip.is_loopback() {
                return Err(format!(
                    "Bubblewrap: proxy address '{}' uses the IPv6 loopback, which the private \
                     network namespace cannot reach; bind the proxy to 127.0.0.1 or a dual-stack \
                     wildcard address instead. The egress rule is emitted with IPv4 iptables.",
                    configured.host()
                )
                .into());
            }
            return Err(ipv6_unsupported(host).into());
        }

        if is_reserved_loopback_name {
            return Ok(Self::rewritten(configured)?);
        }

        let resolved = resolve(host, configured.port())?;
        reject_slirp_reserved(resolved, host)?;
        let ip = sandbox_facing_ip(resolved);
        let pin = configured
            .host_pin(IpAddr::V4(ip))
            .map_err(|error| format!("Bubblewrap: {error}"))?;

        Ok(Self {
            address: configured.clone(),
            egress: ProxyEgress {
                ip,
                port: configured.port(),
                pin,
            },
        })
    }

    /// The proxy reached by rewriting its URL to slirp's gateway.
    fn rewritten(configured: &ProxyAddress) -> Result<Self, String> {
        Ok(Self {
            address: rewrite_to_gateway(configured)?,
            egress: ProxyEgress {
                ip: SLIRP_HOST_GATEWAY_IP,
                port: configured.port(),
                pin: None,
            },
        })
    }

    /// The proxy URL the workload is given.
    pub(crate) fn address(&self) -> &ProxyAddress {
        &self.address
    }

    /// The endpoint the egress chain opens.
    pub(crate) fn egress(&self) -> &ProxyEgress {
        &self.egress
    }
}

/// The address the sandbox reaches a host-resolved endpoint at.
///
/// slirp gives the sandbox its own loopback, so a name that resolves to the
/// host's loopback is pinned to the gateway instead: pinning it verbatim would
/// aim the workload at itself. `0.0.0.0` is an answer `/etc/hosts` can produce
/// and names the host the same way, so it is translated alongside loopback --
/// matching the IP-literal path, which rewrites both.
fn sandbox_facing_ip(resolved: Ipv4Addr) -> Ipv4Addr {
    if resolved.is_loopback() || resolved.is_unspecified() {
        SLIRP_HOST_GATEWAY_IP
    } else {
        resolved
    }
}

/// Reject an endpoint the host resolved into the sandbox's own slirp network.
///
/// Every address in [`SLIRP_NETWORK`] is on-link inside the namespace, so it
/// does not name the machine the host meant: [`SLIRP_HOST_GATEWAY`] is the
/// route to host loopback, `.100` is the sandbox itself, and the rest have no
/// neighbour at all. Opening the gateway is the sharp case -- the egress rule
/// would grant the workload an unrelated host-loopback service on the proxy
/// port. Applied to what the host answered, so the deliberate loopback and
/// wildcard translations in [`sandbox_facing_ip`] still reach the gateway.
fn reject_slirp_reserved(resolved: Ipv4Addr, host: &str) -> Result<(), String> {
    if !SLIRP_NETWORK_OCTETS.eq(&resolved.octets()[..3]) {
        return Ok(());
    }
    Err(format!(
        "Bubblewrap: proxy endpoint '{host}' is {resolved}, which is inside the sandbox's own \
         network ({SLIRP_NETWORK}); there that address is slirp's own, not the host's \
         {resolved}, so the egress rule would open an unrelated service. Bind the proxy to \
         127.0.0.1 -- which is translated to the gateway deliberately -- or give it an address \
         outside {SLIRP_NETWORK}."
    ))
}

/// Leading octets of [`SLIRP_NETWORK`], asserted against it by
/// [`tests::gateway_constants_agree`].
const SLIRP_NETWORK_OCTETS: [u8; 3] = [10, 0, 2];

/// Bound on the host lookup performed by [`resolve_ipv4`].
///
/// Sized so a resolver whose first nameserver is dead still answers: glibc
/// defaults to a 5s timeout with 2 attempts per server, so a single failed
/// server costs ~10s before the next is tried. A black-holed resolver would
/// otherwise run to ~30s or more across three servers.
const RESOLVE_TIMEOUT: Duration = Duration::from_secs(15);

/// Thread name for the lookup [`resolve_ipv4`] bounds.
const RESOLVE_TIMEOUT_LABEL: &str = "mxc-proxy-resolve";

/// Run `work` on its own thread and wait at most `timeout` for its answer.
///
/// Used for calls that cannot be cancelled: on expiry the thread is abandoned
/// and its result discarded, which bounds the caller's wait even though the
/// work itself runs to completion. `label` names the thread for diagnostics.
fn with_deadline<T: Send + 'static>(
    label: &str,
    timeout: Duration,
    work: impl FnOnce() -> T + Send + 'static,
) -> Result<Result<T, mpsc::RecvTimeoutError>, std::io::Error> {
    let (sender, receiver) = mpsc::channel();
    thread::Builder::new()
        .name(label.to_string())
        .spawn(move || {
            // Abandoned on expiry: the receiver is gone, so this send fails
            // and the answer is discarded rather than blocking the thread.
            let _ = sender.send(work());
        })?;

    Ok(receiver.recv_timeout(timeout))
}

/// Resolve `host` to the address the egress chain will open, without waiting
/// on the resolver indefinitely.
///
/// This runs during setup, before the sandbox starts, so it is outside the
/// script timeout: an unbounded lookup would stall a run that never began.
/// `getaddrinfo` cannot be cancelled, so the lookup is moved to a thread and
/// abandoned once the bound expires -- the wait is bounded even though the
/// query itself keeps running until the resolver gives up.
fn resolve_ipv4(host: &str, port: u16) -> Result<Ipv4Addr, ProxyResolveError> {
    let query = host.to_string();
    let waited = with_deadline(RESOLVE_TIMEOUT_LABEL, RESOLVE_TIMEOUT, move || {
        lookup_ipv4(&query, port)
    })
    .map_err(|error| {
        ProxyResolveError::Lookup(format!(
            "Bubblewrap: could not start the lookup of proxy host '{host}': {error}"
        ))
    })?;

    match waited {
        Ok(resolved) => resolved,
        Err(mpsc::RecvTimeoutError::Timeout) => Err(ProxyResolveError::Lookup(format!(
            "Bubblewrap: resolving proxy host '{host}' exceeded {}s. The proxy endpoint is \
             resolved on the host because DNS is closed inside the sandbox, so an unresponsive \
             host resolver blocks the sandbox from starting. Check the host's DNS configuration, \
             or give the proxy as an IPv4 address to skip resolution.",
            RESOLVE_TIMEOUT.as_secs()
        ))),
        Err(mpsc::RecvTimeoutError::Disconnected) => Err(ProxyResolveError::Lookup(format!(
            "Bubblewrap: the lookup of proxy host '{host}' ended without an answer."
        ))),
    }
}

/// The blocking lookup behind [`resolve_ipv4`].
///
/// Only the first IPv4 answer is used, and it is the same one the sandbox is
/// pinned to. Opening the rest would widen the chain to addresses the sandbox
/// can no longer select: with DNS closed, the pin is its only resolution path.
fn lookup_ipv4(host: &str, port: u16) -> Result<Ipv4Addr, ProxyResolveError> {
    let resolved: Vec<IpAddr> = (host, port)
        .to_socket_addrs()
        .map_err(|error| {
            ProxyResolveError::Lookup(format!(
                "Bubblewrap: could not resolve proxy host '{host}': {error}. The proxy endpoint \
                 is resolved on the host because DNS is closed inside the sandbox."
            ))
        })?
        .map(|addr| addr.ip())
        .collect();

    if let Some(IpAddr::V4(ip)) = resolved.iter().find(|ip| ip.is_ipv4()) {
        return Ok(*ip);
    }

    // A name with AAAA records and no A records is the same unenforceable case
    // as an IPv6 literal, so say so rather than claiming it does not resolve.
    if resolved.is_empty() {
        Err(ProxyResolveError::Lookup(format!(
            "Bubblewrap: proxy host '{host}' did not resolve to any address."
        )))
    } else {
        Err(ipv6_unsupported(host).into())
    }
}

/// The error for an endpoint that only IPv6 can reach.
fn ipv6_unsupported(host: &str) -> String {
    format!(
        "Bubblewrap: proxy-only egress requires an IPv4 proxy endpoint, but '{host}' is reachable \
         over IPv6 only. The egress rule is emitted with IPv4 iptables, so an IPv6 endpoint would \
         be silently dropped. Use an IPv4 proxy address."
    )
}

/// Runtime file descriptors Bubblewrap needs while establishing its child.
pub(crate) struct BwrapStartup {
    info_reader: File,
    info_writer: Option<OwnedFd>,
    gate_reader: Option<OwnedFd>,
    gate_writer: Option<OwnedFd>,
    /// Descriptors bwrap must inherit, cleared of `FD_CLOEXEC` in the child
    /// only. See [`inherit_descriptors`].
    inheritable: Vec<RawFd>,
    _pins: Vec<File>,
}

impl BwrapStartup {
    pub(crate) fn configure(args: &mut Vec<String>) -> Result<Self, String> {
        let (info_reader, info_writer) = pipe_above_stdio()?;
        let (gate_reader, gate_writer) = pipe_above_stdio()?;
        args.splice(
            0..0,
            [
                "--info-fd".to_string(),
                info_writer.as_raw_fd().to_string(),
                "--block-fd".to_string(),
                gate_reader.as_raw_fd().to_string(),
            ],
        );

        Ok(Self {
            inheritable: vec![info_writer.as_raw_fd(), gate_reader.as_raw_fd()],
            info_reader: File::from(info_reader),
            info_writer: Some(info_writer),
            gate_reader: Some(gate_reader),
            gate_writer: Some(gate_writer),
            _pins: Vec::new(),
        })
    }

    /// Arrange for bwrap -- and only bwrap -- to inherit the startup
    /// descriptors.
    pub(crate) fn prepare_command(&self, command: &mut Command) {
        inherit_descriptors(command, self.inheritable.clone());
    }

    /// Close the parent copies of the descriptors inherited by Bubblewrap.
    pub(crate) fn child_spawned(&mut self) {
        self.info_writer.take();
        self.gate_reader.take();
    }

    /// Wait for Bubblewrap to report the host-visible PID of its sandbox child.
    pub(crate) fn child_pid(&mut self, child: &Child) -> Result<u32, String> {
        set_nonblocking(self.info_reader.as_raw_fd())?;
        let deadline = Instant::now() + STARTUP_TIMEOUT;
        let mut json = Vec::new();
        let mut chunk = [0_u8; 512];

        loop {
            match self.info_reader.read(&mut chunk) {
                Ok(0) => {}
                Ok(count) => json.extend_from_slice(&chunk[..count]),
                Err(error) if error.kind() == ErrorKind::WouldBlock => {}
                Err(error) => {
                    return Err(format!(
                        "Bubblewrap: failed to read bwrap child information: {error}"
                    ));
                }
            }

            if let Ok(value) = serde_json::from_slice::<serde_json::Value>(&json) {
                if let Some(pid) = value.get("child-pid").and_then(|pid| pid.as_u64()) {
                    return u32::try_from(pid).map_err(|_| {
                        format!("Bubblewrap: bwrap reported an out-of-range child PID: {pid}")
                    });
                }
                return Err(format!(
                    "Bubblewrap: bwrap child information omitted 'child-pid': {value}"
                ));
            }

            if has_exited_unreaped(child.id())
                .map_err(|error| format!("Bubblewrap: failed to inspect bwrap startup: {error}"))?
            {
                return Err("Bubblewrap: bwrap exited before publishing child information".into());
            }
            if Instant::now() >= deadline {
                return Err("Bubblewrap: timed out waiting for bwrap child information".into());
            }
            thread::sleep(Duration::from_millis(10));
        }
    }

    pub(crate) fn release(&mut self) -> Result<(), String> {
        let writer = self
            .gate_writer
            .take()
            .ok_or_else(|| "Bubblewrap: workload startup gate is already closed".to_string())?;
        File::from(writer)
            .write_all(&[1])
            .map_err(|error| format!("Bubblewrap: failed to release workload startup: {error}"))
    }
}

/// The rule families the supervisor installs.
///
/// IPv6 is dropped only when the kernel has no IPv6 stack at all. The sandbox
/// then cannot open an IPv6 socket, so there is no IPv6 traffic to filter, and
/// `ip6tables-restore` would fail because the kernel has no IPv6 tables to
/// program. Every other host keeps both families.
fn rule_families(kernel_ipv6: bool) -> &'static [RuleFamily] {
    if kernel_ipv6 {
        &[RuleFamily::V4, RuleFamily::V6]
    } else {
        &[RuleFamily::V4]
    }
}

/// Whether the kernel can create IPv6 sockets.
///
/// Answered by opening one rather than by reading `/proc/net/if_inet6`. Where
/// IPv6 is a module, a socket request loads it, so a later request (including
/// one from inside the sandbox) could bring IPv6 up after a file check had
/// reported it absent. Opening the socket here triggers that load first, so
/// only a kernel that cannot provide IPv6 at all answers `EAFNOSUPPORT`.
fn kernel_supports_ipv6() -> bool {
    ipv6_probe_means_supported(socket(
        AddressFamily::Inet6,
        SockType::Datagram,
        SockFlag::SOCK_CLOEXEC,
        None,
    ))
}

/// Only `EAFNOSUPPORT` proves IPv6 is absent. Any other failure, such as
/// descriptor exhaustion, says nothing about IPv6, so the IPv6 rules are kept
/// and `ip6tables-restore` gets the final word.
fn ipv6_probe_means_supported(probe: nix::Result<OwnedFd>) -> bool {
    !matches!(probe, Err(Errno::EAFNOSUPPORT))
}

/// Warn that the IPv6 firewall rules were not installed.
///
/// Uses [`Logger::warning_line`], not `log_line`, so that callers see it in
/// `Output::warnings`; `warn_unreachable_v6_targets` in `bwrap_runner` explains
/// why the debug buffer is not a channel either path reads.
fn warn_skipped_ipv6_rules(kernel_ipv6: bool, logger: &mut Logger) {
    if kernel_ipv6 {
        return;
    }
    logger.warning_line(
        "WARNING: Bubblewrap did not install IPv6 firewall rules: the kernel reports \
         no IPv6 support (EAFNOSUPPORT), so the sandbox cannot send IPv6 traffic and \
         the IPv4 rules alone enforce the network policy.",
    );
}

pub(crate) struct ProxyNetworkNamespace {
    state_dir: TempDir,
    supervisor: Supervisor,
    exit_writer: Option<OwnedFd>,
    /// Write end of the pipe carrying the sandbox PID to the supervisor.
    /// Dropping it without writing ends the supervisor's wait at EOF.
    pid_writer: Option<OwnedFd>,
    userns: Option<File>,
    /// Hosts file mounted over `/etc/hosts`, when the endpoint is a hostname.
    hosts: Option<PathBuf>,
    /// Generated resolver file and the sandbox path it is mounted over, when
    /// the host's own nameservers are unreachable from a private namespace.
    resolver: Option<(String, String)>,
    /// Read end of the descriptor the supervisor and slirp hold open, taken by
    /// the monitor that watches for the network provider dying mid-run.
    liveness_reader: Option<OwnedFd>,
    /// Restore transactions the supervisor will apply, which sizes the
    /// readiness budget in [`Self::attach`].
    transactions: usize,
    /// The request's `script_timeout` in ms, 0 when absent. Clamps the same
    /// budget, which is spent before the child's own timeout exists.
    script_timeout_ms: u32,
}

impl ProxyNetworkNamespace {
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn start(
        tools: &NetworkTools,
        plan: &EgressPlan,
        ingress: &IngressPlan,
        pin: Option<&ProxyHostPin>,
        resolver: Option<&ResolverPin>,
        logger: &mut Logger,
        script_timeout_ms: u32,
        workload_userns: Option<&File>,
        identity: Option<RootIdentity>,
    ) -> Result<Self, String> {
        let state_dir = tempfile::Builder::new()
            .prefix("mxc-bwrap-proxy-")
            .tempdir()
            .map_err(|error| {
                format!("Bubblewrap: failed to create proxy-network state: {error}")
            })?;
        // Written before the supervisor is spawned: the script reads them
        // during startup, so a missing or partial file must not be possible.
        // A family renders to as many transactions as its size needs; the
        // supervisor applies them in name order.
        let kernel_ipv6 = kernel_supports_ipv6();
        warn_skipped_ipv6_rules(kernel_ipv6, logger);
        let mut transactions = 0usize;
        for &family in rule_families(kernel_ipv6) {
            let payloads =
                render_filter_payloads(plan, ingress, family, EGRESS_CHAIN, INGRESS_CHAIN);
            transactions += payloads.len();
            for (index, payload) in payloads.iter().enumerate() {
                let path = state_dir
                    .path()
                    .join(payload_file_name(family, index, payloads.len()));
                std::fs::write(&path, payload).map_err(|error| {
                    format!("Bubblewrap: failed to write network rules to {path:?}: {error}")
                })?;
            }
        }
        let stderr_path = state_dir.path().join("supervisor.stderr");
        let stderr = File::create(&stderr_path).map_err(|error| {
            format!("Bubblewrap: failed to create proxy-network diagnostics: {error}")
        })?;
        let (exit_reader, exit_writer) = pipe_above_stdio()?;
        let (pid_reader, pid_writer) = pipe_above_stdio()?;
        let (liveness_reader, liveness_writer) = pipe_above_stdio()?;
        set_nonblocking(liveness_reader.as_raw_fd())?;

        let mut command = if workload_userns.is_some() {
            Command::new(&tools.sh)
        } else {
            let mut command = Command::new(&tools.unshare);
            command
                .args(["--user", "--map-current-user", "--keep-caps", "--"])
                .arg(&tools.sh);
            command
        };
        let slirp_sandbox = if workload_userns.is_some() {
            "yes"
        } else {
            "no"
        };
        // The supervisor's TERM/INT trap, which stops slirp4netns, can only
        // run if those signals are not left blocked by the watchdog.
        termination_signals::unblock_in_child(&mut command);
        command
            .args(["-c", SUPERVISOR_SCRIPT, "mxc-bwrap-proxy-supervisor"])
            .arg(state_dir.path())
            .arg(XTABLES_LOCK_WAIT.as_secs().to_string())
            .args(tools.supervisor_arguments())
            .arg(slirp_sandbox)
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::from(stderr))
            // Its own group, so a failed startup can kill every descendant.
            .process_group(0);
        // Both pipes stay CLOEXEC in this process, so a concurrent spawn from
        // another thread cannot inherit them; only the supervisor gets them,
        // and only at the fixed numbers its script names.
        remap_descriptors(
            &mut command,
            [
                (pid_reader.as_raw_fd(), SUPERVISOR_PID_FD),
                (exit_reader.as_raw_fd(), SUPERVISOR_EXIT_FD),
                (liveness_writer.as_raw_fd(), SUPERVISOR_LIVENESS_FD),
            ],
        );

        let mut supervisor = command.spawn().map(Supervisor::new).map_err(|error| {
            format!("Bubblewrap: failed to start proxy-network supervisor: {error}")
        })?;
        drop(exit_reader);
        drop(pid_reader);

        // The supervisor tree is now the only holder of the write end, which is
        // what makes the read end reach EOF when it dies.
        drop(liveness_writer);

        if let Err(error) = wait_for_file(
            state_dir.path().join("userns.ready"),
            &mut supervisor,
            &stderr_path,
            "user namespace startup",
            STARTUP_TIMEOUT,
        ) {
            let _ = supervisor.terminate();
            return Err(format!(
                "{error}. If unshare was refused, check AppArmor's \
                 kernel.apparmor_restrict_unprivileged_userns setting and the \
                 kernel.unprivileged_userns_clone and user.max_user_namespaces limits"
            ));
        }

        let userns_path = format!("/proc/{}/ns/user", supervisor.id());
        let userns = match workload_userns
            .map(File::try_clone)
            .unwrap_or_else(|| File::open(&userns_path))
            .and_then(|file| above_stdio(file).map_err(std::io::Error::from))
        {
            Ok(file) => file,
            Err(error) => {
                let _ = supervisor.terminate();
                return Err(format!(
                    "Bubblewrap: failed to open proxy user namespace {userns_path}: {error}"
                ));
            }
        };
        logger.log_line("Bubblewrap: created private network supervisor");

        let hosts = match pin {
            Some(pin) => {
                let path = state_dir.path().join("hosts");
                if let Err(error) = write_pinned_hosts(&path, pin, identity) {
                    let _ = supervisor.terminate();
                    return Err(error);
                }
                logger.log_line(&format!(
                    "Bubblewrap: pinned proxy host '{}' to {} for the sandbox",
                    pin.hostname(),
                    pin.ip()
                ));
                Some(path)
            }
            None => None,
        };

        let resolver = stage_resolver(resolver, state_dir.path(), logger);

        Ok(Self {
            state_dir,
            supervisor,
            exit_writer: Some(exit_writer),
            pid_writer: Some(pid_writer),
            userns: Some(userns),
            hosts,
            resolver,
            liveness_reader: Some(liveness_reader),
            transactions,
            script_timeout_ms,
        })
    }

    /// Whether the sandbox will be given the generated resolver.
    pub(crate) fn resolver_pinned(&self) -> bool {
        self.resolver.is_some()
    }

    /// Add the dynamic namespace and startup-barrier descriptors to bwrap.
    pub(crate) fn configure_bwrap(
        &self,
        args: &mut Vec<String>,
        logger: &mut Logger,
    ) -> Result<BwrapStartup, String> {
        let userns = self
            .userns
            .as_ref()
            .ok_or_else(|| "Bubblewrap: proxy user namespace is already handed off".to_string())?;

        let mut pins = Vec::new();
        if let Some(hosts) = &self.hosts {
            let file = open_pin(hosts)?;
            if insert_hosts_bind(args, file.as_raw_fd())? {
                logger.log_line(
                    "Bubblewrap: the proxy host pin overrides an earlier mount of \
                     /etc/hosts; the sandbox sees the pinned file",
                );
            }
            pins.push(file);
        }

        if let Some((source, destination)) = &self.resolver {
            let file = open_pin(Path::new(source))?;
            if insert_pin_bind(args, file.as_raw_fd(), destination)? {
                logger.log_line(&format!(
                    "Bubblewrap: the resolver pin overrides an earlier mount of {destination}; \
                     the sandbox sees the pinned file"
                ));
            }
            pins.push(file);
        }

        let mut startup = BwrapStartup::configure(args)?;
        args.splice(
            0..0,
            ["--userns".to_string(), userns.as_raw_fd().to_string()],
        );
        startup.inheritable.push(userns.as_raw_fd());
        startup
            .inheritable
            .extend(pins.iter().map(AsRawFd::as_raw_fd));
        startup._pins = pins;
        Ok(startup)
    }

    pub(crate) fn userns_handed_off(&mut self) {
        self.userns.take();
    }

    /// Give the supervisor the Bubblewrap child PID and wait for slirp readiness.
    pub(crate) fn attach(&mut self, child_pid: u32, logger: &mut Logger) -> Result<(), String> {
        let timeout = rule_install_timeout(self.transactions, self.script_timeout_ms);
        self.attach_within(child_pid, timeout, logger)
    }

    fn attach_within(
        &mut self,
        child_pid: u32,
        timeout: Duration,
        logger: &mut Logger,
    ) -> Result<(), String> {
        let mut writer = self
            .pid_writer
            .take()
            .map(File::from)
            .ok_or_else(|| "Bubblewrap: sandbox PID was already published".to_string())?;
        writer
            .write_all(format!("{child_pid}\n").as_bytes())
            .map_err(|error| format!("Bubblewrap: failed to publish bwrap child PID: {error}"))?;
        drop(writer);

        wait_for_file(
            self.state_dir.path().join("slirp.ready"),
            &mut self.supervisor,
            &self.state_dir.path().join("supervisor.stderr"),
            // Written after slirp is up *and* both rule sets are installed, so
            // naming slirp alone would send the reader to the wrong place.
            "slirp4netns startup and network rule installation",
            timeout,
        )?;
        logger.log_line(
            "Bubblewrap: slirp4netns configured the private network namespace and the network \
             rules are in force",
        );
        Ok(())
    }

    /// Confirm the network provider is still alive, immediately before the
    /// workload's startup gate opens.
    ///
    /// `slirp.ready` is a latch that stays on disk after slirp dies, so the
    /// readiness [`Self::attach`] waited for can already be stale here.
    pub(crate) fn check_alive(&mut self) -> Result<(), String> {
        match self.supervisor.poll() {
            Ok(None) => Ok(()),

            // The supervisor's last act is to wait on slirp, so it outlives
            // slirp and any exit at all leaves the sandbox with no route.
            Ok(Some(status)) => Err(format!(
                "Bubblewrap: the proxy network supervisor exited ({status}) after signalling \
                 readiness but before the workload started, leaving the sandbox with no \
                 network provider ({})",
                stderr_detail(&self.state_dir.path().join("supervisor.stderr"))
            )),
            Err(error) => Err(format!(
                "Bubblewrap: failed to inspect the proxy network supervisor before starting \
                 the workload: {error}"
            )),
        }
    }

    /// Take the descriptor a [`ProviderMonitor`] watches for provider loss.
    pub(crate) fn take_liveness_watch(&mut self) -> Option<OwnedFd> {
        self.liveness_reader.take()
    }

    /// Describe the provider loss a monitor observed, for the error the run
    /// fails with.
    pub(crate) fn lost_provider_detail(&mut self) -> String {
        let status = match self.supervisor.poll() {
            Ok(Some(status)) => format!("exited with {status}"),
            Ok(None) => "is still running, so slirp4netns died on its own".to_string(),
            Err(error) => format!("could not be inspected: {error}"),
        };
        format!(
            "Bubblewrap: the sandbox lost its network provider while the workload was \
             running; the proxy network supervisor {status} ({})",
            stderr_detail(&self.state_dir.path().join("supervisor.stderr"))
        )
    }

    /// Stop slirp and reap the namespace supervisor.
    pub(crate) fn stop(&mut self, logger: &mut Logger) {
        // Release the PID pipe too: a supervisor still waiting for the sandbox
        // PID sees EOF and exits rather than lingering.
        self.pid_writer.take();
        self.exit_writer.take();
        let deadline = Instant::now() + SHUTDOWN_TIMEOUT;
        loop {
            match self.supervisor.poll() {
                Ok(Some(status)) => {
                    // A clean teardown closes the exit pipe and slirp leaves
                    // with success. Anything else means it died on its own --
                    // and since slirp carries the sandbox's only route, that
                    // is otherwise indistinguishable from the workload's own
                    // network calls failing. Say so, with whatever it wrote.
                    if !status.success() {
                        logger.log_line(&format!(
                            "WARNING: Bubblewrap: proxy network supervisor exited with {status} \
                             ({})",
                            stderr_detail(&self.state_dir.path().join("supervisor.stderr"))
                        ));
                    }
                    return;
                }
                Ok(None) if Instant::now() < deadline => {
                    thread::sleep(Duration::from_millis(10));
                }
                Ok(None) => {
                    logger.log_line(&format!(
                        "WARNING: Bubblewrap: slirp4netns did not stop promptly; terminating it \
                         ({})",
                        stderr_detail(&self.state_dir.path().join("supervisor.stderr"))
                    ));
                    let _ = self.supervisor.terminate();
                    return;
                }
                Err(error) => {
                    logger.log_line(&format!(
                        "WARNING: Bubblewrap: failed to inspect slirp4netns shutdown: {error}"
                    ));
                    let _ = self.supervisor.terminate();
                    return;
                }
            }
        }
    }
}

impl Drop for ProxyNetworkNamespace {
    fn drop(&mut self) {
        let mut logger = Logger::new(crate::mxc_common::logger::Mode::Buffer);
        self.stop(&mut logger);
    }
}

/// Rewrite a loopback or wildcard proxy URL to slirp's host gateway.
///
/// Only IP literals reach here. A hostname is pinned instead, so that the URL
/// the workload receives is the one the operator configured.
fn rewrite_to_gateway(address: &ProxyAddress) -> Result<ProxyAddress, String> {
    if let Some(original_url) = &address.original_url {
        let mut url = url::Url::parse(original_url).map_err(|error| {
            format!("Bubblewrap: failed to translate proxy URL for private networking: {error}")
        })?;
        url.set_host(Some(SLIRP_HOST_GATEWAY)).map_err(|_| {
            "Bubblewrap: failed to translate proxy URL host for private networking".to_string()
        })?;
        return Ok(ProxyAddress::from_url(
            url.as_str(),
            SLIRP_HOST_GATEWAY.to_string(),
            address.port(),
        ));
    }

    Ok(ProxyAddress::new(
        SLIRP_HOST_GATEWAY.to_string(),
        address.port(),
    ))
}

/// Outcome of a bounded dependency probe.
#[derive(Debug)]
struct ProbeOutput {
    status: ExitStatus,
    stdout: String,
}

/// Which bound produced a command's deadline, so a timeout names the right
/// cause: a hung tool, or a budget earlier checks had spent.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum DeadlineSource {
    Command,
    Budget,
}

/// How long a dependency walk may take in total. `None` bounds the walk only
/// by the sum of the per-command [`PROBE_TIMEOUT`]s.
#[derive(Clone, Copy)]
struct ProbeBudget {
    deadline: Option<Instant>,
}

impl ProbeBudget {
    fn unbounded() -> Self {
        Self { deadline: None }
    }

    fn total(budget: Duration) -> Self {
        Self {
            deadline: Some(Instant::now() + budget),
        }
    }

    /// The next command's own ceiling, clamped to what is left of the budget.
    fn command_deadline(self) -> (Instant, DeadlineSource) {
        let per_command = Instant::now() + PROBE_TIMEOUT;
        match self.deadline {
            Some(total) if total < per_command => (total, DeadlineSource::Budget),
            _ => (per_command, DeadlineSource::Command),
        }
    }

    fn is_exhausted(self) -> bool {
        self.deadline
            .is_some_and(|deadline| Instant::now() >= deadline)
    }
}

/// Run `command` to completion, killing it if it outlives [`PROBE_TIMEOUT`].
///
/// `Command::output()` waits forever. These probes run inside `validate`, so a
/// single wedged binary would stall every proxy-mode execution on the host with
/// no diagnostic -- a hang is far harder to chase than a failure, so bound it
/// and name the tool that stalled.
///
/// The bounded-execution mechanics live in [`crate::bwrap_common::probe_exec`], shared with
/// the `bwrap --version` gate.
fn run_probe(
    mut command: Command,
    label: &str,
    budget: ProbeBudget,
) -> Result<ProbeOutput, String> {
    if budget.is_exhausted() {
        return Err(format!(
            "Bubblewrap: ran out of time before checking '{label}' \
             (the host took longer than {PRE_FLIGHT_BUDGET:?} to answer earlier checks)"
        ));
    }

    let (deadline, deadline_source) = budget.command_deadline();
    // `cleanup_error` means the probe could not prove it stopped the child it
    // abandoned, so it is appended rather than dropped.
    let timed_out = |cleanup_error: Option<std::io::Error>| {
        let reason = match deadline_source {
            DeadlineSource::Command => format!(
                "Bubblewrap: '{label}' did not respond within {PROBE_TIMEOUT:?}; \
                 the host's {label} installation appears to be hung"
            ),
            // The budget is shorter than the per-command ceiling, so this fires
            // for a healthy-but-slow tool too; blaming it for hanging would be
            // wrong.
            DeadlineSource::Budget => format!(
                "Bubblewrap: gave up while checking '{label}' after the host took \
                 longer than {PRE_FLIGHT_BUDGET:?} to answer the dependency checks"
            ),
        };
        match cleanup_error {
            Some(error) => {
                format!("{reason}; failed to terminate it, so it may still be running: {error}")
            }
            None => reason,
        }
    };

    match probe_exec::run_bounded(&mut command, deadline) {
        Ok(captured) => {
            // A banner this large is not the tool we meant to interrogate, and
            // the backend/flag checks downstream read the text -- so a partial
            // read must not be treated as an answer.
            if captured.stdout.truncated || captured.stderr.truncated {
                return Err(format!(
                    "Bubblewrap: '{label}' produced more than {} bytes of output; \
                     refusing to judge a truncated banner",
                    probe_exec::MAX_PROBE_OUTPUT_BYTES
                ));
            }
            Ok(ProbeOutput {
                status: captured.status,
                stdout: String::from_utf8_lossy(&captured.stdout.bytes).into_owned(),
            })
        }
        Err(probe_exec::ProbeFailure::Spawn(error)) => Err(format!("{error}")),
        Err(probe_exec::ProbeFailure::TimedOut { cleanup_error }) => Err(timed_out(cleanup_error)),
        Err(probe_exec::ProbeFailure::Wait { stage, error }) => Err(format!(
            "failed while {} '{label}': {error}",
            stage.as_str()
        )),
        Err(probe_exec::ProbeFailure::Internal(detail)) => {
            Err(format!("failed to inspect '{label}': {detail}"))
        }
    }
}

/// Flags for the namespace grant check, and the single definition of what
/// the kernel is asked for — the walk builds the command through its injected
/// factory.
///
/// `unshare --help` only proves the flags are compiled in; the kernel can still
/// refuse (unprivileged userns disabled, AppArmor restriction, or
/// `user.max_net_namespaces` exhausted). Both namespaces are requested together, mirroring
/// the `CLONE_NEWUSER|CLONE_NEWNET` bwrap asks for.
const PRIVATE_NAMESPACE_PROBE_FLAGS: [&str; 5] =
    ["--user", "--map-current-user", "--keep-caps", "--net", "--"];

fn private_namespace_probe<F>(tools: &NetworkTools, command: &F) -> Command
where
    F: Fn(&Path, &[&str]) -> Command,
{
    let mut probe = command(&tools.unshare, &PRIVATE_NAMESPACE_PROBE_FLAGS);

    // The supervisor runs as `sh -c` inside these namespaces, so the check runs
    // a no-op the same way.
    probe.arg(&tools.sh).args(["-c", ":"]);
    probe
}

/// Run the namespace grant check and turn a refusal into actionable guidance.
///
/// Takes the command so tests can drive the real path — `run_probe`, a genuine
/// [`ExitStatus`], and the diagnostic mapping — with a stand-in that fails
/// deterministically. The kernel cannot be made to refuse namespaces from a
/// unit test, so without this seam the failure path is only ever exercised at
/// the pure-formatter level.
fn check_private_namespaces(
    command: Command,
    shell: &Path,
    use_case: PrivateNetworkUse,
    budget: ProbeBudget,
) -> Result<(), String> {
    let requirement = use_case.requirement();
    let userns = run_probe(command, "unshare", budget).map_err(|error| {
        format!("Bubblewrap: {requirement} requires private user and network namespaces: {error}")
    })?;
    if !userns.status.success() {
        return Err(namespace_probe_error(userns.status, shell, use_case));
    }
    Ok(())
}

/// Whether an `unshare` exit code means the trailing command never started,
/// rather than the namespaces being refused (which exits 1).
fn shell_failed_to_start(code: i32) -> bool {
    matches!(code, 126 | 127)
}

/// Turn a failed namespace probe into actionable guidance.
///
/// Split out so the diagnostics are testable: a host where the namespaces work
/// cannot be made to produce these statuses.
fn namespace_probe_error(status: ExitStatus, shell: &Path, use_case: PrivateNetworkUse) -> String {
    let requirement = use_case.requirement();

    // 126/127 are the exec-failure codes `unshare` propagates (EACCES and
    // ENOENT). Both mean the namespaces worked and the shell is what could not
    // start.
    if status.code().is_some_and(shell_failed_to_start) {
        return format!(
            "Bubblewrap: {requirement} runs its network supervisor with '{}', which could not \
             start inside the new namespace. Install a working POSIX shell or {}.",
            shell.display(),
            use_case.remedy()
        );
    }
    format!(
        "Bubblewrap: {requirement} requires unprivileged user and network namespaces, \
         which this host refused (unshare --user --net exited with {status}). On Ubuntu 24.04+ \
         this is usually AppArmor's 'kernel.apparmor_restrict_unprivileged_userns=1': give \
         the caller an AppArmor profile that permits userns, or clear that sysctl on an \
         ephemeral host. Otherwise enable the namespaces (for example 'sysctl -w \
         kernel.unprivileged_userns_clone=1', or raise 'user.max_user_namespaces' / \
         'user.max_net_namespaces') or {}.",
        use_case.remedy()
    )
}

/// Write the sandbox's `/etc/hosts`: the pin, then the host's own entries with
/// every competing mapping for the pinned name removed.
///
/// Ordering alone is *not* enough, which is why the name is stripped rather
/// than merely outranked. glibc's `files` backend collects **every** line that
/// matches a name and hands the whole set to `getaddrinfo`, which then re-sorts
/// it by RFC 6724 destination-address rules. Those rules promote a loopback
/// address above a global one, so a leftover `127.0.0.1 <proxy>` entry is
/// returned *ahead* of a pin written on line 1. A client walking the result in
/// order then dials an address the egress chain never authorized -- or, worse,
/// dials back into the sandbox's own loopback.
///
/// The host's other entries are kept so the sandbox retains the mappings a
/// workload expects (`localhost` above all). They are read before the file is
/// created, so a read failure cannot leave a half-written pin behind.
fn write_pinned_hosts(
    path: &Path,
    pin: &ProxyHostPin,
    identity: Option<RootIdentity>,
) -> Result<(), String> {
    // The host file is optional: a host without one simply contributes no
    // entries, which is not a reason to refuse to pin.
    let existing = match read_as_workload(identity, Path::new(SANDBOX_HOSTS_PATH)) {
        Ok(contents) => contents,
        Err(error) if error.kind() == ErrorKind::NotFound => String::new(),
        Err(error) => {
            return Err(format!(
                "Bubblewrap: failed to read {SANDBOX_HOSTS_PATH} while pinning the proxy host: \
                 {error}"
            ))
        }
    };

    let contents = format!(
        "{}\n{}",
        pin.hosts_line(),
        strip_host_from_hosts(&existing, pin.hostname())
    );
    fs::write(path, contents)
        .map_err(|error| format!("Bubblewrap: failed to write the proxy hosts pin: {error}"))
}

/// Remove `hostname` from every entry in a hosts file, dropping a line that has
/// no names left.
///
/// Only the name is removed, never the whole line: an entry like
/// `127.0.0.1 localhost <proxy>` still has to keep resolving `localhost`.
/// Comments and blank lines pass through untouched so the sandbox's file stays
/// recognizable, and a trailing comment on a mapping line is preserved.
///
/// Matching is ASCII-case-insensitive because DNS names are, so a host file
/// spelling the proxy name in a different case would otherwise survive and
/// reintroduce exactly the competing mapping this removes.
fn strip_host_from_hosts(contents: &str, hostname: &str) -> String {
    let mut out = String::with_capacity(contents.len());
    for line in contents.lines() {
        let (body, comment) = match line.split_once('#') {
            Some((body, comment)) => (body, Some(comment)),
            None => (line, None),
        };

        let mut fields = body.split_whitespace();
        let Some(address) = fields.next() else {
            out.push_str(line);
            out.push('\n');
            continue;
        };

        // Lines that never mention the pinned name are passed through byte for
        // byte. Rewriting them would normalize the operator's tabs and column
        // alignment for no benefit.
        let names: Vec<&str> = fields.collect();
        if !names.iter().any(|name| name.eq_ignore_ascii_case(hostname)) {
            out.push_str(line);
            out.push('\n');
            continue;
        }

        let kept: Vec<&str> = names
            .into_iter()
            .filter(|name| !name.eq_ignore_ascii_case(hostname))
            .collect();

        // Every name on the line was the pinned one, so the mapping is gone.
        // Keep a trailing comment rather than silently deleting the operator's
        // text along with the entry.
        if kept.is_empty() {
            if let Some(comment) = comment {
                out.push('#');
                out.push_str(comment);
                out.push('\n');
            }
            continue;
        }

        out.push_str(address);
        for name in kept {
            out.push(' ');
            out.push_str(name);
        }
        if let Some(comment) = comment {
            out.push_str(" #");
            out.push_str(comment);
        }
        out.push('\n');
    }
    out
}

#[derive(Debug)]
pub(crate) struct ResolverPin {
    /// Canonical host path, which is what the filesystem policy is compared
    /// against.
    destination: String,
    contents: String,
}

impl ResolverPin {
    pub(crate) fn for_host(
        policy: &ContainerPolicy,
        mounts: &[PolicyMount],
        identity: Option<RootIdentity>,
        logger: &mut Logger,
    ) -> Option<Self> {
        Self::from_resolver(
            Path::new(SANDBOX_RESOLV_CONF_PATH),
            policy,
            mounts,
            identity,
            logger,
        )
    }

    pub(crate) fn from_resolver(
        resolver_path: &Path,
        policy: &ContainerPolicy,
        mounts: &[PolicyMount],
        identity: Option<RootIdentity>,
        logger: &mut Logger,
    ) -> Option<Self> {
        let shown = resolver_path.display();
        let host_contents = match read_as_workload(identity, resolver_path) {
            Ok(contents) => contents,
            // No resolver file is not a loopback stub to rescue, and is normal
            // on a host that configures DNS some other way.
            Err(error) if error.kind() == ErrorKind::NotFound => return None,
            Err(error) => {
                logger.warning_line(&format!(
                    "WARNING: Bubblewrap: {shown} could not be read ({error}), so the sandbox \
                     keeps whatever resolver it inherits and names may not resolve inside it."
                ));
                return None;
            }
        };
        if !resolvers_are_loopback_only(&host_contents) {
            return None;
        }

        let destination = match resolver_target_of(resolver_path) {
            Ok(destination) => destination,
            Err(reason) => {
                logger.warning_line(&format!(
                    "WARNING: Bubblewrap: the host resolves through a loopback nameserver, which \
                     the sandbox's private network namespace cannot reach, and {reason}. Names \
                     will not resolve inside the sandbox; point {shown} at a routable nameserver."
                ));
                return None;
            }
        };

        let destination_text = match destination.to_str() {
            Some(text) => text.to_string(),
            None => {
                logger.warning_line(&format!(
                    "WARNING: Bubblewrap: the host resolves through a loopback nameserver, but \
                     {} is not valid UTF-8 and cannot be named to bwrap, so the sandbox keeps \
                     the host's unreachable resolver. Names will not resolve inside the sandbox.",
                    destination.display()
                ));
                return None;
            }
        };
        let sandbox_destination = sandbox_mount_path(&destination_text);
        let covering_mount = mounts
            .iter()
            .rfind(|mount| Path::new(&sandbox_destination).starts_with(&mount.destination));
        if resolver_target_is_denied(policy, &destination)
            || covering_mount.is_some_and(|mount| mount.intent == FsIntent::Denied)
        {
            logger.warning_line(&format!(
                "WARNING: Bubblewrap: the host resolves through a loopback nameserver, but the \
                 filesystem policy denies {destination_text}, so the sandbox keeps the host's \
                 unreachable resolver. Names will not resolve inside the sandbox; remove that \
                 path from deniedPaths to let the sandbox use slirp's forwarder."
            ));
            return None;
        }

        if policy_names_path(policy, &resolver_path.to_string_lossy())
            || policy_names_path(policy, &destination_text)
            || covering_mount.is_some_and(|mount| {
                Path::new(&mount.destination) == Path::new(&sandbox_destination)
            })
        {
            logger.warning_line(&format!(
                "WARNING: Bubblewrap: the filesystem policy mounts its own resolver, so the \
                 sandbox keeps it rather than slirp's forwarder — but that file names only \
                 loopback nameservers, which the sandbox's private network namespace cannot \
                 reach, so names will not resolve inside it. Point {shown} at a routable \
                 nameserver, or drop the grant on it to let the sandbox use slirp's forwarder."
            ));
            return None;
        }

        Some(Self {
            destination: destination_text,
            contents: render_pinned_resolv_conf(&host_contents),
        })
    }

    /// Write the generated file into `directory` and report the mount it needs.
    fn stage(&self, directory: &Path) -> Result<(String, String), String> {
        let source = directory.join("resolv.conf");
        fs::write(&source, &self.contents)
            .map_err(|error| format!("Bubblewrap: failed to write the resolver pin: {error}"))?;
        let source = source.to_str().ok_or_else(|| {
            format!(
                "Bubblewrap: the staged resolver path {} is not valid UTF-8",
                source.display()
            )
        })?;
        Ok((source.to_string(), sandbox_mount_path(&self.destination)))
    }
}

/// Write the pin into `directory` and report the mount it needs, or `None`
/// when there is nothing to pin or staging failed.
///
/// A staging failure gives up the pin rather than the run. The pin is an
/// improvement on a resolver the sandbox already cannot reach, so refusing to
/// start would deny the caller a sandbox that would otherwise have run with
/// exactly the DNS it has today.
fn stage_resolver(
    resolver: Option<&ResolverPin>,
    directory: &Path,
    logger: &mut Logger,
) -> Option<(String, String)> {
    let resolver = resolver?;
    match resolver.stage(directory) {
        Ok(staged) => {
            logger.log_line(&format!(
                "Bubblewrap: the host resolves through a loopback nameserver, so the sandbox \
                 reads {} with nameserver {SLIRP_DNS_FORWARDER}",
                staged.1
            ));
            Some(staged)
        }
        Err(error) => {
            logger.warning_line(&format!(
                "WARNING: {error}. The sandbox keeps the host's loopback nameserver, which its \
                 private network namespace cannot reach, so names will not resolve inside it."
            ));
            None
        }
    }
}

/// Whether every nameserver the host declares is a loopback address, with at
/// least one of them IPv4.
///
/// Both halves gate the pin. All-loopback means name resolution is already
/// broken inside the namespace, so replacing it cannot regress a host that
/// works. The IPv4 requirement is libslirp's: it forwards a query to the first
/// IPv4 nameserver in the host's file and drops the packet when there is none.
fn resolvers_are_loopback_only(contents: &str) -> bool {
    let mut saw_ipv4_loopback = false;
    for value in nameserver_values(contents) {
        // A link-local v6 nameserver may carry a zone suffix, which is not part
        // of the address.
        let literal = value.split('%').next().unwrap_or(value);
        match literal.parse::<IpAddr>() {
            Ok(address) if address.is_loopback() => saw_ipv4_loopback |= address.is_ipv4(),
            _ => return false,
        }
    }
    saw_ipv4_loopback
}

/// The sandbox's resolver file, pointed at slirp's forwarder.
///
/// Only the directives `resolv.conf(5)` defines are carried over: `search`,
/// `domain`, `sortlist`, and `options` decide how a bare name is expanded and
/// retried, so dropping them would change which names resolve rather than
/// merely where they resolve.
fn render_pinned_resolv_conf(contents: &str) -> String {
    let mut out = format!("nameserver {SLIRP_DNS_FORWARDER}\n");
    for line in contents.lines().filter(|line| {
        directive_keyword(line).is_some_and(|keyword| CARRIED_DIRECTIVES.contains(&keyword))
    }) {
        out.push_str(line);
        out.push('\n');
    }
    out
}

/// Resolver directives that change which names resolve.
const CARRIED_DIRECTIVES: &[&str] = &["search", "domain", "sortlist", "options"];

/// The directive a line declares, if it declares one.
fn directive_keyword(line: &str) -> Option<&str> {
    // A resolver directive is only read when its keyword starts the line.
    if line.starts_with(char::is_whitespace) {
        return None;
    }
    line.split_whitespace().next()
}

fn nameserver_values(contents: &str) -> impl Iterator<Item = &str> {
    contents
        .lines()
        .filter(|line| is_nameserver_line(line))
        .filter_map(|line| line.split_whitespace().nth(1))
}

fn is_nameserver_line(line: &str) -> bool {
    directive_keyword(line) == Some("nameserver")
}

/// Where the pin has to be mounted for the sandbox to read it.
///
/// bwrap refuses to mount over a path whose leaf is a symlink, and cannot
/// create a mount point beneath a symlinked ancestor that sits inside a
/// read-only bind, so the destination is resolved the same way a `deniedPaths`
/// entry is: every component, not only the leaf. Resolving less than that also
/// made the policy checks compare a spelling the mount would never use.
fn resolver_target_of(start: &Path) -> Result<PathBuf, String> {
    let resolved = resolve_through_symlinks(start)
        .ok_or_else(|| format!("{} is not a resolvable path", start.display()))?;
    if let Some(error) = resolved.error {
        return Err(format!(
            "{} could not be resolved ({error})",
            start.display()
        ));
    }
    let resolved = resolved.path;

    let metadata = fs::symlink_metadata(&resolved)
        .map_err(|error| format!("{} could not be read ({error})", resolved.display()))?;
    if !metadata.file_type().is_file() {
        return Err(format!(
            "{} does not resolve to a regular file",
            resolved.display()
        ));
    }
    Ok(resolved)
}

/// Reject a hostname endpoint whose pin would defeat a denied `/etc/hosts`.
///
/// The pin is spliced after every filesystem-policy mount so it survives them
/// (see [`insert_hosts_bind`]), which means it would also survive a denial --
/// handing back a readable file, populated from the host's own `/etc/hosts`,
/// that the policy asked to mask. Refusing at policy time is the only honest
/// outcome: dropping the pin instead would leave the proxy name unresolvable
/// and fail at connect time, long after the caller could act on it.
///
/// Only a denial is refused. A `readonlyPaths` or `readwritePaths` entry is
/// still overridden with a warning: shadowing a mount the caller asked to
/// *read* narrows their access rather than widening it.
pub(crate) fn check_hosts_pin_against_policy(
    configured: &ProxyAddress,
    policy: &ContainerPolicy,
) -> Result<(), String> {
    let (needs_pin, _) = SandboxProxy::inspect_without_resolving(configured);
    if !needs_pin || !hosts_file_is_denied(policy) {
        return Ok(());
    }

    Err(format!(
        "Bubblewrap: the proxy endpoint '{}' is a hostname, which is reached by pinning it in \
         the sandbox's {SANDBOX_HOSTS_PATH}, but the filesystem policy denies that path. The pin \
         is applied after every policy mount, so honouring it would expose the file the policy \
         masks. Remove {SANDBOX_HOSTS_PATH} from deniedPaths, or give the proxy an IP address, \
         which needs no pin.",
        configured.host()
    ))
}

/// Whether the filesystem policy masks the sandbox's hosts file.
///
/// The plan is ordered shallow-to-deep and bwrap applies the last mount at a
/// path, so the deepest entry covering the file is the one that takes effect:
/// an ancestor denial counts, and a more specific grant beneath it wins back.
fn hosts_file_is_denied(policy: &ContainerPolicy) -> bool {
    path_is_denied(policy, SANDBOX_HOSTS_PATH)
}

/// Whether the filesystem policy names `target` itself rather than an ancestor.
fn policy_names_path(policy: &ContainerPolicy, target: &str) -> bool {
    resolve_mount_order(policy)
        .iter()
        .any(|mount| mount.path.trim_end_matches('/') == target)
}

/// Index of the separator that ends bwrap's options and begins the command.
///
/// Scanning for the first `--` would find a caller-controlled value instead:
/// `process.env` of `FOO=--` is emitted as `--setenv FOO --` ahead of the real
/// separator, and splicing there would shift the pin's three arguments into
/// that option's operands. Scanning for the *last* one is no better -- the
/// script is arbitrary text. The command is appended last with a fixed shape,
/// so that trailing shape is what identifies it.
fn command_separator(args: &[String]) -> Result<usize, String> {
    args.len()
        .checked_sub(COMMAND_TAIL.len() + 1)
        .filter(|&separator| args[separator..separator + COMMAND_TAIL.len()] == COMMAND_TAIL[..])
        .ok_or_else(|| "Bubblewrap: argument list has no command separator".to_string())
}

/// Splice a pin's bind in just before the command separator.
///
/// bwrap applies mounts in argument order and the last mount at a path wins,
/// so the bind must come after every baseline and user-policy mount for the
/// pin to survive -- including one that would otherwise expose the host's own
/// file. Returns `true` when an earlier mount already targeted `destination`,
/// so the caller can report that the pin overrides it.
fn insert_pin_bind(
    args: &mut Vec<String>,
    source: RawFd,
    destination: &str,
) -> Result<bool, String> {
    let separator = command_separator(args)?;
    let overrides = args[..separator].iter().any(|arg| arg == destination);
    args.splice(
        separator..separator,
        [
            "--ro-bind-data".to_string(),
            source.to_string(),
            destination.to_string(),
        ],
    );
    Ok(overrides)
}

fn insert_hosts_bind(args: &mut Vec<String>, hosts: RawFd) -> Result<bool, String> {
    insert_pin_bind(args, hosts, SANDBOX_HOSTS_PATH)
}

fn open_pin(path: &Path) -> Result<File, String> {
    File::open(path)
        .and_then(|file| above_stdio(file).map_err(std::io::Error::from))
        .map_err(|error| {
            format!(
                "Bubblewrap: could not open generated pin {}: {error}",
                path.display()
            )
        })
}

/// What pulled this request into a private network namespace.
///
/// The dependency probe is shared by runtime proxy egress and directional
/// firewall enforcement, with actionable advice for either posture.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum PrivateNetworkUse {
    ProxyOnlyEgress,
    FirewallEnforcement,
}

impl PrivateNetworkUse {
    /// The config element that made the private namespace necessary.
    fn requirement(self) -> &'static str {
        match self {
            Self::ProxyOnlyEgress => "runtimeConfig.networkProxy",
            Self::FirewallEnforcement => "network.egress",
        }
    }

    /// What the caller can drop to stop needing these dependencies.
    fn remedy(self) -> &'static str {
        match self {
            Self::ProxyOnlyEgress => "omit runtimeConfig.networkProxy",
            Self::FirewallEnforcement => "use ruleless network.egress.default='deny'",
        }
    }

    /// The mechanism the installed rules implement.
    fn mechanism(self) -> &'static str {
        match self {
            Self::ProxyOnlyEgress => "proxy-only egress",
            Self::FirewallEnforcement => "firewall enforcement",
        }
    }
}

/// Whether this host can enforce proxy-only egress, and why not when it cannot.
///
/// Pre-flight counterpart to the launch-path check in
/// [`crate::bwrap_common::bwrap_runner`]: supported runtime proxy policy has no fallback, so a
/// caller that cannot ask this ahead of time only learns the answer when the
/// run fails. Advisory — the runner checks the tools and creates the
/// namespaces at launch.
///
/// Not exhaustive: a missing `nf_conntrack` module is only detectable when the
/// rules are installed, so it still surfaces at launch.
///
/// Bounded by `PRE_FLIGHT_BUDGET` in total, unlike the launch-path walk: a
/// caller answering "can this host do it?" before spawning cannot afford the
/// sum of every per-command timeout. The walk runs in a deadline-watched
/// worker, so the ceiling holds even when a spawn itself blocks (a PATH lookup
/// on a stalled filesystem is not covered by the per-command deadlines, which
/// only bound what the walk *waits* on).
///
/// Uncached in both directions. Sharing the launch cache would let one
/// advisory call report support long after the tooling was removed, and would
/// let it stand in for the fresh walk the runner promises to do at launch.
pub fn probe_proxy_enforcement() -> Result<(), String> {
    supervise_preflight(PRE_FLIGHT_BUDGET, || {
        probe_dependencies_uncached(
            PrivateNetworkUse::ProxyOnlyEgress,
            ProbeBudget::total(PRE_FLIGHT_BUDGET),
        )
        .map(|_| ())
    })
}

/// Run `walk` on a worker and return by `budget` whatever it is doing.
///
/// The walk's own budget bounds each command it *waits* on, but not the spawn
/// itself: a PATH lookup or exec can block on a stalled filesystem before any
/// deadline is consulted.
///
/// On timeout the worker is **abandoned, not joined**. Joining would
/// reintroduce exactly the unbounded wait this exists to remove; the cost is
/// that a child the walk had in flight is left running and unreaped.
///
/// At most one walk may be in flight: without the gate, a host wedged badly
/// enough to time out would strand another thread on every call. An overlapping
/// caller waits for it within its own budget rather than being refused, so a
/// healthy walk does not make the answer depend on call scheduling.
///
/// `walk` is a parameter so a test can supply one that never returns — the
/// only way to prove this supervision does anything.
fn supervise_preflight<F>(budget: Duration, walk: F) -> Result<(), String>
where
    F: FnOnce() -> Result<(), String> + Send + 'static,
{
    supervise_preflight_with(&PREFLIGHT_GATE, budget, walk)
}

/// [`supervise_preflight`] against a caller-supplied gate, so a test that
/// deliberately strands a worker cannot wedge the shared one.
fn supervise_preflight_with<F>(
    gate: &'static PreflightGate,
    budget: Duration,
    walk: F,
) -> Result<(), String>
where
    F: FnOnce() -> Result<(), String> + Send + 'static,
{
    let deadline = Instant::now() + budget;
    let Some(slot) = gate.claim_until(deadline) else {
        return Err(format!(
            "Bubblewrap: an earlier proxy-enforcement pre-flight probe did not return within \
             {budget:?}, so this host cannot be confirmed"
        ));
    };

    let (sender, receiver) = mpsc::sync_channel(1);
    let worker = thread::Builder::new()
        .name("mxc-proxy-preflight".to_string())
        .spawn(move || {
            let _slot = slot;
            let _ = sender.send(walk());
        });
    if let Err(error) = worker {
        return Err(format!(
            "Bubblewrap: could not start the proxy-enforcement pre-flight probe: {error}"
        ));
    }

    match receiver.recv_timeout(deadline.saturating_duration_since(Instant::now())) {
        Ok(result) => result,
        Err(mpsc::RecvTimeoutError::Timeout) => Err(format!(
            "Bubblewrap: the host did not answer the proxy-enforcement dependency \
             checks within {budget:?}"
        )),
        Err(mpsc::RecvTimeoutError::Disconnected) => {
            Err("Bubblewrap: the proxy-enforcement pre-flight probe stopped unexpectedly".into())
        }
    }
}

/// Admits one pre-flight walk at a time, making later callers wait for the
/// one in flight instead of refusing them outright.
struct PreflightGate {
    in_flight: Mutex<bool>,
    available: Condvar,
}

static PREFLIGHT_GATE: PreflightGate = PreflightGate::new();

impl PreflightGate {
    const fn new() -> Self {
        Self {
            in_flight: Mutex::new(false),
            available: Condvar::new(),
        }
    }

    fn claim_until(&'static self, deadline: Instant) -> Option<PreflightSlot> {
        let mut in_flight = self
            .in_flight
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        loop {
            if !*in_flight {
                *in_flight = true;
                return Some(PreflightSlot(self));
            }

            let remaining = deadline.saturating_duration_since(Instant::now());
            if remaining.is_zero() {
                return None;
            }
            let (next, wait) = self
                .available
                .wait_timeout(in_flight, remaining)
                .unwrap_or_else(|poisoned| poisoned.into_inner());
            in_flight = next;
            if wait.timed_out() && *in_flight {
                return None;
            }
        }
    }
}

/// Permission to run one pre-flight walk, held by the worker rather than the
/// caller: a timed-out caller returns while its walk still owns the slot.
struct PreflightSlot(&'static PreflightGate);

impl Drop for PreflightSlot {
    fn drop(&mut self) {
        let mut in_flight = self
            .0
            .in_flight
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        *in_flight = false;
        self.0.available.notify_one();
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct NetworkTools {
    unshare: PathBuf,
    sh: PathBuf,
    slirp4netns: PathBuf,
    nsenter: PathBuf,
    ip: PathBuf,
    iptables: PathBuf,
    ip6tables: PathBuf,
    iptables_restore: PathBuf,
    ip6tables_restore: PathBuf,
    sleep: PathBuf,
}

impl NetworkTools {
    fn find<L>(use_case: PrivateNetworkUse, find: L) -> Result<Self, String>
    where
        L: Fn(&str) -> Result<PathBuf, LookupError>,
    {
        let tool = |name: &str| {
            find(name).map_err(|error| {
                format!(
                    "Bubblewrap: {} requires '{name}', which {error}. Install it or {}.",
                    use_case.requirement(),
                    use_case.remedy()
                )
            })
        };
        Ok(Self {
            unshare: tool("unshare")?,
            sh: tool("sh")?,
            slirp4netns: tool("slirp4netns")?,
            nsenter: tool("nsenter")?,
            ip: tool("ip")?,
            iptables: tool("iptables")?,
            ip6tables: tool("ip6tables")?,
            iptables_restore: tool("iptables-restore")?,
            ip6tables_restore: tool("ip6tables-restore")?,
            sleep: tool("sleep")?,
        })
    }

    /// `(name, path, argument, whether its iptables backend must be checked)`
    /// for the tools without a dedicated check.
    fn tool_probes(&self) -> [(&'static str, &Path, &'static str, bool); 7] {
        [
            ("nsenter", &self.nsenter, "--version", false),
            ("ip", &self.ip, "-Version", false),
            // The supervisor runs only the -restore variants, but these carry
            // the version banner the backend decision reads.
            ("iptables", &self.iptables, "--version", true),
            ("ip6tables", &self.ip6tables, "--version", true),
            (
                "iptables-restore",
                &self.iptables_restore,
                "--version",
                true,
            ),
            (
                "ip6tables-restore",
                &self.ip6tables_restore,
                "--version",
                true,
            ),
            ("sleep", &self.sleep, "0", false),
        ]
    }

    /// The paths [`SUPERVISOR_SCRIPT`] reads from `$3` onward, in its order.
    fn supervisor_arguments(&self) -> [&Path; 7] {
        [
            &self.nsenter,
            &self.ip,
            &self.slirp4netns,
            &self.iptables_restore,
            &self.ip6tables_restore,
            &self.sleep,
            &self.unshare,
        ]
    }
}

pub(crate) fn probe_dependencies(use_case: PrivateNetworkUse) -> Result<NetworkTools, String> {
    static APPROVED: Mutex<Option<NetworkTools>> = Mutex::new(None);

    probe_dependencies_caching(
        &APPROVED,
        use_case,
        ProbeBudget::unbounded(),
        host_tools::find,
        real_probe_command,
    )
}

/// [`probe_dependencies`] against a caller-supplied approval, so the reuse
/// rules are testable without process-global state.
fn probe_dependencies_caching<L, F>(
    approved: &Mutex<Option<NetworkTools>>,
    use_case: PrivateNetworkUse,
    budget: ProbeBudget,
    find: L,
    command: F,
) -> Result<NetworkTools, String>
where
    L: Fn(&str) -> Result<PathBuf, LookupError>,
    F: Fn(&Path, &[&str]) -> Command,
{
    let tools = NetworkTools::find(use_case, find)?;

    // A newly installed tool, or a PATH change that selects other files, takes
    // effect without restarting the process.
    let already_approved = approved
        .lock()
        .unwrap_or_else(PoisonError::into_inner)
        .as_ref()
        == Some(&tools);
    if !already_approved {
        probe_stable_dependencies(use_case, budget, &tools, &command)?;
        *approved.lock().unwrap_or_else(PoisonError::into_inner) = Some(tools.clone());
    }

    Ok(tools)
}

pub(crate) fn probe_private_namespaces(
    tools: &NetworkTools,
    use_case: PrivateNetworkUse,
) -> Result<(), String> {
    check_private_namespaces(
        private_namespace_probe(tools, &real_probe_command),
        &tools.sh,
        use_case,
        ProbeBudget::unbounded(),
    )
}

#[cfg(test)]
const EXPECTED_SUPERVISOR_SCRIPT_DIGEST: u64 = 0xc1a5_bc1d_c051_a6fd;

/// Every external command [`SUPERVISOR_SCRIPT`] runs, each of which the
/// pre-flight walk must check.
#[cfg(test)]
const SUPERVISOR_EXTERNAL_COMMANDS: &[&str] = &[
    "slirp4netns",
    "nsenter",
    "ip",
    "iptables-restore",
    "ip6tables-restore",
    "sleep",
    "unshare",
];

/// How each dependency check's command is built.
///
/// Injectable so a test can make one specific tool look missing or broken
/// without depending on what the runner happens to have installed — and so the
/// success path can be driven on a host that has none of the tooling.
fn real_probe_command(program: &Path, args: &[&str]) -> Command {
    let mut command = Command::new(program);
    command.args(args);
    command
}

fn probe_dependencies_uncached(
    use_case: PrivateNetworkUse,
    budget: ProbeBudget,
) -> Result<NetworkTools, String> {
    probe_dependencies_with(use_case, budget, host_tools::find, real_probe_command)
}

fn probe_dependencies_with<L, F>(
    use_case: PrivateNetworkUse,
    budget: ProbeBudget,
    find: L,
    command: F,
) -> Result<NetworkTools, String>
where
    L: Fn(&str) -> Result<PathBuf, LookupError>,
    F: Fn(&Path, &[&str]) -> Command,
{
    let tools = probe_dependencies_caching(&Mutex::new(None), use_case, budget, find, &command)?;
    check_private_namespaces(
        private_namespace_probe(&tools, &command),
        &tools.sh,
        use_case,
        budget,
    )?;
    Ok(tools)
}

/// The half of the walk whose answers are fixed by what is installed: tool
/// presence, version banners, and the `iptables` backend.
fn probe_stable_dependencies<F>(
    use_case: PrivateNetworkUse,
    budget: ProbeBudget,
    tools: &NetworkTools,
    command: &F,
) -> Result<(), String>
where
    F: Fn(&Path, &[&str]) -> Command,
{
    let requirement = use_case.requirement();
    let slirp4netns = tools.slirp4netns.display();
    let slirp = run_probe(
        command(&tools.slirp4netns, &["--version"]),
        "slirp4netns",
        budget,
    )
    .map_err(|error| {
        format!(
            "Bubblewrap: {requirement} requires 'slirp4netns' ({slirp4netns}): {error}. \
             Install slirp4netns or {}.",
            use_case.remedy()
        )
    })?;
    if !slirp.status.success() {
        return Err(format!(
            "Bubblewrap: {requirement} requires a working slirp4netns installation \
             ({slirp4netns} --version exited with {})",
            slirp.status
        ));
    }

    let unshare_path = tools.unshare.display();
    let unshare =
        run_probe(command(&tools.unshare, &["--help"]), "unshare", budget).map_err(|error| {
            format!(
                "Bubblewrap: {requirement} requires util-linux 'unshare' ({unshare_path}): \
                 {error}"
            )
        })?;
    if !unshare.status.success()
        || !unshare.stdout.contains("--map-current-user")
        || !unshare.stdout.contains("--keep-caps")
    {
        return Err(format!(
            "Bubblewrap: {requirement} requires util-linux unshare with \
             --map-current-user and --keep-caps support ({unshare_path})"
        ));
    }

    // A broken tool must fail here rather than deep inside supervisor startup.
    for (binary, path, probe, has_backend) in tools.tool_probes() {
        let output = run_probe(command(path, &[probe]), binary, budget).map_err(|error| {
            format!(
                "Bubblewrap: {requirement} requires '{binary}' ({}) to enforce {}: {error}",
                path.display(),
                use_case.mechanism()
            )
        })?;
        if !output.status.success() {
            return Err(format!(
                "Bubblewrap: {requirement} requires a working '{binary}' installation \
                 ({} {probe} exited with {})",
                path.display(),
                output.status
            ));
        }
        // Presence is not enough: the binary can work while its backend is one
        // this supervisor cannot drive.
        if has_backend {
            iptables_backend_is_usable(
                binary,
                path,
                &output.stdout,
                Path::new(XTABLES_LOCK_PATH),
                use_case,
            )?;
        }
    }
    Ok(())
}

/// Whether `binary`'s backend can install rules from the unprivileged supervisor.
///
/// The supervisor runs under `unshare --user --map-current-user`, so it keeps the
/// caller's uid: its capabilities apply inside the new user namespace, not to
/// root-owned files in the initial one. The legacy backend opens
/// [`XTABLES_LOCK_PATH`] before touching any table, so on a stock host (root-owned
/// `/run`, no lock file) it fails with `EACCES` and `set -e` kills the supervisor
/// at the first rule. `nf_tables` takes no lock.
///
/// The banner alone cannot decide this: legacy *does* work where the lock is
/// reachable (as root, or with a writable lock). So the backend picks the
/// question, and for legacy the lock itself is tested.
fn iptables_backend_is_usable(
    binary: &str,
    path: &Path,
    banner: &str,
    lock: &Path,
    use_case: PrivateNetworkUse,
) -> Result<(), String> {
    if banner.contains("nf_tables") {
        return Ok(());
    }
    if lock_is_writable(lock) {
        return Ok(());
    }

    // A pre-1.8 banner carries no marker at all; those builds are legacy-only.
    Err(format!(
        "Bubblewrap: {} requires an iptables backend the sandbox supervisor can \
         drive without privilege, but '{binary}' ({}) resolves to the legacy backend ({}) and \
         '{}' is not writable by this user. The {} rules are installed by an \
         unprivileged supervisor in a user namespace, which keeps the caller's uid, so the \
         root-owned lock is unreachable and every rule would fail. Select the nf_tables \
         backend (for example: update-alternatives --set {binary} /usr/sbin/{binary}-nft), \
         or make '{}' writable.",
        use_case.requirement(),
        path.display(),
        banner.trim(),
        lock.display(),
        use_case.mechanism(),
        lock.display()
    ))
}

/// Whether the legacy backend could take its lock as the current user.
///
/// The lock is created on first use, so an absent file makes the *directory* the
/// thing that must be writable. `access` tests the real uid — the uid the
/// supervisor itself runs under.
fn lock_is_writable(lock: &Path) -> bool {
    let target = if lock.exists() {
        lock
    } else {
        match lock.parent() {
            Some(parent) => parent,
            None => return false,
        }
    };
    access(target, AccessFlags::W_OK).is_ok()
}

/// Cap on how much component stderr is quoted into a diagnostic.
///
/// A wedged component can write without bound, and this is read from `Drop`, so
/// the read itself must be bounded rather than trimmed after the fact.
const MAX_STDERR_TAIL: u64 = 2048;

/// Last [`MAX_STDERR_TAIL`] bytes of `path`, phrased for an error message.
///
/// The tail, not the head: whatever actually killed the component is written
/// last, and a truncated head would quote its startup banner instead.
fn stderr_detail(path: &std::path::Path) -> String {
    let text = read_stderr_tail(path);
    let text = text.trim();
    if text.is_empty() {
        return "no stderr output".to_string();
    }
    format!("stderr: {text}")
}

fn read_stderr_tail(path: &std::path::Path) -> String {
    let Ok(mut file) = File::open(path) else {
        return String::new();
    };
    let len = file.metadata().map(|metadata| metadata.len()).unwrap_or(0);
    if len > MAX_STDERR_TAIL && file.seek(SeekFrom::End(-(MAX_STDERR_TAIL as i64))).is_err() {
        return String::new();
    }
    let mut buffer = Vec::new();
    if file.take(MAX_STDERR_TAIL).read_to_end(&mut buffer).is_err() {
        return String::new();
    }
    // Seeking to a byte offset can land mid-character; lossy keeps the rest
    // readable instead of discarding the whole tail.
    String::from_utf8_lossy(&buffer).into_owned()
}

fn wait_for_file(
    path: impl AsRef<std::path::Path>,
    child: &mut Supervisor,
    stderr_path: &std::path::Path,
    component: &str,
    timeout: Duration,
) -> Result<(), String> {
    let path = path.as_ref();
    let deadline = Instant::now() + timeout;
    loop {
        if fs::metadata(path).is_ok_and(|metadata| metadata.len() > 0) {
            return Ok(());
        }
        if let Some(status) = child.poll().map_err(|error| {
            format!("Bubblewrap: failed to inspect {component} startup: {error}")
        })? {
            return Err(format!(
                "Bubblewrap: {component} exited during startup ({status}): {}",
                stderr_detail(stderr_path)
            ));
        }
        if Instant::now() >= deadline {
            // Include whatever the component wrote to stderr: on a timeout it
            // is usually the only evidence of *why* startup stalled, and the
            // process is still alive so no exit status will explain it.
            return Err(format!(
                "Bubblewrap: timed out waiting for {component} after {timeout:?} ({})",
                stderr_detail(stderr_path)
            ));
        }
        thread::sleep(Duration::from_millis(10));
    }
}

/// Hand `fds` to one specific child, without exposing them process-wide.
///
/// `FD_CLOEXEC` is per-process, so clearing it on the parent's copy would leak
/// the descriptors to every concurrent `Command::spawn` -- a real window, since
/// this crate is reachable from the SDK and FFI. Clearing it in the forked child
/// instead gives them to the intended child and no one else.
///
/// The number is left as the OS assigned it, which is safe here because bwrap
/// receives it in argv (`--info-fd N`) and parses it as an integer. A child
/// that must *redirect* to the descriptor from a shell needs
/// [`remap_descriptors`] instead.
pub(crate) fn inherit_descriptors(command: &mut Command, fds: Vec<RawFd>) {
    // SAFETY: `pre_exec` runs between fork and exec, where only
    // async-signal-safe work is permitted. `fcntl` is async-signal-safe and
    // this closure allocates nothing -- `fds` is captured by move and holds
    // plain integers.
    unsafe {
        command.pre_exec(move || {
            for fd in &fds {
                fcntl(*fd, FcntlArg::F_SETFD(FdFlag::empty())).map_err(std::io::Error::from)?;
            }
            Ok(())
        });
    }
}

// The child's stdio replaces descriptors 0-2 before pre_exec runs.
pub(crate) fn above_stdio(file: File) -> Result<File, Errno> {
    let fd = fcntl(
        file.as_raw_fd(),
        FcntlArg::F_DUPFD_CLOEXEC(libc::STDERR_FILENO + 1),
    )?;

    // SAFETY: fcntl returned a new descriptor that nothing else owns.
    Ok(unsafe { File::from_raw_fd(fd) })
}

pub(crate) fn pipe_above_stdio() -> Result<(OwnedFd, OwnedFd), String> {
    let (reader, writer) =
        pipe2(OFlag::O_CLOEXEC).map_err(|error| format!("Bubblewrap: pipe failed: {error}"))?;
    let lift = |end: OwnedFd| {
        above_stdio(File::from(end))
            .map(OwnedFd::from)
            .map_err(|error| format!("Bubblewrap: failed to move a pipe above stdio: {error}"))
    };
    Ok((lift(reader)?, lift(writer)?))
}

/// Hand `mapping` to one specific child at fixed, known descriptor numbers.
///
/// Two problems are solved together. `FD_CLOEXEC` is per-process, so clearing
/// it on the parent's copy would leak the descriptors to every concurrent
/// `Command::spawn` -- a real window, since this crate is reachable from the
/// SDK and FFI. And an OS-assigned descriptor number cannot be named from
/// `/bin/sh`: dash rejects `>&$fd` and `<&$fd` for any descriptor >= 10 with
/// `Bad fd number` at *parse* time, so interpolating a raw number breaks the
/// supervisor as soon as the parent holds enough open files.
///
/// `dup2` in the forked child solves both: it clears `FD_CLOEXEC` on the new
/// descriptor only, and it puts that descriptor on a number the script can
/// hardcode. The originals stay CLOEXEC and close at exec.
fn remap_descriptors<const N: usize>(command: &mut Command, mapping: [(RawFd, RawFd); N]) {
    // SAFETY: `pre_exec` runs between fork and exec, where only
    // async-signal-safe work is permitted. `fcntl` and `dup2` are both
    // async-signal-safe and this closure allocates nothing -- `mapping` is a
    // fixed-size array of plain integers captured by move, and the staging
    // buffer is a fixed-size array too.
    unsafe {
        command.pre_exec(move || {
            // Stage every source above the target range before landing any of
            // them: a direct `dup2` could otherwise clobber a source that
            // happens to already sit on a later target.
            let mut staged = [-1; N];
            for (index, (source, _)) in mapping.iter().enumerate() {
                staged[index] = fcntl(*source, FcntlArg::F_DUPFD_CLOEXEC(FD_STAGING_BASE))
                    .map_err(std::io::Error::from)?;
            }
            for (index, (_, target)) in mapping.iter().enumerate() {
                dup2(staged[index], *target).map_err(std::io::Error::from)?;
            }
            Ok(())
        });
    }
}

fn set_nonblocking(fd: RawFd) -> Result<(), String> {
    let flags = fcntl(fd, FcntlArg::F_GETFL)
        .map_err(|error| format!("Bubblewrap: failed to read descriptor flags: {error}"))?;
    let flags = OFlag::from_bits_truncate(flags);
    fcntl(fd, FcntlArg::F_SETFL(flags | OFlag::O_NONBLOCK))
        .map(|_| ())
        .map_err(|error| format!("Bubblewrap: failed to make descriptor nonblocking: {error}"))
}

pub(crate) fn startup_output(
    child: &mut Child,
    pty: Option<&crate::mxc_pty::LivePty>,
) -> Result<String, String> {
    if let Some(pty) = pty {
        let output = pty
            .read_available_output(64 * 1024)
            .map_err(|error| format!("Bubblewrap: failed to read startup PTY output: {error}"))?;
        return Ok(String::from_utf8_lossy(&output).trim().to_string());
    }
    let Some(stderr) = child.stderr.as_mut() else {
        return Ok(String::new());
    };
    set_nonblocking(stderr.as_raw_fd())?;
    let mut output = Vec::new();
    let mut buffer = [0; 4096];
    while output.len() < 64 * 1024 {
        match stderr.read(&mut buffer) {
            Ok(0) => break,
            Ok(count) => output.extend_from_slice(&buffer[..count]),
            Err(error) if error.kind() == ErrorKind::WouldBlock => break,
            Err(error) => {
                return Err(format!(
                    "Bubblewrap: failed to read startup stderr: {error}"
                ))
            }
        }
    }
    Ok(String::from_utf8_lossy(&output).trim().to_string())
}

/// The namespace supervisor and the process group it leads.
///
/// The leader stays unreaped until its group has been swept. [`group_kill`]
/// signals the saved PID and group ID directly, so reaping first would let
/// Linux reuse that ID for an unrelated process before the sweep runs.
struct Supervisor {
    child: Child,
    exit: Option<ExitStatus>,
}

impl Supervisor {
    fn new(child: Child) -> Self {
        Self { child, exit: None }
    }

    fn id(&self) -> u32 {
        self.child.id()
    }

    /// The exit status once the supervisor has exited.
    ///
    /// Observing the exit also sweeps the group: a blocked `nsenter`, `ip` or
    /// restore child must not outlive a supervisor that died first.
    fn poll(&mut self) -> std::io::Result<Option<ExitStatus>> {
        if self.exit.is_none() && has_exited_unreaped(self.child.id())? {
            self.terminate()?;
        }
        Ok(self.exit)
    }

    /// Kill the supervisor's whole process group, then reap the leader.
    ///
    /// The leader is signalled before the sweep (see [`group_kill`]), so a
    /// woken shell cannot start a child the sweep misses.
    fn terminate(&mut self) -> std::io::Result<ExitStatus> {
        if let Some(status) = self.exit {
            return Ok(status);
        }
        group_kill(&mut self.child)?;
        let status = self.child.wait()?;
        self.exit = Some(status);
        Ok(status)
    }
}

/// Whether `pid` has exited without reaping it.
pub(crate) fn has_exited_unreaped(pid: u32) -> std::io::Result<bool> {
    waitid(
        Id::Pid(Pid::from_raw(pid as i32)),
        WaitPidFlag::WEXITED | WaitPidFlag::WNOHANG | WaitPidFlag::WNOWAIT,
    )
    .map(|status| status != WaitStatus::StillAlive)
    .map_err(std::io::Error::from)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::bwrap_common::bwrap_command::{COMPAT_RUN_LINK, COMPAT_RUN_TARGET};

    #[test]
    fn child_information_failure_keeps_the_launcher_unreaped_for_cleanup() {
        let mut startup = BwrapStartup {
            info_reader: File::open("/dev/null").expect("empty child information"),
            info_writer: None,
            gate_reader: None,
            gate_writer: None,
            inheritable: Vec::new(),
            _pins: Vec::new(),
        };
        let mut child = Command::new("sh")
            .args(["-c", "exit 7"])
            .spawn()
            .expect("start failing launcher");
        let result = startup.child_pid(&child);
        let exited_unreaped = has_exited_unreaped(child.id());
        let status = child.wait().expect("reap launcher");

        assert!(result
            .expect_err("missing child information must fail startup")
            .contains("bwrap exited before publishing child information"));
        assert!(
            matches!(exited_unreaped, Ok(true)),
            "startup reaped the process-group leader before cleanup: {exited_unreaped:?}"
        );
        assert_eq!(status.code(), Some(7));
    }

    #[test]
    fn startup_stderr_returns_the_child_diagnostic() {
        let mut child = Command::new("sh")
            .args(["-c", "printf 'namespace refused\\n' >&2"])
            .stderr(Stdio::piped())
            .spawn()
            .expect("start diagnostic child");
        assert!(child.wait().expect("wait for diagnostic child").success());
        assert_eq!(
            startup_output(&mut child, None).expect("read startup stderr"),
            "namespace refused"
        );
    }

    /// The reported concern: a hostname proxy resolves through the host's
    /// resolver during setup, before the script timeout applies, so an
    /// unresponsive resolver would stall a run that never started.
    #[test]
    fn work_that_outlives_its_deadline_is_abandoned() {
        let started = Instant::now();
        let waited = with_deadline("mxc-test-deadline", Duration::from_millis(50), || {
            thread::sleep(Duration::from_secs(30));
            "an answer that arrives too late"
        })
        .expect("the worker thread starts");

        assert!(
            matches!(waited, Err(mpsc::RecvTimeoutError::Timeout)),
            "the wait must end on the deadline rather than on the work"
        );
        assert!(
            started.elapsed() < Duration::from_secs(5),
            "the caller waited {:?}, so the deadline did not bound it",
            started.elapsed()
        );
    }

    #[test]
    fn work_that_finishes_within_its_deadline_returns_its_answer() {
        let waited = with_deadline("mxc-test-deadline", Duration::from_secs(30), || 7)
            .expect("the worker thread starts");

        assert_eq!(waited, Ok(7));
    }

    /// The bound is only useful if it is longer than a working resolver's
    /// slow path; see [`RESOLVE_TIMEOUT`].
    #[test]
    fn the_resolver_bound_survives_one_dead_nameserver() {
        assert!(RESOLVE_TIMEOUT > Duration::from_secs(10));
    }

    #[test]
    fn gateway_constants_agree() {
        // The rule and the pin are written from the address; the URL rewrite
        // from the string. A drift between them would open one endpoint and
        // point the workload at another.
        assert_eq!(SLIRP_HOST_GATEWAY_IP.to_string(), SLIRP_HOST_GATEWAY);
        // The reserved-range check is written from the octets, the diagnostic
        // from the string; the gateway must fall inside the range it names.
        assert!(SLIRP_NETWORK.starts_with(&format!(
            "{}.{}.{}.",
            SLIRP_NETWORK_OCTETS[0], SLIRP_NETWORK_OCTETS[1], SLIRP_NETWORK_OCTETS[2]
        )));
        assert_eq!(SLIRP_HOST_GATEWAY_IP.octets()[..3], SLIRP_NETWORK_OCTETS);
    }

    /// A hostname answering with the gateway is the sharp case: the address is
    /// routable on the host, so nothing else flags it, but inside the namespace
    /// it is the route to host loopback. Pinning it would hand the workload an
    /// unrelated host service on the proxy port.
    #[test]
    fn egress_rejects_a_hostname_resolving_into_the_sandbox_network() {
        let address = ProxyAddress::new("proxy.example".into(), 3128);
        let error = SandboxProxy::resolve_with(&address, resolver([10, 0, 2, 2]))
            .expect_err("the slirp gateway must not be pinned as if it were a host address");

        let ProxyResolveError::Rejected(error) = error else {
            panic!("a reserved answer is a policy refusal: {error}");
        };
        assert!(
            error.contains("10.0.2.0/24") && error.contains("127.0.0.1"),
            "error should name the reserved range and the supported alternative: {error}"
        );
    }

    /// The sandbox's own tap address, and a plain neighbour, are wrong for the
    /// same reason -- so the whole range is rejected, not just the gateway.
    #[test]
    fn egress_rejects_every_address_in_the_sandbox_network() {
        for octets in [[10, 0, 2, 3], [10, 0, 2, 100], [10, 0, 2, 50]] {
            let address = ProxyAddress::new("proxy.example".into(), 3128);
            assert!(
                SandboxProxy::resolve_with(&address, resolver(octets)).is_err(),
                "{octets:?} is on-link inside the namespace and cannot name a host endpoint"
            );

            let literal = ProxyAddress::new(Ipv4Addr::from(octets).to_string(), 3128);
            assert!(
                SandboxProxy::resolve(&literal).is_err(),
                "{octets:?} must be rejected as a literal too, not only as an answer"
            );
        }
    }

    /// The rejection must not swallow the translation it sits next to: a
    /// loopback answer is *meant* to become the gateway.
    #[test]
    fn rejecting_the_sandbox_network_leaves_the_loopback_translation_intact() {
        let address = ProxyAddress::new("proxy.example".into(), 3128);
        let resolved = SandboxProxy::resolve_with(&address, resolver([127, 0, 0, 1]))
            .expect("a loopback answer is translated, not rejected");

        assert_eq!(resolved.egress().ip, SLIRP_HOST_GATEWAY_IP);
    }

    /// The neighbouring /24 is ordinary host space, so the check must not
    /// widen past the network slirp actually assigns.
    #[test]
    fn egress_accepts_an_address_just_outside_the_sandbox_network() {
        let address = ProxyAddress::new("proxy.example".into(), 3128);
        let resolved = SandboxProxy::resolve_with(&address, resolver([10, 0, 3, 2]))
            .expect("10.0.3.2 is a normal routable answer");

        assert_eq!(resolved.egress().ip, Ipv4Addr::new(10, 0, 3, 2));
    }

    #[test]
    fn egress_opens_the_gateway_for_a_loopback_literal() {
        // A literal has no name to pin, so the URL is rewritten and the rule
        // must open the rewritten address, not the original loopback.
        let address = ProxyAddress::new("127.0.0.1".into(), 8080);
        let resolved = SandboxProxy::resolve(&address).unwrap();

        assert_eq!(resolved.address().host(), SLIRP_HOST_GATEWAY);
        assert_eq!(resolved.egress().ip.to_string(), SLIRP_HOST_GATEWAY);
        assert_eq!(resolved.egress().port, 8080);
        assert!(resolved.egress().pin().is_none());
    }

    #[test]
    fn egress_accepts_a_routable_ipv4_proxy() {
        let address = ProxyAddress::new("10.1.2.3".into(), 3128);
        let resolved = SandboxProxy::resolve(&address).unwrap();

        assert_eq!(resolved.address().host(), "10.1.2.3");
        assert_eq!(resolved.egress().ip.to_string(), "10.1.2.3");
        assert_eq!(resolved.egress().port, 3128);
        assert!(resolved.egress().pin().is_none());
    }

    /// A resolver that answers every name with `ip`, so pin decisions can be
    /// tested without a lookup the test does not control.
    fn resolver(ip: [u8; 4]) -> impl Fn(&str, u16) -> Result<Ipv4Addr, ProxyResolveError> {
        move |_, _| Ok(Ipv4Addr::from(ip))
    }

    #[test]
    fn pins_a_hostname_and_keeps_its_url() {
        // The workload must present the configured name -- proxy-auth realms
        // and Host headers are keyed on it -- so the name is pinned rather
        // than rewritten to an address.
        let address = ProxyAddress::from_url(
            "http://proxy.corp.example:3128/",
            "proxy.corp.example".into(),
            3128,
        );
        let resolved = SandboxProxy::resolve_with(&address, resolver([10, 1, 2, 3])).unwrap();

        assert_eq!(
            resolved.address().to_url(),
            "http://proxy.corp.example:3128/"
        );

        let pin = resolved.egress().pin().expect("hostname must be pinned");
        assert_eq!(pin.hostname(), "proxy.corp.example");
        assert_eq!(pin.ip().to_string(), "10.1.2.3");
        assert_eq!(resolved.egress().ip.to_string(), "10.1.2.3");
    }

    #[test]
    fn pins_a_loopback_hostname_to_the_gateway() {
        // slirp gives the sandbox its own loopback, so a name resolving to the
        // host's loopback must be pinned to the gateway -- pinning it verbatim
        // would aim the workload at itself.
        let address = ProxyAddress::from_url("http://proxy.local:3128", "proxy.local".into(), 3128);
        let resolved = SandboxProxy::resolve_with(&address, resolver([127, 0, 1, 1])).unwrap();

        let pin = resolved.egress().pin().expect("hostname must be pinned");
        assert_eq!(pin.ip().to_string(), SLIRP_HOST_GATEWAY);
        assert_eq!(resolved.egress().ip.to_string(), SLIRP_HOST_GATEWAY);
    }

    #[test]
    fn rewrites_localhost_instead_of_pinning_it() {
        // `localhost` is reserved to loopback (RFC 6761). A pin is sandbox
        // wide, so pinning it would redirect the workload's own loopback
        // traffic to the host.
        let address = ProxyAddress::from_url("http://localhost:3128/", "localhost".into(), 3128);
        let resolved =
            SandboxProxy::resolve_with(&address, |_, _| panic!("localhost must not be resolved"))
                .unwrap();

        assert_eq!(resolved.address().host(), SLIRP_HOST_GATEWAY);
        assert!(resolved.egress().pin().is_none());
        assert_eq!(resolved.egress().ip.to_string(), SLIRP_HOST_GATEWAY);
    }

    /// The pre-flight check exists to fail fast, not to duplicate work: a name
    /// must survive it untouched so `run` performs the only lookup, whose
    /// answer is also the pin the sandbox is given.
    #[test]
    fn the_pre_flight_check_defers_every_verdict_that_needs_a_lookup() {
        // `.invalid` is reserved as never-resolvable (RFC 2606), so a real
        // lookup here could only fail -- passing proves none was made.
        let named = ProxyAddress::new("proxy.this-name-cannot-exist.invalid".into(), 3128);
        assert!(
            SandboxProxy::check_without_resolving(&named).is_ok(),
            "a hostname's verdict belongs to the lookup in `run`"
        );
    }

    #[test]
    fn the_pre_flight_check_still_rejects_what_no_lookup_could_rescue() {
        // Decided by the configured address alone, so deferring these would
        // only move the same rejection past a started proxy.
        for unusable in [
            ProxyAddress::new("[::1]".into(), 3128),
            ProxyAddress::new("2001:db8::1".into(), 3128),
            ProxyAddress::new("127.0.0.1".into(), 0),
        ] {
            assert!(
                SandboxProxy::check_without_resolving(&unusable).is_err(),
                "endpoint '{}' is unusable regardless of DNS",
                unusable.host()
            );
        }
    }

    /// The effective intent is the deepest entry covering the file, so an
    /// ancestor denial masks it and a grant beneath that denial wins it back.
    #[test]
    fn a_denied_ancestor_counts_as_denying_the_hosts_file() {
        let denied_parent = ContainerPolicy {
            denied_paths: vec!["/etc".into()],
            ..Default::default()
        };
        assert!(hosts_file_is_denied(&denied_parent));

        let regranted = ContainerPolicy {
            denied_paths: vec!["/etc".into()],
            readonly_paths: vec![SANDBOX_HOSTS_PATH.into()],
            ..Default::default()
        };
        assert!(
            !hosts_file_is_denied(&regranted),
            "a more specific grant beneath the denial takes effect"
        );

        let unrelated = ContainerPolicy {
            denied_paths: vec!["/etc/hostname".into(), "/etc/hosts.allow".into()],
            ..Default::default()
        };
        assert!(
            !hosts_file_is_denied(&unrelated),
            "a sibling with a shared prefix must not be mistaken for the file"
        );
    }

    #[test]
    fn pins_a_routable_hostname_to_its_resolved_address() {
        // Only a loopback answer is redirected to the gateway; a routable one
        // is reached directly through slirp.
        assert_eq!(
            sandbox_facing_ip(Ipv4Addr::new(10, 1, 2, 3)),
            Ipv4Addr::new(10, 1, 2, 3)
        );
        assert_eq!(
            sandbox_facing_ip(Ipv4Addr::new(127, 0, 0, 1)),
            SLIRP_HOST_GATEWAY_IP
        );
        // `/etc/hosts` can map a name to `0.0.0.0`, which names the host the
        // same way loopback does -- and which the IP-literal path rewrites.
        assert_eq!(
            sandbox_facing_ip(Ipv4Addr::UNSPECIFIED),
            SLIRP_HOST_GATEWAY_IP
        );
    }

    #[test]
    fn egress_rejects_an_ipv6_proxy() {
        // Rules are IPv4-only, so an IPv6 endpoint would never be opened.
        let loopback = ProxyAddress::new("[::1]".into(), 8080);
        let error = SandboxProxy::resolve(&loopback).unwrap_err();
        assert!(
            error.message().contains("IPv4"),
            "error should explain the IPv4 requirement: {error}"
        );

        let routable = ProxyAddress::new("2001:db8::1".into(), 8080);
        assert!(SandboxProxy::resolve(&routable).is_err());
    }

    #[test]
    fn egress_rejects_an_unresolvable_hostname() {
        // `.invalid` is reserved by RFC 2606 and never resolves, so a name
        // that cannot be pinned must fail loudly rather than yield a rule the
        // sandbox can never reach.
        let address = ProxyAddress::from_url(
            "http://proxy.corp.invalid:3128",
            "proxy.corp.invalid".into(),
            3128,
        );
        let error = SandboxProxy::resolve(&address).unwrap_err();

        // A lookup failure is a host fault, not a refusal of the policy.
        let ProxyResolveError::Lookup(error) = error else {
            panic!("an unresolvable name is a lookup failure: {error}");
        };
        assert!(
            error.contains("proxy.corp.invalid"),
            "error should name the offending host: {error}"
        );
    }

    #[test]
    fn a_failed_lookup_is_not_reported_as_a_refusal() {
        let address = ProxyAddress::new("proxy.example".into(), 3128);
        let error = SandboxProxy::resolve_with(&address, |_, _| {
            Err(ProxyResolveError::Lookup("timed out".into()))
        })
        .unwrap_err();

        assert!(matches!(error, ProxyResolveError::Lookup(_)), "{error}");
    }

    #[test]
    fn static_rejections_are_refusals() {
        for host in ["[::1]", "2001:db8::1", "10.0.2.2"] {
            let address = ProxyAddress::new(host.into(), 8080);
            let error = SandboxProxy::resolve(&address).unwrap_err();
            assert!(
                matches!(error, ProxyResolveError::Rejected(_)),
                "{host}: {error}"
            );
        }
    }

    /// `::1` used to be rewritten to the IPv4 gateway, which handed the sandbox
    /// an address the proxy never listens on: an IPv6-loopback listener does
    /// not accept the IPv4 connection slirp's gateway produces. Rejecting at
    /// policy time beats failing at connect time.
    #[test]
    fn rejects_an_ipv6_loopback_proxy_instead_of_translating_it() {
        for host in ["[::1]", "::1"] {
            let address = ProxyAddress::new(host.into(), 8080);
            let error = SandboxProxy::resolve(&address).unwrap_err();

            assert!(
                error.message().contains("IPv6 loopback"),
                "error should name the unreachable address family: {error}"
            );
        }
    }

    /// The rejection must not swallow `::`: a dual-stack wildcard listener does
    /// accept the gateway's IPv4 connection, so it still translates.
    #[test]
    fn ipv6_loopback_rejection_leaves_the_ipv6_wildcard_translatable() {
        let address = ProxyAddress::new("[::]".into(), 8080);
        let translated = SandboxProxy::resolve(&address).unwrap();

        assert_eq!(translated.address().host(), SLIRP_HOST_GATEWAY);
    }

    #[test]
    fn egress_rejects_a_zero_port() {
        let address = ProxyAddress::new("10.0.2.2".into(), 0);
        let error = SandboxProxy::resolve(&address).unwrap_err();

        assert!(
            error.message().contains("non-zero"),
            "error should explain the port requirement: {error}"
        );
    }

    /// The supervisor script with the lock-wait flag elided.
    ///
    /// The flag is an operational detail, not part of the egress policy these
    /// tests pin. Normalising it away keeps a change in lock handling from
    /// failing every ordering assertion -- while
    /// `every_rule_command_waits_for_the_xtables_lock` still asserts it is
    /// present on all of them.
    fn normalised_script() -> String {
        SUPERVISOR_SCRIPT.replace(r#" -w "$lock_wait""#, "")
    }

    /// The pin a hostname proxy produces, for the hosts-file tests.
    fn test_pin() -> ProxyHostPin {
        ProxyAddress::new("proxy.example".into(), 3128)
            .host_pin(IpAddr::V4(SLIRP_HOST_GATEWAY_IP))
            .expect("hostname must be pinnable")
            .expect("a hostname needs a pin")
    }

    #[test]
    fn pinned_hosts_file_puts_the_pin_first() {
        // Ordering is not sufficient on its own (see the duplicate-name tests
        // below), but the pin still leads the file so the intent is legible.
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("hosts");
        write_pinned_hosts(&path, &test_pin(), None).unwrap();

        let contents = fs::read_to_string(&path).unwrap();
        assert_eq!(
            contents.lines().next().unwrap(),
            format!("{SLIRP_HOST_GATEWAY} proxy.example")
        );
    }

    /// The reason the name is stripped rather than merely outranked: glibc
    /// returns *every* matching hosts line to `getaddrinfo`, which re-sorts
    /// them by RFC 6724 and promotes a loopback address above the pin. A
    /// surviving duplicate is therefore tried first, sending the workload to an
    /// address the egress chain never authorized -- or back into the sandbox.
    #[test]
    fn a_competing_mapping_for_the_pinned_name_is_removed() {
        let stripped = strip_host_from_hosts(
            "127.0.0.1 localhost\n127.0.0.1 proxy.example\n10.9.9.9 proxy.example\n",
            "proxy.example",
        );
        assert_eq!(stripped, "127.0.0.1 localhost\n");
    }

    #[test]
    fn stripping_the_pinned_name_keeps_the_other_names_on_its_line() {
        // Dropping the whole line would cost the sandbox `localhost`.
        let stripped =
            strip_host_from_hosts("127.0.0.1 localhost proxy.example\n", "proxy.example");
        assert_eq!(stripped, "127.0.0.1 localhost\n");
    }

    #[test]
    fn stripping_the_pinned_name_ignores_case() {
        // DNS names are case-insensitive, so a differently cased duplicate
        // would otherwise survive and reintroduce the competing mapping.
        let stripped = strip_host_from_hosts("127.0.0.1 Proxy.EXAMPLE\n", "proxy.example");
        assert_eq!(stripped, "");
    }

    #[test]
    fn stripping_leaves_unrelated_lines_byte_for_byte() {
        // Real hosts files are tab-aligned; normalizing them would churn the
        // sandbox's file for no benefit.
        let original = "127.0.0.1\tlocalhost\n\n# a comment\n::1\tip6-localhost ip6-loopback\n";
        assert_eq!(strip_host_from_hosts(original, "proxy.example"), original);
    }

    #[test]
    fn stripping_an_entire_entry_keeps_its_trailing_comment() {
        let stripped =
            strip_host_from_hosts("10.9.9.9 proxy.example # operator note\n", "proxy.example");
        assert_eq!(stripped, "# operator note\n");
    }

    #[test]
    fn the_written_hosts_file_has_exactly_one_mapping_for_the_pinned_name() {
        // End-to-end twin of the unit tests above, against the real host file.
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("hosts");
        write_pinned_hosts(&path, &test_pin(), None).unwrap();

        let written = fs::read_to_string(&path).unwrap();
        let matches = written
            .lines()
            .filter(|line| {
                let body = line.split('#').next().unwrap_or("");
                body.split_whitespace()
                    .skip(1)
                    .any(|name| name.eq_ignore_ascii_case("proxy.example"))
            })
            .count();
        assert_eq!(
            matches, 1,
            "exactly one mapping may survive for the pinned name:\n{written}"
        );
    }

    #[test]
    fn pinned_hosts_file_keeps_the_host_entries() {
        // Dropping them would cost the sandbox `localhost`, which workloads
        // and the loopback exemption both rely on.
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("hosts");
        write_pinned_hosts(&path, &test_pin(), None).unwrap();

        let written = fs::read_to_string(&path).unwrap();
        let host_file = fs::read_to_string(SANDBOX_HOSTS_PATH).unwrap_or_default();
        for line in host_file.lines().filter(|line| {
            // A line mapping the pinned name is *expected* to be rewritten;
            // every other line must survive untouched.
            !line.trim().is_empty()
                && !line
                    .split('#')
                    .next()
                    .unwrap_or("")
                    .split_whitespace()
                    .skip(1)
                    .any(|name| name.eq_ignore_ascii_case("proxy.example"))
        }) {
            assert!(
                written.contains(line),
                "host entry should be preserved: {line}"
            );
        }
    }

    #[test]
    fn hosts_bind_is_applied_after_policy_mounts() {
        // bwrap applies mounts in order and the last at a path wins, so the
        // pin must land past every policy mount -- including one that would
        // otherwise expose the host's own /etc/hosts.
        let mut args = vec![
            "--ro-bind-try".to_string(),
            "/etc".to_string(),
            "/etc".to_string(),
            "--bind".to_string(),
            "/etc/hosts".to_string(),
            "/etc/hosts".to_string(),
        ];
        args.extend(command_tail());
        insert_hosts_bind(&mut args, 17).unwrap();

        let pin = args
            .windows(3)
            .position(|window| window == ["--ro-bind-data", "17", SANDBOX_HOSTS_PATH])
            .expect("pin bind should be present");
        let policy = args
            .windows(3)
            .position(|window| window == ["--bind", "/etc/hosts", "/etc/hosts"])
            .expect("policy mount should be retained");
        let separator = command_separator(&args).unwrap();

        assert!(pin > policy, "pin must be applied after the policy mount");
        assert!(pin < separator, "pin must precede the command separator");
    }

    #[test]
    fn hosts_bind_reports_an_overridden_policy_mount() {
        // Silently shadowing a user's own /etc/hosts mount would make the
        // sandbox's view of the file inexplicable from the config alone.
        let mut args = vec![
            "--bind".to_string(),
            "/custom/hosts".to_string(),
            "/etc/hosts".to_string(),
        ];
        args.extend(command_tail());
        assert!(insert_hosts_bind(&mut args, 17).unwrap());

        let mut untouched = vec!["--ro-bind-try".to_string()];
        untouched.extend(command_tail());
        assert!(!insert_hosts_bind(&mut untouched, 17).unwrap());
    }

    #[test]
    fn hosts_bind_requires_a_command_separator() {
        // Appending blindly to an argument list with no separator would pass
        // the bind to the workload as arguments and leave it unpinned.
        let mut args = vec!["--ro-bind-try".to_string(), "/etc".to_string()];
        assert!(insert_hosts_bind(&mut args, 17).is_err());
    }

    /// The stub resolver the issue reports: readable inside the sandbox,
    /// unreachable from it.
    const SYSTEMD_RESOLVED_STUB: &str = "nameserver 127.0.0.53\noptions edns0 trust-ad\n\
                                         search corp.example\n";

    /// The resolver file is written from the string and the egress check reads
    /// the address. A drift between them would pin one forwarder and test the
    /// chain against another, so the warning would fire on a chain that works.
    #[test]
    fn forwarder_constants_agree() {
        assert_eq!(SLIRP_DNS_FORWARDER_IP.to_string(), SLIRP_DNS_FORWARDER);
    }

    #[test]
    fn a_loopback_stub_resolver_is_pinned() {
        assert!(resolvers_are_loopback_only(SYSTEMD_RESOLVED_STUB));
        assert!(resolvers_are_loopback_only("nameserver 127.0.0.1\n"));
    }

    /// Pinning a host whose nameserver is routable would redirect name
    /// resolution that already works.
    #[test]
    fn a_routable_resolver_is_left_alone() {
        assert!(!resolvers_are_loopback_only("nameserver 8.8.8.8\n"));
        assert!(!resolvers_are_loopback_only(
            "nameserver 127.0.0.53\nnameserver 8.8.8.8\n"
        ));
    }

    /// slirp forwards to the first IPv4 nameserver in the host's file and drops
    /// the query when there is none, so a v6-only resolver list cannot be
    /// rescued by pointing at the forwarder.
    #[test]
    fn a_resolver_list_without_an_ipv4_entry_is_left_alone() {
        assert!(!resolvers_are_loopback_only("nameserver ::1\n"));
        assert!(!resolvers_are_loopback_only("search corp.example\n"));
        assert!(!resolvers_are_loopback_only(""));
    }

    /// An address this cannot parse might be routable, and pinning over it
    /// would take away name resolution that works.
    #[test]
    fn an_unreadable_nameserver_is_left_alone() {
        assert!(!resolvers_are_loopback_only("nameserver localhost\n"));
        assert!(!resolvers_are_loopback_only("nameserver 127.0.0.999\n"));
        assert!(!resolvers_are_loopback_only("nameserver\n"));
    }

    /// glibc reads a directive only when its keyword starts the line, so an
    /// indented one names no resolver the host actually uses and the file still
    /// counts as loopback-only.
    #[test]
    fn an_indented_directive_is_not_a_nameserver() {
        assert!(!is_nameserver_line("  nameserver 8.8.8.8"));
        assert!(resolvers_are_loopback_only(
            "nameserver 127.0.0.53\n  nameserver 8.8.8.8\n"
        ));
        assert_eq!(
            render_pinned_resolv_conf("nameserver 127.0.0.53\n  nameserver 8.8.8.8\n"),
            "nameserver 10.0.2.3\n"
        );
    }

    /// glibc takes the address after the keyword and ignores the rest of the
    /// line.
    #[test]
    fn a_nameserver_line_ignores_trailing_fields() {
        assert!(resolvers_are_loopback_only(
            "nameserver 127.0.0.53 # stub\n"
        ));
    }

    /// `search` and `options` decide how a bare name is expanded and retried,
    /// so dropping them would change which names resolve.
    #[test]
    fn the_pinned_resolver_keeps_every_other_directive() {
        let pinned = render_pinned_resolv_conf(SYSTEMD_RESOLVED_STUB);

        assert_eq!(
            pinned,
            "nameserver 10.0.2.3\noptions edns0 trust-ad\nsearch corp.example\n"
        );
    }

    /// The pin can land on a path the filesystem policy never granted, so only
    /// the directives the resolver acts on cross into the sandbox.
    #[test]
    fn the_pinned_resolver_carries_no_host_commentary() {
        let pinned = render_pinned_resolv_conf(
            "# generated by something\nnameserver 127.0.0.53\ndomain corp.example\n\
             sortlist 10.0.0.0/8\nbogus-directive value\n",
        );

        assert_eq!(
            pinned,
            "nameserver 10.0.2.3\ndomain corp.example\nsortlist 10.0.0.0/8\n"
        );
    }

    /// Leaving one behind would let the resolver fall back to an address the
    /// namespace cannot reach.
    #[test]
    fn the_pinned_resolver_replaces_every_nameserver() {
        let pinned =
            render_pinned_resolv_conf("nameserver 127.0.0.53\nnameserver 127.0.0.54\n# comment\n");

        assert_eq!(pinned, "nameserver 10.0.2.3\n");
        assert_eq!(nameserver_values(&pinned).collect::<Vec<_>>(), ["10.0.2.3"]);
    }

    /// A host whose `/etc/resolv.conf` is `contents`, as a real file the
    /// decision can be run against.
    fn host_with_resolver(dir: &tempfile::TempDir, contents: &str) -> PathBuf {
        let root = std::fs::canonicalize(dir.path()).expect("tempdir canonicalizes");
        let path = root.join("resolv.conf");
        fs::write(&path, contents).expect("fixture resolver");
        path
    }

    fn buffer_logger() -> Logger {
        Logger::new(crate::mxc_common::logger::Mode::Buffer)
    }

    /// The whole decision, not just its helpers: a loopback stub is pinned to
    /// slirp's forwarder and mounted over the file the chain ends at.
    #[test]
    fn the_decision_pins_a_loopback_host() {
        let dir = tempfile::tempdir().unwrap();
        let resolver = host_with_resolver(&dir, SYSTEMD_RESOLVED_STUB);
        let mut logger = buffer_logger();

        let pin = ResolverPin::from_resolver(
            &resolver,
            &ContainerPolicy::default(),
            &[],
            None,
            &mut logger,
        )
        .expect("a loopback stub is pinned");

        assert_eq!(pin.destination, resolver);
        assert!(pin.contents.contains("nameserver 10.0.2.3"));
        assert!(pin.contents.contains("search corp.example"));
        assert!(logger.warnings().is_empty(), "{:?}", logger.warnings());
    }

    /// A host that already resolves is left alone, silently.
    #[test]
    fn the_decision_declines_a_routable_host() {
        let dir = tempfile::tempdir().unwrap();
        let resolver = host_with_resolver(&dir, "nameserver 8.8.8.8\n");
        let mut logger = buffer_logger();

        assert!(ResolverPin::from_resolver(
            &resolver,
            &ContainerPolicy::default(),
            &[],
            None,
            &mut logger
        )
        .is_none());
        assert!(logger.warnings().is_empty(), "{:?}", logger.warnings());
    }

    /// A host with no resolver file has no stub to rescue, which is not a
    /// degradation worth reporting.
    #[test]
    fn the_decision_is_silent_when_there_is_no_resolver() {
        let dir = tempfile::tempdir().unwrap();
        let absent = dir.path().join("absent.conf");
        let mut logger = buffer_logger();

        assert!(ResolverPin::from_resolver(
            &absent,
            &ContainerPolicy::default(),
            &[],
            None,
            &mut logger
        )
        .is_none());
        assert!(logger.warnings().is_empty(), "{:?}", logger.warnings());
    }

    /// The pin is spliced after every policy mount, so honouring it would hand
    /// back the file the policy masked.
    #[test]
    fn the_decision_declines_a_denied_destination() {
        let dir = tempfile::tempdir().unwrap();
        let resolver = host_with_resolver(&dir, SYSTEMD_RESOLVED_STUB);
        let policy = ContainerPolicy {
            denied_paths: vec![resolver.to_string_lossy().into_owned()],
            ..Default::default()
        };
        let mut logger = buffer_logger();

        assert!(ResolverPin::from_resolver(&resolver, &policy, &[], None, &mut logger).is_none());
        let out = logger.warnings().join("\n");
        assert!(out.contains("deniedPaths"), "must name the remedy: {out}");
    }

    #[test]
    fn resolver_pins_respect_translated_file_grants_and_masks() {
        let dir = tempfile::tempdir().unwrap();
        let resolver = host_with_resolver(&dir, SYSTEMD_RESOLVED_STUB);
        let file = resolver.to_string_lossy().into_owned();
        let parent = resolver.parent().unwrap().to_string_lossy().into_owned();
        for (intent, destination, pinned, warning) in [
            (
                FsIntent::ReadWrite,
                file.clone(),
                false,
                "mounts its own resolver",
            ),
            (FsIntent::ReadOnly, file, false, "mounts its own resolver"),
            (
                FsIntent::Denied,
                parent.clone(),
                false,
                "filesystem policy denies",
            ),
            (FsIntent::ReadOnly, parent, true, ""),
        ] {
            let mounts = vec![PolicyMount {
                source: "/run/resolvconf/resolv.conf".into(),
                destination,
                intent,
                readonly_overlay: None,
            }];
            let mut logger = buffer_logger();
            let pin = ResolverPin::from_resolver(
                &resolver,
                &ContainerPolicy::default(),
                &mounts,
                None,
                &mut logger,
            );
            assert_eq!(pin.is_some(), pinned, "{mounts:?}");
            if !pinned {
                assert!(logger.warnings().join("\n").contains(warning));
            }
        }
    }

    #[test]
    fn the_decision_declines_a_caller_supplied_resolver() {
        let dir = tempfile::tempdir().unwrap();
        let resolver = host_with_resolver(&dir, SYSTEMD_RESOLVED_STUB);
        let policy = ContainerPolicy {
            readonly_paths: vec![resolver.to_string_lossy().into_owned()],
            ..Default::default()
        };
        let mut logger = buffer_logger();

        assert!(ResolverPin::from_resolver(&resolver, &policy, &[], None, &mut logger).is_none());
        let out = logger.warnings().join("\n");
        assert!(
            out.contains("loopback"),
            "the resolver they mounted cannot be reached either: {out}"
        );
    }

    /// On a real host the grant and the resolver's own path are different
    /// spellings of the same file, and either one is the caller claiming it.
    #[test]
    fn the_decision_declines_a_caller_supplied_resolver_through_a_symlink() {
        use crate::mxc_common::models::ContainerPolicy;

        let dir = tempfile::tempdir().unwrap();
        let root = std::fs::canonicalize(dir.path()).unwrap();
        fs::create_dir_all(root.join("run/systemd/resolve")).unwrap();
        fs::create_dir_all(root.join("etc")).unwrap();
        let target = root.join("run/systemd/resolve/stub-resolv.conf");
        fs::write(&target, SYSTEMD_RESOLVED_STUB).unwrap();
        let link = root.join("etc/resolv.conf");
        std::os::unix::fs::symlink(&target, &link).unwrap();

        for grant in [link.clone(), target.clone()] {
            for policy in [
                ContainerPolicy {
                    readonly_paths: vec![grant.to_string_lossy().into_owned()],
                    ..Default::default()
                },
                ContainerPolicy {
                    readwrite_paths: vec![grant.to_string_lossy().into_owned()],
                    ..Default::default()
                },
            ] {
                let mut logger = buffer_logger();
                assert!(
                    ResolverPin::from_resolver(&link, &policy, &[], None, &mut logger).is_none(),
                    "a grant on {} is the caller claiming the resolver",
                    grant.display()
                );
            }
        }
    }

    /// A chain with no regular file at the end gives up the pin, not the run,
    /// and says why.
    #[test]
    fn the_decision_declines_an_unresolvable_chain() {
        let dir = tempfile::tempdir().unwrap();
        let root = std::fs::canonicalize(dir.path()).unwrap();
        let first = root.join("first.conf");
        let second = root.join("second.conf");
        std::os::unix::fs::symlink(&second, &first).unwrap();
        std::os::unix::fs::symlink(&first, &second).unwrap();
        let mut logger = buffer_logger();

        assert!(ResolverPin::from_resolver(
            &first,
            &ContainerPolicy::default(),
            &[],
            None,
            &mut logger
        )
        .is_none());
        let out = logger.warnings().join("\n");
        assert!(out.contains("could not be read"), "got: {out}");
    }

    /// The destination is the canonical file, so a policy denying it through an
    /// ancestor is honoured even when the host's symlink spells the path
    /// differently. An ancestor denial is used deliberately: a policy naming
    /// the destination exactly would also trip the caller-supplied-resolver
    /// check, and the test would pass without the deny comparison being right.
    #[test]
    fn the_decision_compares_policy_against_the_canonical_destination() {
        let dir = tempfile::tempdir().unwrap();
        let root = std::fs::canonicalize(dir.path()).unwrap();
        fs::create_dir_all(root.join("real")).unwrap();
        fs::write(root.join("real/stub.conf"), SYSTEMD_RESOLVED_STUB).unwrap();
        std::os::unix::fs::symlink(root.join("real"), root.join("link")).unwrap();

        let policy = ContainerPolicy {
            denied_paths: vec![root.join("real").to_string_lossy().into_owned()],
            ..Default::default()
        };
        let mut logger = buffer_logger();

        assert!(
            ResolverPin::from_resolver(
                &root.join("link/stub.conf"),
                &policy,
                &[],
                None,
                &mut logger
            )
            .is_none(),
            "a denial of the canonical directory must stop the pin reached by an alias"
        );
        let out = logger.warnings().join("\n");
        assert!(out.contains("deniedPaths"), "must name the remedy: {out}");
    }

    /// The pin improves on a resolver the sandbox already cannot reach, so a
    /// staging failure must cost the pin and not the run — the caller would
    /// otherwise lose a sandbox that was going to start.
    #[test]
    fn a_staging_failure_gives_up_the_pin_rather_than_the_run() {
        let dir = tempfile::tempdir().unwrap();
        let resolver = host_with_resolver(&dir, SYSTEMD_RESOLVED_STUB);
        let mut logger = buffer_logger();
        let pin = ResolverPin::from_resolver(
            &resolver,
            &ContainerPolicy::default(),
            &[],
            None,
            &mut logger,
        )
        .expect("a loopback stub is pinned");

        let staged = stage_resolver(
            Some(&pin),
            Path::new("/mxc-absent-staging-dir"),
            &mut logger,
        );

        assert!(
            staged.is_none(),
            "a failed stage leaves the sandbox unpinned"
        );
        let out = logger.warnings().join("\n");
        assert!(
            out.contains("loopback nameserver"),
            "the degradation must be reported: {out}"
        );
        assert!(
            logger.get_buffer().is_empty(),
            "the warning must travel as a retained warning, not as buffer output"
        );
    }

    #[test]
    fn staging_reports_the_pin_it_mounted() {
        let dir = tempfile::tempdir().unwrap();
        let resolver = host_with_resolver(&dir, SYSTEMD_RESOLVED_STUB);
        let mut logger = buffer_logger();
        let pin = ResolverPin::from_resolver(
            &resolver,
            &ContainerPolicy::default(),
            &[],
            None,
            &mut logger,
        )
        .expect("a loopback stub is pinned");

        let staging = tempfile::tempdir().unwrap();
        let (source, destination) = stage_resolver(Some(&pin), staging.path(), &mut logger)
            .expect("staging into a real dir");

        assert_eq!(fs::read_to_string(&source).unwrap(), pin.contents);
        assert_eq!(destination, resolver.to_string_lossy());
        assert!(
            logger.warnings().is_empty(),
            "a successful pin is not a degradation: {:?}",
            logger.warnings()
        );
    }

    /// A host whose resolver already works is never pinned, and that is not a
    /// degradation worth reporting.
    #[test]
    fn staging_nothing_is_silent() {
        let dir = tempfile::tempdir().unwrap();
        let mut logger = buffer_logger();

        assert!(stage_resolver(None, dir.path(), &mut logger).is_none());
        assert!(logger.warnings().is_empty());
        assert!(logger.get_buffer().is_empty());
    }

    /// A host that keeps a real `/var/run` yields a destination the sandbox
    /// reaches only through its compatibility symlink, which bwrap cannot
    /// create through.
    #[test]
    fn the_mount_path_follows_the_sandbox_compat_symlink() {
        assert_eq!(
            sandbox_mount_path("/var/run/NetworkManager/resolv.conf"),
            "/run/NetworkManager/resolv.conf"
        );
    }

    /// Only the directory itself is a symlink in the sandbox; a path that
    /// merely starts with the same letters is a different place.
    #[test]
    fn the_mount_path_leaves_other_spellings_alone() {
        assert_eq!(
            sandbox_mount_path("/run/systemd/resolve/stub-resolv.conf"),
            "/run/systemd/resolve/stub-resolv.conf"
        );
        assert_eq!(
            sandbox_mount_path("/var/running/resolv.conf"),
            "/var/running/resolv.conf"
        );
        assert_eq!(sandbox_mount_path("/etc/resolv.conf"), "/etc/resolv.conf");
        assert_eq!(sandbox_mount_path(COMPAT_RUN_LINK), COMPAT_RUN_LINK);
    }

    /// The rewrite is only correct while the sandbox really is given this
    /// symlink.
    #[test]
    fn the_compat_symlink_the_rewrite_assumes_is_the_one_emitted() {
        let args = crate::bwrap_common::bwrap_command::build_args(
            &crate::mxc_common::models::ExecutionRequest {
                script_code: "echo hi".into(),
                ..Default::default()
            },
            None,
        );

        let emitted = args
            .windows(3)
            .any(|w| w[0] == "--symlink" && w[1] == COMPAT_RUN_TARGET && w[2] == COMPAT_RUN_LINK);
        assert!(
            emitted,
            "the sandbox must be given `--symlink {COMPAT_RUN_TARGET} {COMPAT_RUN_LINK}` for the \
             resolver rewrite to be correct; got: {args:?}"
        );
    }

    /// The host spelling is what the policy checks compare against.
    #[test]
    fn staging_rewrites_the_mount_but_keeps_the_host_destination() {
        let pin = ResolverPin {
            destination: "/var/run/NetworkManager/resolv.conf".to_string(),
            contents: format!("nameserver {SLIRP_DNS_FORWARDER}\n"),
        };
        let mut logger = buffer_logger();
        let staging = tempfile::tempdir().unwrap();
        let (_, destination) =
            stage_resolver(Some(&pin), staging.path(), &mut logger).expect("staging succeeds");

        assert_eq!(destination, "/run/NetworkManager/resolv.conf");
        assert_eq!(pin.destination, "/var/run/NetworkManager/resolv.conf");
    }

    /// bwrap refuses to mount over a symlinked leaf, so the pin has to land on
    /// the file the chain ends at.
    #[test]
    fn the_resolver_target_follows_the_link_chain() {
        let dir = tempfile::tempdir().unwrap();
        let root = std::fs::canonicalize(dir.path()).unwrap();
        fs::create_dir_all(root.join("run/systemd/resolve")).unwrap();
        fs::create_dir_all(root.join("etc")).unwrap();
        let stub = root.join("run/systemd/resolve/stub-resolv.conf");
        fs::write(&stub, SYSTEMD_RESOLVED_STUB).unwrap();
        std::os::unix::fs::symlink(&stub, root.join("etc/resolv.conf")).unwrap();

        assert_eq!(resolver_target_of(&root.join("etc/resolv.conf")), Ok(stub));
    }

    /// Debian's resolvconf writes a relative link, which has to be resolved
    /// against the directory holding it rather than the process's cwd.
    #[test]
    fn the_resolver_target_resolves_a_relative_link() {
        let dir = tempfile::tempdir().unwrap();
        let root = std::fs::canonicalize(dir.path()).unwrap();
        fs::create_dir_all(root.join("run/resolvconf")).unwrap();
        fs::create_dir_all(root.join("etc")).unwrap();
        let real = root.join("run/resolvconf/resolv.conf");
        fs::write(&real, SYSTEMD_RESOLVED_STUB).unwrap();
        std::os::unix::fs::symlink(
            "../run/resolvconf/resolv.conf",
            root.join("etc/resolv.conf"),
        )
        .unwrap();

        assert_eq!(resolver_target_of(&root.join("etc/resolv.conf")), Ok(real));
    }

    /// A destination still holding a symlinked ancestor is one bwrap cannot
    /// create a mount point at when that ancestor's parent is bound read-only,
    /// which aborts the sandbox rather than merely leaving DNS broken.
    #[test]
    fn the_resolver_target_resolves_a_symlinked_ancestor() {
        let dir = tempfile::tempdir().unwrap();
        let root = std::fs::canonicalize(dir.path()).unwrap();
        fs::create_dir_all(root.join("run/res/v1")).unwrap();
        fs::create_dir_all(root.join("etc")).unwrap();
        let real = root.join("run/res/v1/stub.conf");
        fs::write(&real, SYSTEMD_RESOLVED_STUB).unwrap();
        std::os::unix::fs::symlink(root.join("run/res/v1"), root.join("run/res/current")).unwrap();
        std::os::unix::fs::symlink(
            root.join("run/res/current/stub.conf"),
            root.join("etc/resolv.conf"),
        )
        .unwrap();

        assert_eq!(resolver_target_of(&root.join("etc/resolv.conf")), Ok(real));
    }

    /// `..` has to be applied to the directory the link really sits in, not to
    /// path text that still names a symlink, or the pin covers a file the
    /// resolver never reads.
    #[test]
    fn the_resolver_target_folds_dotdot_under_a_symlinked_ancestor() {
        let dir = tempfile::tempdir().unwrap();
        let root = std::fs::canonicalize(dir.path()).unwrap();
        fs::create_dir_all(root.join("run/resolvconf")).unwrap();
        fs::create_dir_all(root.join("etc")).unwrap();
        let real = root.join("run/other.conf");
        fs::write(&real, SYSTEMD_RESOLVED_STUB).unwrap();
        // /etc/link -> /run/resolvconf, then the leaf climbs out of it.
        std::os::unix::fs::symlink(root.join("run/resolvconf"), root.join("etc/link")).unwrap();
        std::os::unix::fs::symlink(
            root.join("etc/link/../other.conf"),
            root.join("etc/resolv.conf"),
        )
        .unwrap();

        assert_eq!(resolver_target_of(&root.join("etc/resolv.conf")), Ok(real));
    }

    /// A plain file is its own target, and a missing one has nothing to pin
    /// over.
    #[test]
    fn the_resolver_target_handles_a_regular_file_and_a_broken_link() {
        let dir = tempfile::tempdir().unwrap();
        let root = std::fs::canonicalize(dir.path()).unwrap();
        let regular = root.join("resolv.conf");
        fs::write(&regular, SYSTEMD_RESOLVED_STUB).unwrap();
        assert_eq!(resolver_target_of(&regular), Ok(regular.clone()));

        let dangling = root.join("dangling");
        std::os::unix::fs::symlink(root.join("absent"), &dangling).unwrap();
        assert!(resolver_target_of(&dangling).is_err());
    }

    /// Reject a link loop before attempting to mount the resolver file.
    #[test]
    fn the_resolver_target_gives_up_on_a_link_loop() {
        let dir = tempfile::tempdir().unwrap();
        let root = std::fs::canonicalize(dir.path()).unwrap();
        let first = root.join("first");
        let second = root.join("second");
        std::os::unix::fs::symlink(&second, &first).unwrap();
        std::os::unix::fs::symlink(&first, &second).unwrap();

        let error = resolver_target_of(&first).expect_err("a loop has no target");
        assert!(error.contains("could not be resolved"), "got: {error}");
    }

    /// A directory would be mounted over as if it were the resolver file.
    #[test]
    fn the_resolver_target_refuses_a_directory() {
        let dir = tempfile::tempdir().unwrap();
        let root = std::fs::canonicalize(dir.path()).unwrap();
        fs::create_dir(root.join("adir")).unwrap();

        assert!(resolver_target_of(&root.join("adir")).is_err());
    }

    /// The pin is spliced after every policy mount, so a `deniedPaths` entry
    /// covering the resolver would be handed back a readable file instead.
    #[test]
    fn a_denied_resolver_path_is_detected() {
        let denied = ContainerPolicy {
            denied_paths: vec!["/run/systemd/resolve".into()],
            ..Default::default()
        };
        assert!(path_is_denied(
            &denied,
            "/run/systemd/resolve/stub-resolv.conf"
        ));
        assert!(!path_is_denied(&denied, "/etc/resolv.conf"));

        let regranted = ContainerPolicy {
            denied_paths: vec!["/run/systemd/resolve".into()],
            readonly_paths: vec!["/run/systemd/resolve/stub-resolv.conf".into()],
            ..Default::default()
        };
        assert!(!path_is_denied(
            &regranted,
            "/run/systemd/resolve/stub-resolv.conf"
        ));
    }

    /// A caller who mounts their own resolver has chosen one, and the pin is
    /// spliced after every policy mount, so it would replace their choice.
    #[test]
    fn a_caller_supplied_resolver_is_recognized() {
        let supplied = ContainerPolicy {
            readonly_paths: vec!["/etc/resolv.conf".into()],
            ..Default::default()
        };
        assert!(policy_names_path(&supplied, "/etc/resolv.conf"));

        // An ancestor grant is not a choice about the resolver itself.
        let whole_etc = ContainerPolicy {
            readonly_paths: vec!["/etc".into()],
            ..Default::default()
        };
        assert!(!policy_names_path(&whole_etc, "/etc/resolv.conf"));
    }

    /// The pin only works if it outranks the baseline mount of the directory
    /// holding the resolver.
    #[test]
    fn the_resolver_bind_lands_after_the_policy_mounts() {
        let mut args = vec![
            "--ro-bind-try".to_string(),
            "/run/systemd/resolve".to_string(),
            "/run/systemd/resolve".to_string(),
        ];
        args.extend(command_tail());

        let overrides =
            insert_pin_bind(&mut args, 17, "/run/systemd/resolve/stub-resolv.conf").unwrap();

        assert!(!overrides, "a parent directory mount is not the same path");
        let pin = args
            .windows(3)
            .position(|window| {
                window
                    == [
                        "--ro-bind-data",
                        "17",
                        "/run/systemd/resolve/stub-resolv.conf",
                    ]
            })
            .expect("pin bind should be present");
        assert!(pin > 0, "pin must follow the baseline mount");
        assert_eq!(
            args[args.len() - COMMAND_TAIL.len() - 1..],
            ["--", "sh", "-c", "echo hello"]
        );
    }

    /// Reported so an operator who mounted their own resolver knows the pin
    /// shadowed it.
    #[test]
    fn the_resolver_bind_reports_overriding_an_earlier_mount() {
        let mut args = vec![
            "--ro-bind".to_string(),
            "/custom/resolv.conf".to_string(),
            "/etc/resolv.conf".to_string(),
        ];
        args.extend(command_tail());

        assert!(
            insert_pin_bind(&mut args, 17, "/etc/resolv.conf").unwrap(),
            "an earlier mount of the same path is an override"
        );
    }

    /// The command bwrap is asked to run, as `build_args` appends it.
    fn command_tail() -> Vec<String> {
        COMMAND_TAIL
            .iter()
            .map(|arg| arg.to_string())
            .chain(["echo hello".to_string()])
            .collect()
    }

    /// Environment values are caller-controlled and reach the argument vector
    /// verbatim, so one that happens to be `--` must not be mistaken for the
    /// separator: splicing there would consume the pin's arguments as that
    /// `--setenv`'s operands and leave the sandbox reading the host's hosts
    /// file.
    #[test]
    fn a_caller_supplied_separator_value_is_not_mistaken_for_the_command() {
        let mut args = vec![
            "--setenv".to_string(),
            "FOO".to_string(),
            "--".to_string(),
            "--ro-bind-try".to_string(),
            "/etc".to_string(),
            "/etc".to_string(),
        ];
        args.extend(command_tail());
        let decoy = 2;

        insert_hosts_bind(&mut args, 17).unwrap();

        assert_eq!(
            args[..=decoy],
            ["--setenv", "FOO", "--"],
            "the environment value must survive the splice intact"
        );
        let pin = args
            .windows(3)
            .position(|window| window == ["--ro-bind-data", "17", SANDBOX_HOSTS_PATH])
            .expect("pin bind should be present");
        assert!(
            pin > decoy,
            "the pin must be spliced at the command, not at the decoy value"
        );
        assert_eq!(
            args[args.len() - COMMAND_TAIL.len() - 1..],
            ["--", "sh", "-c", "echo hello"],
            "the command must remain last"
        );
    }

    /// Byte offset of `needle` in the normalised supervisor script.
    fn script_offset(needle: &str) -> usize {
        normalised_script()
            .find(needle)
            .unwrap_or_else(|| panic!("supervisor script should contain {needle:?}"))
    }

    #[test]
    fn script_signals_readiness_only_after_rules_are_installed() {
        // The caller releases the workload on this signal, so emitting it early
        // would let the workload run with egress wide open.
        let last_restore = script_offset(r#""$ip6tables_restore""#);
        let ready = script_offset(r#"printf ready > "$state_dir/slirp.ready""#);

        assert!(
            last_restore < ready,
            "readiness must be signalled after the final restore"
        );
    }

    #[test]
    fn the_script_hardcodes_no_rule_of_its_own() {
        // Every rule reaches iptables through a restore payload rendered in
        // Rust from parsed addresses, which is what makes the posture auditable
        // in one place and keeps caller text out of the shell entirely. A rule
        // written into the script -- a port 53 accept being the obvious
        // temptation -- would be invisible to the rule model and to every
        // policy test written against it.
        for line in normalised_script().lines() {
            for fragment in [" -j ACCEPT", " -j DROP", " -d ", " -A ", " -N "] {
                assert!(
                    !line.contains(fragment),
                    "the script names a rule that did not come from the payload: {line}"
                );
            }
        }
    }

    #[test]
    fn script_restores_both_families() {
        // A family left unrestored is a family with no chain and no terminal
        // verdict, so it would stay wide open.
        script_offset(r#"-- "$iptables_restore" "#);
        script_offset(r#"-- "$ip6tables_restore" "#);
    }

    #[test]
    fn script_installs_rules_synchronously() {
        // Offset-based ordering assertions only hold if the restores run
        // inline. Backgrounding one would satisfy those tests while destroying
        // the guarantee that rules precede readiness.
        let rules_start = script_offset(r#"-- "$iptables_restore" "#);
        let ready = script_offset(r#"printf ready > "$state_dir/slirp.ready""#);
        let script = normalised_script();
        let region = &script[rules_start..ready];

        for line in region.lines().filter(|line| line.contains("nsenter")) {
            assert!(
                !line.trim_end().ends_with('&'),
                "rule must not be backgrounded: {line}"
            );
            assert!(
                !line.contains('('),
                "rule must not run in a subshell: {line}"
            );
        }
    }

    #[test]
    fn translates_loopback_literal_to_slirp_gateway() {
        let address = ProxyAddress::new("127.0.0.1".into(), 8080);
        let resolved = SandboxProxy::resolve(&address).unwrap();

        assert_eq!(resolved.address().host(), SLIRP_HOST_GATEWAY);
        assert_eq!(resolved.address().port(), 8080);
        assert_eq!(resolved.address().to_url(), "http://10.0.2.2:8080");
    }

    #[test]
    fn translates_loopback_url_without_losing_url_components() {
        let address =
            ProxyAddress::from_url("http://user:pass@127.0.0.1:3128/", "127.0.0.1".into(), 3128);
        let resolved = SandboxProxy::resolve(&address).unwrap();

        assert_eq!(resolved.address().host(), SLIRP_HOST_GATEWAY);
        assert_eq!(resolved.address().port(), 3128);
        assert_eq!(
            resolved.address().to_url(),
            "http://user:pass@10.0.2.2:3128/"
        );
    }

    #[test]
    fn leaves_a_routable_literal_proxy_unchanged() {
        let address = ProxyAddress::from_url("https://10.1.2.3:8443", "10.1.2.3".into(), 8443);
        let resolved = SandboxProxy::resolve(&address).unwrap();

        assert_eq!(resolved.address().to_url(), address.to_url());
    }

    /// A proxy bound to the wildcard address is reachable on the host's
    /// loopback, which the sandbox's private namespace cannot see, so it needs
    /// the same gateway rewrite `127.0.0.1` gets.
    #[test]
    fn translates_wildcard_proxy_to_slirp_gateway() {
        let address = ProxyAddress::new("0.0.0.0".into(), 8080);
        let translated = SandboxProxy::resolve(&address).unwrap();

        assert_eq!(translated.address().host(), SLIRP_HOST_GATEWAY);
        assert_eq!(translated.address().port(), 8080);
    }

    #[test]
    fn translates_bracketed_ipv6_wildcard_proxy_to_slirp_gateway() {
        let address = ProxyAddress::from_url("http://[::]:3128/", "[::]".into(), 3128);
        let translated = SandboxProxy::resolve(&address).unwrap();

        assert_eq!(translated.address().host(), SLIRP_HOST_GATEWAY);
        assert_eq!(translated.address().port(), 3128);
        assert_eq!(translated.address().to_url(), "http://10.0.2.2:3128/");
    }

    /// The descriptor must reach the child that was prepared and no other. The
    /// obvious alternative -- clearing `FD_CLOEXEC` on the parent's copy --
    /// passes the first assertion and fails the other two.
    #[test]
    fn inherited_descriptors_reach_only_the_prepared_child() {
        let (reader, _writer) = pipe2(OFlag::O_CLOEXEC).expect("pipe");
        let fd = reader.as_raw_fd();
        let probe = format!("test -e /proc/self/fd/{fd} && echo present || echo absent");

        let mut prepared = Command::new("sh");
        prepared.arg("-c").arg(&probe);
        inherit_descriptors(&mut prepared, vec![fd]);
        let prepared_out = prepared.output().expect("spawn prepared child");

        let bystander = Command::new("sh")
            .arg("-c")
            .arg(&probe)
            .output()
            .expect("spawn bystander child");

        assert_eq!(
            String::from_utf8_lossy(&prepared_out.stdout).trim(),
            "present",
            "the prepared child did not inherit the descriptor"
        );
        assert_eq!(
            String::from_utf8_lossy(&bystander.stdout).trim(),
            "absent",
            "an unrelated child inherited the descriptor"
        );

        let flags = FdFlag::from_bits_truncate(fcntl(fd, FcntlArg::F_GETFD).expect("F_GETFD"));
        assert!(
            flags.contains(FdFlag::FD_CLOEXEC),
            "the parent's own descriptor was left inheritable"
        );
    }

    /// Regression for the defect this scheme exists to prevent: dash rejects a
    /// redirection to a *variable* descriptor >= 10 at parse time, so the old
    /// `eval "... >&$fd"` form failed based on how many files the parent
    /// happened to hold open. Remapping must land the pipe on a fixed low
    /// number regardless of what the OS originally assigned.
    #[test]
    fn remapped_descriptors_land_on_fixed_numbers_from_any_source() {
        // Force a high source number -- the exact case the old scheme broke on.
        let (reader, writer) = pipe2(OFlag::O_CLOEXEC).expect("pipe");
        let high = fcntl(reader.as_raw_fd(), FcntlArg::F_DUPFD_CLOEXEC(20)).expect("dup high");
        assert!(high >= 20, "test needs a two-digit source descriptor");

        File::from(writer).write_all(b"4242\n").expect("write pid");

        let mut command = Command::new("sh");
        command
            .arg("-c")
            // Reads through the *literal* descriptor the script hardcodes.
            .arg(format!(
                "IFS= read -r v <&{SUPERVISOR_PID_FD}; printf %s \"$v\""
            ));
        remap_descriptors(&mut command, [(high, SUPERVISOR_PID_FD)]);

        let out = command.output().expect("spawn remapped child");
        assert!(
            out.status.success(),
            "remapped child failed: {}",
            String::from_utf8_lossy(&out.stderr)
        );
        assert_eq!(
            String::from_utf8_lossy(&out.stdout),
            "4242",
            "the pipe did not arrive on the fixed descriptor"
        );
    }

    /// A source already sitting on another mapping's target must survive the
    /// remap. A naive sequential `dup2` clobbers it and this catches that.
    #[test]
    fn remapping_survives_a_source_already_on_a_target_number() {
        let (a_reader, a_writer) = pipe2(OFlag::O_CLOEXEC).expect("pipe");
        let (b_reader, b_writer) = pipe2(OFlag::O_CLOEXEC).expect("pipe");
        let a = a_reader.as_raw_fd();
        let b = b_reader.as_raw_fd();

        File::from(a_writer).write_all(b"AAA\n").expect("write a");
        File::from(b_writer).write_all(b"BBB\n").expect("write b");

        // The second mapping's source is the first mapping's target, so a
        // sequential `dup2` would overwrite `b` before it had been landed.
        let mapping = [(a, b), (b, SUPERVISOR_PID_FD)];

        let mut command = Command::new("sh");
        command.arg("-c").arg(format!(
            "printf 'first=%s second=%s' \
             \"$(cat /proc/self/fd/{b})\" \"$(cat /proc/self/fd/{SUPERVISOR_PID_FD})\""
        ));
        remap_descriptors(&mut command, mapping);

        let out = command.output().expect("spawn remapped child");
        assert_eq!(
            String::from_utf8_lossy(&out.stdout),
            "first=AAA second=BBB",
            "a source sitting on another target was clobbered during remap"
        );
    }

    /// The supervisor runs under `/bin/sh`, which is dash on Debian/Ubuntu.
    /// Parse it with the real shell so a construct dash rejects cannot ship.
    #[test]
    fn supervisor_script_parses_under_the_shell_that_runs_it() {
        let out = Command::new("sh")
            .arg("-n")
            .arg("-c")
            .arg(SUPERVISOR_SCRIPT)
            .output()
            .expect("spawn sh");

        assert!(
            out.status.success(),
            "supervisor script is not valid /bin/sh: {}",
            String::from_utf8_lossy(&out.stderr)
        );
    }

    /// The script may only name descriptors the parent actually pins. Two
    /// forms are banned: `>&$var`, which broke on dash for fd >= 10, and
    /// `{var}>`, the varfd allocation the review proposed as a fix — dash
    /// *parses* that as a plain word, so it fails silently rather than loudly
    /// and `sh -n` cannot catch it.
    #[test]
    fn supervisor_script_never_redirects_to_a_variable_descriptor() {
        for line in SUPERVISOR_SCRIPT.lines() {
            let code = line.trim();
            if code.starts_with('#') {
                continue;
            }
            assert!(
                !code.contains(">&$") && !code.contains("<&$"),
                "variable descriptor redirection breaks dash for fd >= 10: {code}"
            );
            assert!(
                !code.contains("}>") && !code.contains("}<"),
                "varfd allocation is a bash-ism; dash parses it as a word: {code}"
            );
        }
    }

    /// Every restore call must wait for the shared host lock. One unguarded
    /// call is enough to fail a concurrent launch under `set -e`.
    #[test]
    fn every_rule_command_waits_for_the_xtables_lock() {
        let code: Vec<&str> = SUPERVISOR_SCRIPT
            .lines()
            .map(str::trim)
            .filter(|line| !line.starts_with('#'))
            .collect();

        let restores: Vec<&&str> = code
            .iter()
            .filter(|line| line.contains(r#"tables_restore""#))
            .collect();
        assert_eq!(
            restores.len(),
            2,
            "one restore call site per family; the per-family loop is what scales"
        );

        for restore in &restores {
            assert!(
                restore.contains(r#"-w "$lock_wait""#),
                "restore may fail instantly on a contended host lock: {restore}"
            );
            assert!(
                restore.contains(" -n "),
                "restore without -n flushes tables it did not write: {restore}"
            );
        }

        // The whole policy travels in the restore payloads now, so any
        // surviving per-rule invocation would be an unbatched leftover.
        assert!(
            !code.iter().any(|line| {
                [
                    "-- iptables ",
                    "-- ip6tables ",
                    r#""$iptables""#,
                    r#""$ip6tables""#,
                ]
                .iter()
                .any(|call| line.contains(call))
            }),
            "rule installation must go through iptables-restore, not per-rule calls"
        );
    }

    /// The budget must cover the worst case it was sized for, or `-w` just
    /// moves the failure from iptables to the parent's timeout.
    #[test]
    fn rule_install_budget_covers_every_transaction_blocking_on_the_lock() {
        for transactions in [2usize, 5, 11] {
            let budget = rule_install_timeout(transactions, 0);
            assert!(
                budget > XTABLES_LOCK_WAIT * transactions as u32,
                "a fully contended host would time out before -w could succeed, and the \
                 budget also covers slirp startup, so it needs headroom above the lock \
                 waits: {transactions} transactions got {budget:?}"
            );
        }
    }

    /// The reason the budget scales at all is a large policy, so it must not
    /// scale without bound -- that is the failure mode the previous per-rule
    /// budget had.
    #[test]
    fn the_rule_install_budget_is_bounded_however_large_the_policy_is() {
        assert_eq!(rule_install_timeout(usize::MAX, 0), RULE_INSTALL_CEILING);
        assert!(
            rule_install_timeout(2, 0) < RULE_INSTALL_CEILING,
            "an ordinary policy must not be charged the ceiling"
        );
    }

    /// This budget is spent before the child's own timeout exists, so without
    /// the clamp setup could outlast the deadline the caller asked for.
    #[test]
    fn rule_install_budget_never_outlasts_the_requested_deadline() {
        let deadline = Duration::from_secs(25);
        assert!(rule_install_timeout(2, 0) > deadline, "premise");
        assert_eq!(rule_install_timeout(2, 25_000), deadline);
    }

    /// Setup has an irreducible cost, so clamping all the way down would fail
    /// every sandbox with a short workload timeout.
    #[test]
    fn the_deadline_clamp_stops_at_the_startup_floor() {
        assert_eq!(rule_install_timeout(2, 1_000), RULE_INSTALL_FLOOR);
    }

    #[test]
    fn an_absent_deadline_leaves_the_budget_unclamped() {
        assert!(rule_install_timeout(2, 0) > RULE_INSTALL_FLOOR);
    }

    fn directional_plan(
        default: crate::mxc_common::models::NetworkAction,
        allowed: &[&str],
        denied: &[&str],
    ) -> EgressPlan {
        use crate::mxc_common::models::{NetworkEgressPolicy, NetworkPeer, NetworkRule};
        let rule = |cidr: &&str| NetworkRule {
            to: vec![NetworkPeer {
                cidr: cidr.parse().expect("test CIDR"),
                except: vec![],
            }],
            ports: vec![],
        };
        let mut request = crate::mxc_common::models::ExecutionRequest::default();
        request.policy.network_egress = Some(NetworkEgressPolicy {
            default,
            allow: allowed.iter().map(rule).collect(),
            deny: denied.iter().map(rule).collect(),
        });
        EgressPlan::for_request(&request).expect("directional rules must build a plan")
    }

    /// A plan whose rule count crosses restore transaction boundaries.
    fn plan_with_rule_count(count: usize) -> EgressPlan {
        let addresses: Vec<String> = (0..count)
            .map(|n| format!("10.0.{}.{}/32", n / 256, n % 256))
            .collect();
        directional_plan(
            crate::mxc_common::models::NetworkAction::Deny,
            &addresses.iter().map(String::as_str).collect::<Vec<_>>(),
            &[],
        )
    }

    /// A rejected transaction installs nothing, so the supervisor must fail
    /// closed *and* name the likeliest cause: iptables reports a missing
    /// `nf_conntrack` only as "Invalid argument", which is unactionable.
    #[test]
    fn a_rejected_transaction_surfaces_the_conntrack_hint() {
        let plan = plan_with_rule_count(3);
        for transaction in 1..=2 {
            let mut supervisor =
                spawn_fake_supervisor_with_plan(&plan, &denied_ingress(), Some(transaction), false);
            supervisor.publish_sandbox_pid();
            let status = supervisor.wait_for_exit();

            assert!(
                !status.success(),
                "transaction {transaction} failed but the supervisor lived on"
            );
            let stderr = supervisor.stderr();
            assert!(
                stderr.contains("nf_conntrack"),
                "a rejected transaction must name the missing kernel module, got: {stderr}"
            );
        }
    }

    /// The payload filenames are a contract between the Rust renderer and the
    /// shell globs that apply them. They live in different languages, so
    /// nothing but this test stops one side from drifting.
    #[test]
    fn the_script_globs_match_the_rendered_payload_names() {
        for family in [RuleFamily::V4, RuleFamily::V6] {
            let glob = format!("\"$state_dir\"/{}*", family.payload_prefix());
            assert!(
                SUPERVISOR_SCRIPT.contains(&glob),
                "the script has no glob {glob} for the payloads the renderer writes"
            );
            assert!(
                payload_file_name(family, 0, 1).starts_with(family.payload_prefix()),
                "the renderer stopped using the prefix the glob matches"
            );
        }
    }

    /// IPv6 stays off until the rules carry the RFC 4890 ICMPv6 exemptions:
    /// enabling it without them would break neighbour discovery and PMTUD
    /// behind a chain that ends in DROP.
    #[test]
    fn the_supervisor_leaves_ipv6_disabled_in_the_namespace() {
        assert!(
            !SUPERVISOR_SCRIPT.contains("--enable-ipv6"),
            "slirp4netns must not offer IPv6 while the ingress chain lacks ICMPv6 exemptions"
        );
    }

    #[test]
    fn ipv6_rules_are_dropped_only_when_the_kernel_lacks_ipv6() {
        assert_eq!(rule_families(true), [RuleFamily::V4, RuleFamily::V6]);
        assert_eq!(rule_families(false), [RuleFamily::V4]);
    }

    #[test]
    fn skipping_the_ipv6_rules_is_a_retained_warning() {
        let mut logger = Logger::new(crate::mxc_common::logger::Mode::Buffer);
        warn_skipped_ipv6_rules(false, &mut logger);
        let out = logger.warnings().join("\n");
        assert!(
            out.contains("did not install IPv6 firewall rules"),
            "must say the IPv6 rules were skipped: {out}"
        );
        // The debug buffer is not read back by `crate::mxc_engine::spawn`, so a
        // warning left there would never reach the caller.
        assert!(
            logger.get_buffer().is_empty(),
            "the warning must travel as a retained warning, not as buffer output"
        );

        let mut logger = Logger::new(crate::mxc_common::logger::Mode::Buffer);
        warn_skipped_ipv6_rules(true, &mut logger);
        assert!(
            logger.warnings().is_empty(),
            "IPv6 rules installed, no warning"
        );
    }

    /// Dropping the IPv6 rules is only safe when the kernel has proven it has
    /// no IPv6. Any other probe failure keeps them.
    #[test]
    fn only_eafnosupport_counts_as_a_kernel_without_ipv6() {
        assert!(!ipv6_probe_means_supported(Err(Errno::EAFNOSUPPORT)));
        for errno in [
            Errno::EMFILE,
            Errno::ENFILE,
            Errno::ENOBUFS,
            Errno::ENOMEM,
            Errno::EACCES,
            Errno::EPROTONOSUPPORT,
        ] {
            assert!(ipv6_probe_means_supported(Err(errno)), "{errno}");
        }
        let socket = socket(
            AddressFamily::Inet,
            SockType::Datagram,
            SockFlag::SOCK_CLOEXEC,
            None,
        )
        .expect("an IPv4 socket stands in for a successful probe");
        assert!(ipv6_probe_means_supported(Ok(socket)));
    }

    #[test]
    fn probe_gives_up_on_a_hung_binary_instead_of_blocking_forever() {
        let mut command = Command::new("sleep");
        command.arg("120");

        let started = Instant::now();
        let error = run_probe(command, "wedged-tool", ProbeBudget::unbounded())
            .expect_err("a hung probe must not succeed");
        let elapsed = started.elapsed();

        assert!(
            error.contains("wedged-tool"),
            "the error must name the tool that hung, got: {error}"
        );
        // The point of the change: bounded, not merely eventual. `sleep 120`
        // would blow this budget by two orders of magnitude if unbounded.
        assert!(
            elapsed < PROBE_TIMEOUT * 3,
            "probe took {elapsed:?}, expected to give up near {PROBE_TIMEOUT:?}"
        );
    }

    #[test]
    fn an_aggregate_budget_bounds_the_walk_tighter_than_one_command_timeout() {
        let mut command = Command::new("sleep");
        command.arg("120");

        let started = Instant::now();
        let error = run_probe(command, "wedged-tool", ProbeBudget::total(Duration::ZERO))
            .expect_err("a hung probe must not succeed");
        let elapsed = started.elapsed();

        // The pre-flight surface is fail-closed and runs behind a caller-owned
        // timeout, so it must give up well inside a single command's ceiling.
        assert!(
            elapsed < PROBE_TIMEOUT,
            "an exhausted budget still waited {elapsed:?}, the per-command ceiling"
        );
        assert!(
            error.contains("ran out of time"),
            "an exhausted budget must blame the budget, not the tool, got: {error}"
        );
    }

    /// An exec failure of the shell surfaces as either exec code; a refused
    /// namespace exits 1 and must stay distinct.
    #[test]
    fn an_exec_failure_is_told_apart_from_a_refused_namespace() {
        assert!(shell_failed_to_start(126));
        assert!(shell_failed_to_start(127));
        assert!(!shell_failed_to_start(1));
        assert!(!shell_failed_to_start(0));
    }

    fn exit_status(code: i32) -> ExitStatus {
        Command::new("sh")
            .args(["-c", &format!("exit {code}")])
            .status()
            .expect("sh must run")
    }

    /// The fail-closed boundary for hosts that disable or exhaust namespaces.
    /// A host where they work cannot produce this status, so classify directly.
    #[test]
    fn a_refused_namespace_names_every_knob_that_could_be_responsible() {
        let error = namespace_probe_error(
            exit_status(1),
            Path::new("/usr/bin/sh"),
            PrivateNetworkUse::ProxyOnlyEgress,
        );

        assert!(error.contains("refused"), "got: {error}");
        for knob in [
            "kernel.apparmor_restrict_unprivileged_userns",
            "kernel.unprivileged_userns_clone",
            "user.max_user_namespaces",
            "user.max_net_namespaces",
        ] {
            assert!(error.contains(knob), "must mention {knob}, got: {error}");
        }
    }

    /// An exec failure must not be reported as a namespace refusal: the
    /// remedies are unrelated.
    #[test]
    fn a_shell_that_cannot_start_is_not_reported_as_a_refused_namespace() {
        for code in [126, 127] {
            let error = namespace_probe_error(
                exit_status(code),
                Path::new("/usr/bin/sh"),
                PrivateNetworkUse::ProxyOnlyEgress,
            );

            assert!(
                error.contains("'/usr/bin/sh'"),
                "must name the shell, got: {error}"
            );
            assert!(
                !error.contains("apparmor"),
                "must not offer namespace remedies, got: {error}"
            );
        }
    }

    fn is_installed(tool: &str) -> bool {
        host_tools::find(tool).is_ok()
    }

    fn namespaces_are_available() -> bool {
        let (Ok(unshare), Ok(sh)) = (host_tools::find("unshare"), host_tools::find("sh")) else {
            return false;
        };
        Command::new(unshare)
            .args(PRIVATE_NAMESPACE_PROBE_FLAGS)
            .arg(sh)
            .args(["-c", ":"])
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status()
            .is_ok_and(|status| status.success())
    }

    fn iptables_uses_nf_tables() -> bool {
        host_tools::find("iptables").is_ok_and(|iptables| {
            Command::new(iptables)
                .arg("--version")
                .output()
                .is_ok_and(|output| String::from_utf8_lossy(&output.stdout).contains("nf_tables"))
        })
    }

    fn script_variable(tool: &str) -> String {
        format!(r#""${}""#, tool.replace('-', "_"))
    }

    /// The supervisor is the only place proxy mode shells out at launch, so the
    /// pre-flight walk is only honest if it covers what that script runs.
    ///
    /// Shell is not worth parsing here — the binaries appear in argument
    /// position (`"$nsenter" --net=… -- "$iptables_restore" …`) as well as
    /// command position, so a tokenizer would miss exactly the cases that
    /// matter. Pinning the constant is exact instead: any edit fails here and
    /// forces a re-check of [`SUPERVISOR_EXTERNAL_COMMANDS`].
    #[test]
    fn supervisor_script_changes_force_a_dependency_re_review() {
        // FNV-1a rather than `DefaultHasher`, whose output is not stable across
        // Rust releases. `\r` is skipped so the digest survives a CRLF checkout.
        let digest = SUPERVISOR_SCRIPT
            .bytes()
            .filter(|byte| *byte != b'\r')
            .fold(0xcbf2_9ce4_8422_2325_u64, |hash, byte| {
                (hash ^ u64::from(byte)).wrapping_mul(0x0000_0100_0000_01b3)
            });

        assert_eq!(
            digest, EXPECTED_SUPERVISOR_SCRIPT_DIGEST,
            "SUPERVISOR_SCRIPT changed. Re-check that every binary the script runs \
             (including those passed to `nsenter --`) arrives as a checked path from \
             NetworkTools::supervisor_arguments and is probed by the dependency walk, update \
             SUPERVISOR_EXTERNAL_COMMANDS, then set EXPECTED_SUPERVISOR_SCRIPT_DIGEST to {digest:#x}."
        );
    }

    /// Guards the other direction: an entry left behind after its command was
    /// removed would claim coverage nothing needs.
    #[test]
    fn every_listed_supervisor_command_is_actually_invoked() {
        for name in SUPERVISOR_EXTERNAL_COMMANDS {
            assert!(
                SUPERVISOR_SCRIPT.contains(&script_variable(name)),
                "SUPERVISOR_EXTERNAL_COMMANDS lists '{name}', but SUPERVISOR_SCRIPT no longer \
                 runs it; drop the entry"
            );
        }
    }

    #[test]
    fn every_supervisor_command_is_in_the_dependency_walk() {
        // The walk's full set: the two checked directly, plus the probe list.
        let tools = tools_in(Path::new("/mxc-test-tools"));
        let mut probed: Vec<&str> = vec!["slirp4netns", "unshare"];
        probed.extend(tools.tool_probes().iter().map(|(name, ..)| *name));

        for name in SUPERVISOR_EXTERNAL_COMMANDS {
            assert!(
                probed.contains(name),
                "the supervisor runs '{name}' but probe_dependencies_uncached never checks it"
            );
        }
    }

    /// The rule tooling the supervisor executes must be probed, not merely
    /// listed: these are reached through `nsenter --`, where a missing binary
    /// surfaces as a dead supervisor mid-startup.
    #[test]
    fn the_rule_tools_the_supervisor_runs_are_probed() {
        let tools = tools_in(Path::new("/mxc-test-tools"));
        for binary in ["nsenter", "ip", "iptables-restore", "ip6tables-restore"] {
            assert!(
                SUPERVISOR_SCRIPT.contains(&script_variable(binary)),
                "expected the supervisor to run '{binary}'"
            );
            assert!(
                tools
                    .tool_probes()
                    .iter()
                    .any(|(probed, ..)| *probed == binary),
                "the supervisor runs '{binary}' but the pre-flight walk never probes it"
            );
        }
    }

    /// `sh` is a dependency of the supervisor itself (`unshare … -- sh -c`), so
    /// it is covered by the namespace probe rather than the command list above.
    #[test]
    fn the_namespace_probe_covers_the_supervisor_shell() {
        // 126/127 are the exec-failure codes `unshare` propagates when the
        // trailing command cannot start.
        assert!(shell_failed_to_start(126));
        assert!(shell_failed_to_start(127));
        assert!(!shell_failed_to_start(1));
    }

    /// Cache reuse, in the three shapes that matter: a remembered success, a
    /// failure that is retried, and reuse across use cases.
    #[test]
    fn the_cache_remembers_tools_without_allocating_namespaces() {
        use std::cell::RefCell;

        let log = RefCell::new(Vec::new());
        let counting = |program: &Path, args: &[&str]| {
            log.borrow_mut()
                .push(format!("{} {}", tool_name(program), args.join(" ")));
            walk_stub_for(program, None)
        };

        // `unshare --help` is a stable check; the bare `unshare` carrying
        // `--map-current-user` is the namespace allocation.
        let namespace_runs = || {
            log.borrow()
                .iter()
                .filter(|call| call.contains("--map-current-user"))
                .count()
        };
        let stable_runs = || {
            log.borrow()
                .iter()
                .filter(|call| call.starts_with("slirp4netns"))
                .count()
        };

        let approved = Mutex::new(None);
        let run = |use_case| {
            probe_dependencies_caching(
                &approved,
                use_case,
                ProbeBudget::unbounded(),
                lookup_where_only(None),
                counting,
            )
            .expect("tool checks should succeed");
            (stable_runs(), namespace_runs())
        };

        let after_first = run(PrivateNetworkUse::ProxyOnlyEgress);
        let after_second = run(PrivateNetworkUse::ProxyOnlyEgress);
        // The cache is shared across use cases, which ask the same questions.
        let after_other_use_case = run(PrivateNetworkUse::FirewallEnforcement);

        assert_eq!(after_first.0, 1, "the tool check must run on a cold cache");
        assert_eq!(
            after_second.0, after_first.0,
            "a warm cache must not re-run the tool checks"
        );
        assert_eq!(
            after_other_use_case.0, after_first.0,
            "the cache is shared across use cases, which ask the same questions"
        );
        assert_eq!(
            (after_first.1, after_second.1, after_other_use_case.1),
            (0, 0, 0),
            "launch dependency checks must not allocate namespaces"
        );
    }

    #[test]
    fn a_different_tool_selection_is_checked_before_it_is_used() {
        use std::cell::Cell;

        let stable_runs = Cell::new(0_u32);
        let counting = |program: &Path, _args: &[&str]| {
            if tool_name(program) == "slirp4netns" {
                stable_runs.set(stable_runs.get() + 1);
            }
            walk_stub_for(program, None)
        };
        let approved = Mutex::new(None);
        let run = |directory: &'static str| {
            let tools = probe_dependencies_caching(
                &approved,
                PrivateNetworkUse::ProxyOnlyEgress,
                ProbeBudget::unbounded(),
                |name: &str| Ok(Path::new(directory).join(name)),
                counting,
            )
            .expect("every tool answers");
            assert_eq!(tools, tools_in(Path::new(directory)));
            stable_runs.get()
        };

        assert_eq!(run("/first"), 1);
        assert_eq!(
            run("/first"),
            1,
            "the approved files must not be re-checked"
        );
        assert_eq!(run("/second"), 2, "different files must be checked first");
    }

    /// A failure must not be remembered: it usually means the operator has not
    /// installed the tooling yet.
    #[test]
    fn a_failed_walk_is_retried_rather_than_remembered() {
        use std::cell::Cell;

        let attempts = Cell::new(0_u32);
        let approved = Mutex::new(None);
        let failing = |_: &Path, _: &[&str]| {
            attempts.set(attempts.get() + 1);
            let mut command = Command::new("sh");
            command.args(["-c", "exit 1"]);
            command
        };

        probe_dependencies_caching(
            &approved,
            PrivateNetworkUse::ProxyOnlyEgress,
            ProbeBudget::unbounded(),
            lookup_where_only(None),
            failing,
        )
        .expect_err("a host whose tooling fails must not be reported usable");
        let after_first = attempts.get();

        probe_dependencies_caching(
            &approved,
            PrivateNetworkUse::ProxyOnlyEgress,
            ProbeBudget::unbounded(),
            lookup_where_only(None),
            failing,
        )
        .expect_err("the failure must not have been cached");

        assert!(
            attempts.get() > after_first,
            "a failed walk must be re-run, not remembered"
        );
    }

    /// The tests above cover `namespace_probe_error` as a pure function. These
    /// drive the real path — `run_probe`, a genuine exit status, the diagnostic
    /// mapping — so a refactor cannot stop feeding the status into it while
    /// every pure-function test still passes.
    #[test]
    fn a_refused_namespace_is_reported_through_the_real_probe_path() {
        let mut command = Command::new("sh");
        command.args(["-c", "exit 1"]);

        let error = check_private_namespaces(
            command,
            Path::new("/usr/bin/sh"),
            PrivateNetworkUse::ProxyOnlyEgress,
            ProbeBudget::unbounded(),
        )
        .expect_err("a non-zero namespace probe must fail the walk");

        assert!(error.contains("refused"), "got: {error}");
        assert!(
            error.contains("kernel.apparmor_restrict_unprivileged_userns"),
            "the refusal must still name the likely knobs, got: {error}"
        );
    }

    #[test]
    fn a_shell_exec_failure_is_reported_through_the_real_probe_path() {
        for code in [126, 127] {
            let mut command = Command::new("sh");
            command.args(["-c", &format!("exit {code}")]);

            let error = check_private_namespaces(
                command,
                Path::new("/usr/bin/sh"),
                PrivateNetworkUse::ProxyOnlyEgress,
                ProbeBudget::unbounded(),
            )
            .expect_err("an exec failure must fail the walk");

            assert!(
                error.contains("'/usr/bin/sh'"),
                "must name the shell, got: {error}"
            );
            assert!(
                !error.contains("apparmor"),
                "must not offer namespace remedies, got: {error}"
            );
        }
    }

    #[test]
    fn a_granted_namespace_passes_the_real_probe_path() {
        let mut command = Command::new("sh");
        command.args(["-c", ":"]);

        assert!(check_private_namespaces(
            command,
            Path::new("/usr/bin/sh"),
            PrivateNetworkUse::ProxyOnlyEgress,
            ProbeBudget::unbounded(),
        )
        .is_ok());
    }

    /// A probe that quietly stopped asking for one of the namespaces would keep
    /// passing everywhere while proving nothing, so pin what it requests.
    #[test]
    fn the_namespace_probe_asks_for_both_namespaces_as_the_supervisor_does() {
        let tools = tools_in(Path::new("/mxc-test-tools"));
        let command = private_namespace_probe(&tools, &real_probe_command);
        assert_eq!(command.get_program(), tools.unshare.as_os_str());

        let args: Vec<String> = command
            .get_args()
            .map(|arg| arg.to_string_lossy().into_owned())
            .collect();
        for flag in ["--user", "--map-current-user", "--keep-caps", "--net"] {
            assert!(
                args.iter().any(|arg| arg == flag),
                "the probe must request {flag}, got: {args:?}"
            );
        }

        // The supervisor runs its shell with `-c`, so the probe must exercise that.
        assert!(
            args.windows(2)
                .any(|pair| Path::new(&pair[0]) == tools.sh && pair[1] == "-c"),
            "the probe must run the supervisor's shell, got: {args:?}"
        );
    }

    fn tool_name(program: &Path) -> &str {
        program
            .file_name()
            .and_then(|name| name.to_str())
            .unwrap_or_default()
    }

    fn tools_in(directory: &Path) -> NetworkTools {
        NetworkTools::find(PrivateNetworkUse::ProxyOnlyEgress, |name| {
            Ok(directory.join(name))
        })
        .expect("every tool is found")
    }

    fn lookup_where_only(
        missing: Option<&'static str>,
    ) -> impl Fn(&str) -> Result<PathBuf, LookupError> {
        move |name| {
            if Some(name) == missing {
                return Err(LookupError::NotFound);
            }
            Ok(Path::new("/mxc-test-tools").join(name))
        }
    }

    /// A stand-in for the whole dependency walk: every tool succeeds with the
    /// banner the walk demands.
    ///
    /// Makes each refusal reproducible on any host, including one with none of
    /// the real tooling — where the host-conditional walk test proves nothing.
    fn walk_stub(program: &Path, _args: &[&str]) -> Command {
        walk_stub_for(program, None)
    }

    /// A stand-in that succeeds, emitting the banner the walk parses for
    /// `program`. `override_script` replaces that behaviour for one tool.
    fn walk_stub_for(program: &Path, override_script: Option<&str>) -> Command {
        let script = override_script.unwrap_or(match tool_name(program) {
            // The walk requires both flags to be advertised.
            "unshare" => "printf '%s\\n' '--map-current-user --keep-caps'",
            // The backend gate refuses anything that is not nf_tables.
            "iptables" | "ip6tables" | "iptables-restore" | "ip6tables-restore" => {
                "printf '%s\\n' 'iptables v1.8.9 (nf_tables)'"
            }
            _ => ":",
        });
        let mut command = Command::new("sh");
        command.args(["-c", script]);
        command
    }

    /// The deterministic counterpart to the host-conditional walk test: proves
    /// the sequence completes on a fully equipped host regardless of what this
    /// runner has installed.
    #[test]
    fn the_dependency_walk_succeeds_when_every_tool_answers() {
        assert_eq!(
            probe_dependencies_with(
                PrivateNetworkUse::ProxyOnlyEgress,
                ProbeBudget::unbounded(),
                lookup_where_only(None),
                walk_stub,
            ),
            Ok(tools_in(Path::new("/mxc-test-tools")))
        );
    }

    /// Each tool the walk depends on must be named when it is absent — the
    /// refusal is the only thing telling an operator what to install.
    #[test]
    fn every_missing_tool_is_named_in_the_refusal() {
        for tool in [
            "slirp4netns",
            "unshare",
            "sh",
            "nsenter",
            "ip",
            "iptables",
            "ip6tables",
            "iptables-restore",
            "ip6tables-restore",
            "sleep",
        ] {
            let error = probe_dependencies_with(
                PrivateNetworkUse::ProxyOnlyEgress,
                ProbeBudget::unbounded(),
                lookup_where_only(Some(tool)),
                walk_stub,
            )
            .expect_err("a missing tool must fail the walk");

            assert!(
                error.contains(&format!("'{tool}'")),
                "a missing '{tool}' must be named, got: {error}"
            );
            assert!(
                error.contains("/usr/sbin"),
                "the refusal must say where the tool was looked for, got: {error}"
            );
            assert!(
                error.contains("runtimeConfig.networkProxy"),
                "the refusal must name the config that required it, got: {error}"
            );
        }
    }

    #[test]
    fn a_found_tool_that_cannot_start_is_reported_at_its_path() {
        let factory = |program: &Path, args: &[&str]| {
            if tool_name(program) == "nsenter" {
                return Command::new("/mxc-probe-absent-directory/nsenter");
            }
            walk_stub(program, args)
        };

        let error = probe_dependencies_with(
            PrivateNetworkUse::ProxyOnlyEgress,
            ProbeBudget::unbounded(),
            lookup_where_only(None),
            factory,
        )
        .expect_err("a tool that cannot start must fail the walk");

        assert!(error.contains("/mxc-test-tools/nsenter"), "got: {error}");
    }

    /// The wording differs by use case, so direct egress must not be told to
    /// drop the runtime proxy.
    #[test]
    fn a_refusal_names_the_use_case_that_required_the_tool() {
        let error = probe_dependencies_with(
            PrivateNetworkUse::FirewallEnforcement,
            ProbeBudget::unbounded(),
            lookup_where_only(Some("slirp4netns")),
            walk_stub,
        )
        .expect_err("a missing tool must fail the walk");

        assert!(error.contains("network.egress"), "got: {error}");
        assert!(
            !error.contains("omit runtimeConfig.networkProxy"),
            "got: {error}"
        );
    }

    /// Present but broken is a different diagnosis from absent, and the walk
    /// must not collapse the two.
    #[test]
    fn a_tool_that_exits_non_zero_is_reported_as_a_broken_installation() {
        let tools = tools_in(Path::new("/mxc-test-tools"));
        for (broken, path, ..) in tools.tool_probes() {
            let factory = |program: &Path, _args: &[&str]| {
                if tool_name(program) == broken {
                    return walk_stub_for(program, Some("exit 3"));
                }
                walk_stub_for(program, None)
            };

            let error = probe_dependencies_with(
                PrivateNetworkUse::ProxyOnlyEgress,
                ProbeBudget::unbounded(),
                lookup_where_only(None),
                factory,
            )
            .expect_err("a broken tool must fail the walk");

            assert!(error.contains(&path.display().to_string()), "got: {error}");
            assert!(
                error.contains("working"),
                "a broken install must not be reported as missing, got: {error}"
            );
        }
    }

    /// `unshare` on PATH is not enough — an implementation without the flags
    /// the supervisor passes would fail at launch instead.
    #[test]
    fn an_unshare_missing_the_required_flags_is_refused() {
        for banner in [
            "printf '%s\\n' 'usage: unshare'",
            "printf '%s\\n' '--map-current-user'",
            "printf '%s\\n' '--keep-caps'",
        ] {
            let factory = move |program: &Path, _args: &[&str]| {
                if tool_name(program) == "unshare" {
                    return walk_stub_for(program, Some(banner));
                }
                walk_stub_for(program, None)
            };

            let error = probe_dependencies_with(
                PrivateNetworkUse::ProxyOnlyEgress,
                ProbeBudget::unbounded(),
                lookup_where_only(None),
                factory,
            )
            .expect_err("an unshare without both flags must fail the walk");

            assert!(
                error.contains("--map-current-user") && error.contains("--keep-caps"),
                "the refusal must name the flags it needs, got: {error}"
            );
        }
    }

    /// The regression test for the supervision itself: delete the worker and
    /// this hangs forever. A timing assertion against the live walk cannot do
    /// that, since a real host answers well inside the budget either way.
    #[test]
    fn a_walk_that_never_returns_still_answers_at_the_budget() {
        static GATE: PreflightGate = PreflightGate::new();
        let budget = Duration::from_millis(300);

        let started = Instant::now();
        let error = supervise_preflight_with(&GATE, budget, move || {
            // Stands in for a spawn blocked on a stalled filesystem: no
            // deadline inside the walk is ever consulted.
            thread::sleep(Duration::from_secs(120));
            Ok(())
        })
        .expect_err("a walk that never returns must not report support");
        let elapsed = started.elapsed();

        // No slack multiplier: tolerating double the ceiling would not pin it.
        assert!(
            elapsed < budget + Duration::from_secs(1),
            "supervision must return at the budget, took {elapsed:?}"
        );
        assert!(
            elapsed >= budget,
            "it must actually wait out the budget, took {elapsed:?}"
        );
        assert!(
            error.contains(&format!("{budget:?}")),
            "the timeout must name the budget that ran out, got: {error}"
        );
    }

    /// A walk that answers inside the budget must have its verdict passed
    /// through unchanged, in both directions — supervision must not swallow the
    /// result or turn a refusal into a timeout.
    ///
    /// Reusing one gate across both calls also pins the release: a slot held
    /// past a completed walk would turn the second call into a refusal.
    #[test]
    fn a_walk_that_answers_is_reported_verbatim() {
        static GATE: PreflightGate = PreflightGate::new();
        assert_eq!(
            supervise_preflight_with(&GATE, Duration::from_secs(5), || Ok(())),
            Ok(())
        );
        assert_eq!(
            supervise_preflight_with(&GATE, Duration::from_secs(5), || Err(
                "slirp4netns missing".into()
            )),
            Err("slirp4netns missing".to_string())
        );
    }

    /// Without the gate a wedged host would strand another thread on every
    /// call, so pin that the second caller is refused rather than starting one.
    #[test]
    fn a_stranded_walk_refuses_the_next_caller_instead_of_stranding_another() {
        static GATE: PreflightGate = PreflightGate::new();
        let budget = Duration::from_millis(200);

        supervise_preflight_with(&GATE, budget, || {
            thread::sleep(Duration::from_secs(120));
            Ok(())
        })
        .expect_err("the stranded walk must time out");

        let error = supervise_preflight_with(&GATE, budget, || {
            panic!("the gate must refuse before a second worker is started")
        })
        .expect_err("a host with a stranded probe cannot be confirmed");

        assert!(
            error.contains("did not return within"),
            "the refusal must say a probe is still outstanding, got: {error}"
        );
    }

    /// Both public entry points reach this probe in one process, so an
    /// overlapping healthy walk must be waited for rather than refused —
    /// otherwise host capability depends on call scheduling.
    #[test]
    fn an_overlapping_healthy_walk_is_waited_for_not_refused() {
        static GATE: PreflightGate = PreflightGate::new();
        let budget = Duration::from_secs(5);

        let first = thread::spawn(move || {
            supervise_preflight_with(&GATE, budget, || {
                thread::sleep(Duration::from_millis(300));
                Ok(())
            })
        });
        // Long enough that the second caller arrives while the first still owns
        // the slot.
        thread::sleep(Duration::from_millis(50));
        let second = supervise_preflight_with(&GATE, budget, || Ok(()));

        assert_eq!(first.join().expect("first walk"), Ok(()));
        assert_eq!(
            second,
            Ok(()),
            "a caller overlapping a healthy walk must get the real answer"
        );
    }

    /// A panicking walk must free the slot, or one bad call would refuse every
    /// later caller for the life of the process.
    #[test]
    fn a_panicking_walk_releases_the_slot() {
        static GATE: PreflightGate = PreflightGate::new();

        let _ = supervise_preflight_with(&GATE, Duration::from_secs(5), || {
            panic!("walk exploded");
        });

        assert_eq!(
            supervise_preflight_with(&GATE, Duration::from_secs(5), || Ok(())),
            Ok(()),
            "the slot must survive a panicking walk"
        );
    }

    /// Smoke check only: the live walk is fast on a healthy host, so this
    /// cannot substitute for the supervision test above.
    #[test]
    fn the_advisory_probe_returns_within_its_budget() {
        let started = Instant::now();
        let _ = probe_proxy_enforcement();
        let elapsed = started.elapsed();

        assert!(
            elapsed < PRE_FLIGHT_BUDGET * 2,
            "the advisory probe must honor its budget, took {elapsed:?}"
        );
    }

    /// The deadline tests cover the individual failure branches in isolation.
    /// This drives the whole sequence, so a check added later cannot start
    /// failing hosts that do meet every requirement.
    #[test]
    fn the_whole_dependency_walk_passes_on_a_host_that_meets_every_requirement() {
        const CHECKED_TOOLS: [&str; 10] = [
            "slirp4netns",
            "unshare",
            "sh",
            "nsenter",
            "ip",
            "iptables",
            "ip6tables",
            "iptables-restore",
            "ip6tables-restore",
            "sleep",
        ];
        let missing: Vec<&str> = CHECKED_TOOLS
            .into_iter()
            .filter(|tool| !is_installed(tool))
            .collect();
        let equipped =
            missing.is_empty() && namespaces_are_available() && iptables_uses_nf_tables();

        let started = Instant::now();
        let result = probe_proxy_enforcement();
        let elapsed = started.elapsed();

        assert!(
            elapsed < PRE_FLIGHT_BUDGET * 2,
            "the walk must stay near its budget, took {elapsed:?}"
        );
        // A less-equipped host still has something to prove: the refusal must
        // say which dependency it was, never fail closed anonymously.
        if let Err(error) = result {
            // Exhausting `PRE_FLIGHT_BUDGET` says how quickly this host
            // answered, not what it has installed: a loaded machine can run out
            // of budget while meeting every requirement.
            let out_of_budget =
                error.contains("ran out of time") || error.contains("gave up while checking");
            assert!(
                !equipped || out_of_budget,
                "a host with every dependency must pass the walk unless the \
                 pre-flight budget ran out, got: {error}"
            );
            if out_of_budget {
                // Even giving up must stay attributable to a specific check.
                assert!(
                    CHECKED_TOOLS.iter().any(|tool| error.contains(tool)),
                    "a budget-exhausted walk must still name the check it \
                     abandoned, got: {error}"
                );
            } else {
                assert!(
                    missing.iter().any(|tool| error.contains(tool))
                        || error.contains("namespaces")
                        || error.contains("iptables")
                        || error.contains("ip6tables"),
                    "a failure must name what is missing or unusable, got: {error}"
                );
            }
        }
    }

    /// A descendant inheriting stdout keeps the pipe's write end open, so a
    /// naive pipe-based probe would block here until that descendant exited.
    /// [`crate::bwrap_common::probe_exec`] sweeps the whole process group once the direct
    /// child exits, so the descendant is killed and the read completes.
    #[test]
    fn a_probe_returns_while_a_descendant_still_holds_its_output() {
        let mut command = Command::new("sh");
        command.args(["-c", "sleep 10 & echo banner"]);

        let started = Instant::now();
        let output = run_probe(command, "sh", ProbeBudget::unbounded())
            .expect("the direct child exits immediately");

        assert!(output.stdout.contains("banner"));
        assert!(
            started.elapsed() < Duration::from_secs(5),
            "reading output must not wait for the descendant, took {:?}",
            started.elapsed()
        );
    }

    #[test]
    fn a_clamped_command_blames_the_budget_rather_than_the_tool() {
        let mut command = Command::new("sleep");
        command.arg("120");

        // A healthy-but-slow tool killed by the residual budget must not be
        // reported as hung: this text is the caller-visible warning.
        let error = run_probe(
            command,
            "innocent-tool",
            ProbeBudget::total(Duration::from_millis(200)),
        )
        .expect_err("a hung probe must not succeed");

        assert!(
            !error.contains("hung"),
            "a budget-clamped command must not be called hung, got: {error}"
        );
        assert!(
            error.contains(&format!("{PRE_FLIGHT_BUDGET:?}")),
            "the error must name the budget that ran out, got: {error}"
        );
    }

    #[test]
    fn a_command_that_outlives_its_own_ceiling_is_reported_as_hung() {
        let budget = ProbeBudget::unbounded();
        let (_, source) = budget.command_deadline();

        assert_eq!(
            source,
            DeadlineSource::Command,
            "an unbounded walk must attribute timeouts to the command itself"
        );
    }

    #[test]
    fn a_live_budget_clamps_a_hung_command_to_the_time_remaining() {
        let mut command = Command::new("sleep");
        command.arg("120");

        let started = Instant::now();
        let error = run_probe(
            command,
            "wedged-tool",
            ProbeBudget::total(Duration::from_millis(200)),
        )
        .expect_err("a hung probe must not succeed");
        let elapsed = started.elapsed();

        assert!(
            elapsed < PROBE_TIMEOUT,
            "the command ran {elapsed:?}, ignoring the {:?} budget it was given",
            Duration::from_millis(200)
        );
        assert!(
            error.contains("wedged-tool"),
            "a command that hung inside its budget must still name the tool, got: {error}"
        );
    }

    #[test]
    fn probe_returns_stdout_of_a_well_behaved_binary() {
        let mut command = Command::new("sh");
        command.args(["-c", "echo probe-stdout-marker"]);

        let probe = run_probe(command, "echo", ProbeBudget::unbounded())
            .expect("a fast probe must succeed");

        assert!(
            probe.status.success(),
            "expected success, got {:?}",
            probe.status
        );
        assert!(
            probe.stdout.contains("probe-stdout-marker"),
            "stdout was not captured, got: {:?}",
            probe.stdout
        );
    }

    /// A wrapper that floods stderr is no more the tool we meant to interrogate
    /// than one that floods stdout.
    #[test]
    fn an_oversized_stream_is_refused_on_either_side() {
        for stream in ["1", "2"] {
            let mut command = Command::new("sh");
            command.args([
                "-c",
                &format!(
                    "echo ok; dd if=/dev/zero bs=1024 count={} >&{stream} 2>/dev/null",
                    (probe_exec::MAX_PROBE_OUTPUT_BYTES / 1024) + 8
                ),
            ]);

            let error = run_probe(command, "flooding-tool", ProbeBudget::unbounded())
                .expect_err("a truncated stream must not be judged");

            assert!(
                error.contains("refusing to judge a truncated banner"),
                "stream {stream} must be refused, got: {error}"
            );
        }
    }

    #[test]
    fn probe_reports_a_failing_binary_without_treating_it_as_a_hang() {
        let mut command = Command::new("sh");
        command.args(["-c", "exit 3"]);

        let probe = run_probe(command, "failing", ProbeBudget::unbounded())
            .expect("a clean non-zero exit is not an error");

        assert!(!probe.status.success(), "expected a non-zero exit status");
    }

    /// A path whose parent does not exist, standing in for the root-owned `/run`
    /// an unprivileged supervisor meets. Keeps the test deterministic and
    /// root-free while hitting the same branch.
    fn unreachable_lock(dir: &TempDir) -> std::path::PathBuf {
        dir.path().join("no-such-dir").join("xtables.lock")
    }

    /// Verified live: with the lock absent and `/run` unwritable, `iptables-nft
    /// -N` still succeeds.
    #[test]
    fn the_nft_backend_is_accepted_even_when_the_lock_is_unreachable() {
        let dir = tempfile::tempdir().expect("tempdir");

        assert!(
            iptables_backend_is_usable(
                "iptables",
                Path::new("/usr/sbin/iptables"),
                "iptables v1.8.10 (nf_tables)\n",
                &unreachable_lock(&dir),
                PrivateNetworkUse::ProxyOnlyEgress
            )
            .is_ok(),
            "the nf_tables backend takes no lock, so an unreachable lock must not refuse it"
        );
    }

    /// The regression this check exists for: legacy opens the lock
    /// unconditionally, so the supervisor dies at the first rule.
    #[test]
    fn the_legacy_backend_is_refused_when_it_could_not_take_the_lock() {
        let dir = tempfile::tempdir().expect("tempdir");

        let error = iptables_backend_is_usable(
            "iptables",
            Path::new("/usr/sbin/iptables"),
            "iptables v1.8.10 (legacy)\n",
            &unreachable_lock(&dir),
            PrivateNetworkUse::ProxyOnlyEgress,
        )
        .expect_err("a legacy backend with an unreachable lock cannot install rules");

        assert!(
            error.contains("iptables") && error.contains("nf_tables"),
            "the error must name the binary and the backend to switch to: {error}"
        );
        assert!(
            error.contains("/usr/sbin/iptables"),
            "the error must name the file that was checked: {error}"
        );
    }

    /// Directional enforcement shares this probe with runtime proxy egress;
    /// the advice must name the policy the caller actually configured.
    #[test]
    fn a_firewall_request_is_never_advised_about_the_proxy() {
        let dir = tempfile::tempdir().expect("tempdir");

        let error = iptables_backend_is_usable(
            "iptables",
            Path::new("/usr/sbin/iptables"),
            "iptables v1.8.10 (legacy)\n",
            &unreachable_lock(&dir),
            PrivateNetworkUse::FirewallEnforcement,
        )
        .expect_err("a legacy backend with an unreachable lock cannot install rules");

        assert!(
            !error.contains("runtimeConfig.networkProxy"),
            "a firewall-only request must not be told about a field it never set: {error}"
        );
        assert!(
            error.contains("network.egress"),
            "the error must name what the caller configured: {error}"
        );
    }

    /// The mirror image: the proxy wording must not drift to firewall terms.
    #[test]
    fn a_proxy_request_is_never_advised_about_the_enforcement_mode() {
        let dir = tempfile::tempdir().expect("tempdir");

        let error = iptables_backend_is_usable(
            "iptables",
            Path::new("/usr/sbin/iptables"),
            "iptables v1.8.10 (legacy)\n",
            &unreachable_lock(&dir),
            PrivateNetworkUse::ProxyOnlyEgress,
        )
        .expect_err("a legacy backend with an unreachable lock cannot install rules");

        assert!(
            error.contains("runtimeConfig.networkProxy") && !error.contains("network.egress"),
            "a proxy request must keep the proxy wording: {error}"
        );
    }

    /// Every use case must produce a distinct, non-empty vocabulary -- an empty
    /// or shared string would silently reintroduce the mismatch above.
    #[test]
    fn each_private_network_use_names_itself_distinctly() {
        let proxy = PrivateNetworkUse::ProxyOnlyEgress;
        let firewall = PrivateNetworkUse::FirewallEnforcement;

        for (a, b) in [
            (proxy.requirement(), firewall.requirement()),
            (proxy.remedy(), firewall.remedy()),
            (proxy.mechanism(), firewall.mechanism()),
        ] {
            assert!(!a.is_empty() && !b.is_empty(), "wording must not be empty");
            assert_ne!(a, b, "the two use cases must not share wording");
        }
    }

    /// Legacy is refused for being unable to take its lock, not for being
    /// legacy: it works as root, and rejecting that would break a valid host.
    #[test]
    fn the_legacy_backend_is_accepted_when_the_lock_is_writable() {
        let dir = tempfile::tempdir().expect("tempdir");
        let lock = dir.path().join("xtables.lock");
        fs::write(&lock, b"").expect("create lock");

        assert!(
            iptables_backend_is_usable(
                "iptables",
                Path::new("/usr/sbin/iptables"),
                "iptables v1.8.10 (legacy)\n",
                &lock,
                PrivateNetworkUse::ProxyOnlyEgress
            )
            .is_ok(),
            "a legacy backend that can take its lock installs rules fine"
        );
    }

    /// The lock is created on first use, so the check must ask about the
    /// directory rather than report the absent file as a failure.
    #[test]
    fn an_absent_lock_in_a_writable_directory_is_usable() {
        let dir = tempfile::tempdir().expect("tempdir");

        assert!(
            lock_is_writable(&dir.path().join("xtables.lock")),
            "the lock is created on demand, so a writable directory is enough"
        );
    }

    /// Pre-1.8 builds print no backend marker and are legacy-only, so an
    /// unmarked banner must not be assumed usable.
    #[test]
    fn a_banner_without_a_backend_marker_is_treated_as_legacy() {
        let dir = tempfile::tempdir().expect("tempdir");

        assert!(
            iptables_backend_is_usable(
                "iptables",
                Path::new("/usr/sbin/iptables"),
                "iptables v1.6.1\n",
                &unreachable_lock(&dir),
                PrivateNetworkUse::ProxyOnlyEgress
            )
            .is_err(),
            "a pre-1.8 build is legacy-only and must not be assumed usable"
        );
    }

    #[test]
    fn stderr_detail_keeps_the_tail_and_stays_bounded() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("supervisor.stderr");
        // The interesting line is last; everything before it is noise that must
        // not push it out of the quoted region.
        let mut noise = "x".repeat(MAX_STDERR_TAIL as usize * 4);
        noise.push_str("\nfatal: the-actual-failure\n");
        fs::write(&path, &noise).expect("write stderr");

        let detail = stderr_detail(&path);

        assert!(
            detail.contains("fatal: the-actual-failure"),
            "the tail (where the failure is) was dropped: {detail}"
        );
        assert!(
            detail.len() <= MAX_STDERR_TAIL as usize + 64,
            "quoted stderr was not bounded, got {} bytes",
            detail.len()
        );
    }

    #[test]
    fn stderr_detail_reports_absence_rather_than_an_empty_string() {
        let dir = tempfile::tempdir().expect("tempdir");
        let missing = dir.path().join("does-not-exist");
        assert_eq!(stderr_detail(&missing), "no stderr output");

        let empty = dir.path().join("empty.stderr");
        fs::write(&empty, "   \n").expect("write stderr");
        assert_eq!(stderr_detail(&empty), "no stderr output");
    }

    /// Chain name the fake supervisor installs into. Distinct from
    /// [`EGRESS_CHAIN`] so a test can never pass by matching production text.
    const TEST_CHAIN: &str = "mxc-test-chain";
    /// Inbound counterpart to [`TEST_CHAIN`].
    const TEST_INGRESS_CHAIN: &str = "mxc-test-ingress";

    /// Counts the restore commands and fails the one named by
    /// `MXC_TEST_FAIL_AT`. The real `nsenter` needs a live namespace and
    /// `CAP_SYS_ADMIN`; the script only cares whether it succeeded.
    ///
    /// The payload each restore would have applied is logged as
    /// `<tool> <line>`, so tests can still assert on the rules that reached
    /// iptables rather than only on the argument vector. The payload is found
    /// by being the one argument that names an existing file, so the stub does
    /// not have to track the renderer's filename scheme. A restore with no such
    /// argument fails, as the real one does when a glob matched nothing and
    /// reached it unexpanded.
    const FAKE_NSENTER: &str = r#"#!/bin/sh
PATH=$MXC_TEST_STUB_PATH
case "$*" in
    *" -- "*/ip" "*)
        if [ ! -e "$MXC_TEST_LOOPBACK_QUERY" ]; then
            printf '%s\n' "$*" > "$MXC_TEST_LOOPBACK_QUERY"
        fi
        if [ "$(cat "$MXC_TEST_LOOPBACK_STATE")" = "error" ]; then
            echo "fake nsenter: sandbox network namespace disappeared" >&2
            exit 1
        fi
        cat "$MXC_TEST_LOOPBACK_STATE"
        exit 0
        ;;
esac
count=$(cat "$MXC_TEST_COUNT" 2>/dev/null || echo 0)
count=$((count + 1))
printf '%s' "$count" > "$MXC_TEST_COUNT"
printf '%s\n' "$*" >> "$MXC_TEST_ARGS"
if [ "${MXC_TEST_FAIL_AT:-0}" = "$count" ]; then
    echo "fake nsenter: forced failure on rule $count" >&2
    exit 1
fi
tool=""
payload=""
for arg in "$@"; do
    case "$arg" in
        */iptables-restore|*/ip6tables-restore)
            tool="${arg##*/}"
            tool="${tool%-restore}"
            ;;
        -*) ;;
        *) [ -f "$arg" ] && payload="$arg" ;;
    esac
done
if [ -n "$tool" ] && [ -z "$payload" ]; then
    echo "fake nsenter: ${tool}-restore was given no payload file" >&2
    exit 1
fi
if [ -n "$tool" ] && [ -n "$payload" ]; then
    while IFS= read -r line; do
        printf '%s %s\n' "$tool" "$line" >> "$MXC_TEST_PAYLOAD"
    done < "$payload"
fi
exit 0
"#;

    /// Signals readiness on the descriptor the supervisor opened for it (9),
    /// then idles so the supervisor's `wait` has something to wait on.
    const FAKE_SLIRP: &str = r#"#!/bin/sh
PATH=$MXC_TEST_STUB_PATH
echo $$ > "$MXC_TEST_SLIRP_PID"
case "$(cat "$MXC_TEST_LOOPBACK_STATE")" in
    *" inet 127.0.0.1/8 "*) ;;
    *)
        echo "fake slirp4netns: started before Bubblewrap initialized loopback" >&2
        exit 1
        ;;
esac
if [ "${MXC_TEST_SLIRP_DIES:-0}" = "1" ]; then
    echo "fake slirp4netns: exiting before readiness" >&2
    exit 1
fi
printf ready >&9
exec sleep 30
"#;

    /// The supervisor script running for real against fake tools.
    ///
    /// The six text-matching tests above assert what the script *says*; they
    /// cannot assert what it *does*. This runs it under the same `sh` a host
    /// would use, with `nsenter`/`slirp4netns` replaced by stubs that can fail
    /// on demand, so the fail-closed ordering can be observed rather than read.
    struct FakeSupervisor {
        dir: TempDir,
        tools: NetworkTools,
        child: Supervisor,
        pid_writer: Option<File>,
        _exit_writer: OwnedFd,
    }

    impl FakeSupervisor {
        fn state_dir(&self) -> std::path::PathBuf {
            self.dir.path().join("state")
        }

        /// How many restore commands actually ran.
        fn rule_invocations(&self) -> u32 {
            fs::read_to_string(self.dir.path().join("rules.count"))
                .ok()
                .and_then(|value| value.trim().parse().ok())
                .unwrap_or(0)
        }

        /// Whether the supervisor told the parent the sandbox is enforced.
        fn signalled_ready(&self) -> bool {
            self.state_dir().join("slirp.ready").exists()
        }

        /// The argument vector of each `nsenter` call, in the order made.
        ///
        /// The count alone cannot distinguish a correct chain from one whose
        /// rules carry the wrong address, verdict or order, so the arguments
        /// that actually reached iptables are what the policy tests assert on.
        fn rule_log(&self) -> Vec<String> {
            fs::read_to_string(self.dir.path().join("rules.args"))
                .unwrap_or_default()
                .lines()
                .map(str::to_owned)
                .collect()
        }

        /// The `-A <chain>` rules, stripped to the part that expresses policy.
        ///
        /// Read from the restore payloads the supervisor actually handed to
        /// iptables: the count and argument vector alone cannot distinguish a
        /// correct chain from one whose rules carry the wrong address, verdict
        /// or order.
        fn chain_rules(&self) -> Vec<String> {
            let prefix = format!(" -A {TEST_CHAIN} ");
            fs::read_to_string(self.dir.path().join("rules.payload"))
                .unwrap_or_default()
                .lines()
                .filter_map(|line| {
                    let (tool, rest) = line.split_once(&prefix)?;
                    Some(format!("{tool} {rest}"))
                })
                .collect()
        }

        /// Every line of every restore payload, prefixed with its tool.
        fn payload_lines(&self) -> Vec<String> {
            fs::read_to_string(self.dir.path().join("rules.payload"))
                .unwrap_or_default()
                .lines()
                .map(str::to_owned)
                .collect()
        }

        fn stderr(&self) -> String {
            stderr_detail(&self.dir.path().join("supervisor.stderr"))
        }

        /// Hand over a sandbox PID, as the parent does once bwrap is up.
        fn publish_sandbox_pid(&mut self) {
            let mut writer = self.pid_writer.take().expect("pid writer");
            writer.write_all(b"4242\n").expect("publish pid");
        }

        /// Close the PID pipe without writing, as a parent that died would.
        fn abandon_without_publishing_pid(&mut self) {
            drop(self.pid_writer.take());
        }

        fn wait_for_exit(&mut self) -> ExitStatus {
            let deadline = Instant::now() + Duration::from_secs(20);
            while Instant::now() < deadline {
                if let Some(status) = self.child.poll().expect("poll") {
                    return status;
                }
                thread::sleep(Duration::from_millis(10));
            }
            panic!(
                "supervisor did not exit; stderr: {}, rules run: {}",
                self.stderr(),
                self.rule_invocations()
            );
        }

        fn wait_until_ready(&mut self) {
            let deadline = Instant::now() + Duration::from_secs(20);
            while Instant::now() < deadline {
                if self.signalled_ready() {
                    return;
                }
                if let Some(status) = self.child.poll().expect("poll") {
                    panic!(
                        "supervisor exited ({status}) without signalling readiness; \
                         stderr: {}, rules run: {}",
                        self.stderr(),
                        self.rule_invocations()
                    );
                }
                thread::sleep(Duration::from_millis(10));
            }
            panic!(
                "supervisor never signalled readiness; stderr: {}",
                self.stderr()
            );
        }
    }

    impl Drop for FakeSupervisor {
        fn drop(&mut self) {
            let _ = self.child.terminate();
            // `set -e` bypasses the script's TERM trap, so a stub left running
            // by an aborted supervisor has to be reaped here.
            if let Ok(pid) = fs::read_to_string(self.dir.path().join("slirp.pid")) {
                let pid = pid.trim();
                if !pid.is_empty() {
                    let _ = Command::new("kill")
                        .args(["-9", pid])
                        .stderr(Stdio::null())
                        .status();
                }
            }
        }
    }

    fn install_stub(path: &std::path::Path, body: &str) {
        fs::write(path, body).expect("write stub");
        let mut perms = fs::metadata(path).expect("stat stub").permissions();
        std::os::unix::fs::PermissionsExt::set_mode(&mut perms, 0o755);
        fs::set_permissions(path, perms).expect("chmod stub");
    }

    fn stub_tools(bin: &Path) -> NetworkTools {
        NetworkTools::find(PrivateNetworkUse::ProxyOnlyEgress, |name| match name {
            // The supervisor script runs these for real; its other tools are
            // stubs or are only handed to the fake `nsenter`.
            "sh" | "sleep" => host_tools::find(name),
            _ => Ok(bin.join(name)),
        })
        .expect("the host has sh and sleep")
    }

    fn spawn_fake_supervisor(fail_at: Option<u32>, slirp_dies: bool) -> FakeSupervisor {
        spawn_fake_supervisor_with_plan(
            &EgressPlan::for_proxy(SLIRP_HOST_GATEWAY_IP, 3128),
            &denied_ingress(),
            fail_at,
            slirp_dies,
        )
    }

    fn denied_ingress() -> IngressPlan {
        IngressPlan::for_policy(&Default::default())
    }

    fn spawn_fake_supervisor_with_plan(
        plan: &EgressPlan,
        ingress: &IngressPlan,
        fail_at: Option<u32>,
        slirp_dies: bool,
    ) -> FakeSupervisor {
        spawn_fake_supervisor_with_families(plan, ingress, rule_families(true), fail_at, slirp_dies)
    }

    /// [`spawn_fake_supervisor_with_plan`] with only `families` written to the
    /// state directory, as `start` does for a kernel without IPv6.
    fn spawn_fake_supervisor_with_families(
        plan: &EgressPlan,
        ingress: &IngressPlan,
        families: &[RuleFamily],
        fail_at: Option<u32>,
        slirp_dies: bool,
    ) -> FakeSupervisor {
        let dir = tempfile::tempdir().expect("tempdir");
        let bin = dir.path().join("bin");
        let state = dir.path().join("state");
        fs::create_dir_all(&bin).expect("bin dir");
        fs::create_dir_all(&state).expect("state dir");
        fs::write(
            dir.path().join("loopback.state"),
            "1: lo    inet 127.0.0.1/8 scope host lo\n",
        )
        .expect("loopback state");
        for &family in families {
            let payloads =
                render_filter_payloads(plan, ingress, family, TEST_CHAIN, TEST_INGRESS_CHAIN);
            for (index, payload) in payloads.iter().enumerate() {
                fs::write(
                    state.join(payload_file_name(family, index, payloads.len())),
                    payload,
                )
                .expect("rules payload");
            }
        }
        install_stub(&bin.join("nsenter"), FAKE_NSENTER);
        install_stub(&bin.join("slirp4netns"), FAKE_SLIRP);
        let tools = stub_tools(&bin);

        let stderr = File::create(dir.path().join("supervisor.stderr")).expect("stderr");
        let (exit_reader, exit_writer) = pipe2(OFlag::O_CLOEXEC).expect("exit pipe");
        let (pid_reader, pid_writer) = pipe2(OFlag::O_CLOEXEC).expect("pid pipe");

        // A PATH naming no real directory proves the script runs only the tools
        // it is handed. The stubs restore the test's own PATH for coreutils.
        let mut command = Command::new(&tools.sh);
        command
            .args(["-c", SUPERVISOR_SCRIPT, "mxc-test-supervisor"])
            .arg(&state)
            .arg("1")
            .args(tools.supervisor_arguments())
            .arg("no")
            .env("PATH", dir.path().join("no-tools"))
            .env(
                "MXC_TEST_STUB_PATH",
                std::env::var_os("PATH").unwrap_or_default(),
            )
            .env("MXC_TEST_COUNT", dir.path().join("rules.count"))
            .env("MXC_TEST_ARGS", dir.path().join("rules.args"))
            .env("MXC_TEST_PAYLOAD", dir.path().join("rules.payload"))
            .env("MXC_TEST_SLIRP_PID", dir.path().join("slirp.pid"))
            .env("MXC_TEST_LOOPBACK_QUERY", dir.path().join("loopback.query"))
            .env("MXC_TEST_LOOPBACK_STATE", dir.path().join("loopback.state"))
            .env(
                "MXC_TEST_FAIL_AT",
                fail_at.map(|n| n.to_string()).unwrap_or_default(),
            )
            .env("MXC_TEST_SLIRP_DIES", if slirp_dies { "1" } else { "0" })
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::from(stderr));
        remap_descriptors(
            &mut command,
            [
                (pid_reader.as_raw_fd(), SUPERVISOR_PID_FD),
                (exit_reader.as_raw_fd(), SUPERVISOR_EXIT_FD),
            ],
        );
        let child = Supervisor::new(command.spawn().expect("spawn supervisor"));
        drop(exit_reader);
        drop(pid_reader);

        FakeSupervisor {
            dir,
            tools,
            child,
            pid_writer: Some(File::from(pid_writer)),
            _exit_writer: exit_writer,
        }
    }

    #[test]
    fn slirp_waits_for_bubblewrap_to_initialize_loopback() {
        for pending in ["", "1: lo    inet 127.0.0.2/8 scope host lo\n"] {
            let mut supervisor = spawn_fake_supervisor(None, false);
            let state = supervisor.dir.path().join("loopback.state");
            fs::write(&state, pending).expect("pending loopback state");
            supervisor.publish_sandbox_pid();

            wait_for_file(
                supervisor.dir.path().join("loopback.query"),
                &mut supervisor.child,
                &supervisor.dir.path().join("supervisor.stderr"),
                "loopback readiness query",
                Duration::from_secs(20),
            )
            .expect("loopback must be queried before slirp starts");
            assert!(
                !supervisor.dir.path().join("slirp.pid").exists(),
                "slirp started while loopback was not ready: {}",
                supervisor.stderr()
            );
            assert_eq!(supervisor.rule_invocations(), 0);
            assert!(!supervisor.signalled_ready());
            let query = fs::read_to_string(supervisor.dir.path().join("loopback.query"))
                .expect("query arguments");
            assert_eq!(
                query.trim(),
                format!(
                    "--net=/proc/4242/ns/net -- {} -4 -o address show dev lo up",
                    supervisor.tools.ip.display()
                )
            );

            fs::write(&state, "1: lo    inet 127.0.0.1/8 scope host lo\n")
                .expect("initialized loopback state");
            supervisor.wait_until_ready();
            assert_eq!(supervisor.rule_invocations(), 2);
        }
    }

    #[test]
    fn a_failed_loopback_query_stops_startup_before_slirp() {
        let mut supervisor = spawn_fake_supervisor(None, false);
        fs::write(supervisor.dir.path().join("loopback.state"), "error")
            .expect("failed loopback state");
        supervisor.publish_sandbox_pid();

        let status = supervisor.wait_for_exit();
        assert!(!status.success(), "{status}");
        assert!(
            supervisor
                .stderr()
                .contains("network namespace disappeared"),
            "{}",
            supervisor.stderr()
        );
        assert!(
            supervisor
                .stderr()
                .contains("failed to query Bubblewrap loopback readiness"),
            "{}",
            supervisor.stderr()
        );
        assert!(
            !supervisor.dir.path().join("slirp.pid").exists(),
            "slirp must not start after a failed loopback query"
        );
        assert_eq!(supervisor.rule_invocations(), 0);
        assert!(!supervisor.signalled_ready());
    }

    #[test]
    fn pending_loopback_uses_the_existing_network_startup_deadline() {
        let mut supervisor = spawn_fake_supervisor(None, false);
        fs::write(supervisor.dir.path().join("loopback.state"), "")
            .expect("pending loopback state");
        supervisor.publish_sandbox_pid();
        wait_for_file(
            supervisor.dir.path().join("loopback.query"),
            &mut supervisor.child,
            &supervisor.dir.path().join("supervisor.stderr"),
            "loopback readiness query",
            Duration::from_secs(20),
        )
        .expect("loopback query must start before the deadline is tested");

        let error = wait_for_file(
            supervisor.state_dir().join("slirp.ready"),
            &mut supervisor.child,
            &supervisor.dir.path().join("supervisor.stderr"),
            "slirp4netns startup and network rule installation",
            Duration::ZERO,
        )
        .expect_err("pending loopback must not bypass the network startup deadline");
        assert!(error.contains("timed out"), "{error}");
        assert!(!supervisor.dir.path().join("slirp.pid").exists());
        assert_eq!(supervisor.rule_invocations(), 0);
        assert!(!supervisor.signalled_ready());
    }

    /// An ordinary policy still fits one transaction per family, and both hooks
    /// ride in it, so a hook is never live over a partially built chain.
    #[test]
    fn each_family_is_restored_from_its_own_payload_in_one_transaction() {
        let mut supervisor = spawn_fake_supervisor(None, false);
        supervisor.publish_sandbox_pid();
        supervisor.wait_until_ready();

        let calls = supervisor.rule_log();
        assert_eq!(calls.len(), 2, "{calls:?}");
        for (call, tool) in calls.iter().zip(["iptables-restore", "ip6tables-restore"]) {
            assert!(call.contains(tool), "{calls:?}");
            assert!(call.contains(" -n "), "restore must be additive: {call}");
        }

        for tool in ["iptables", "ip6tables"] {
            let lines: Vec<String> = supervisor
                .payload_lines()
                .into_iter()
                .filter_map(|line| line.strip_prefix(&format!("{tool} ")).map(str::to_owned))
                .collect();
            assert_eq!(lines.first().map(String::as_str), Some("*filter"), "{tool}");
            assert_eq!(
                lines[lines.len() - 3],
                format!("-A OUTPUT -j {TEST_CHAIN}"),
                "the {tool} egress hook must be committed with its chain"
            );
            assert_eq!(
                lines[lines.len() - 2],
                format!("-A INPUT -j {TEST_INGRESS_CHAIN}"),
                "the {tool} ingress hook must be committed with its chain"
            );
            assert_eq!(lines.last().map(String::as_str), Some("COMMIT"), "{tool}");
        }
    }

    /// A kernel without IPv6 gets no IPv6 payload, and the supervisor must
    /// still come up on the IPv4 rules alone rather than hand the unmatched
    /// glob to `ip6tables-restore`.
    #[test]
    fn a_kernel_without_ipv6_is_enforced_by_the_ipv4_rules_alone() {
        let mut supervisor = spawn_fake_supervisor_with_families(
            &EgressPlan::for_proxy(SLIRP_HOST_GATEWAY_IP, 3128),
            &denied_ingress(),
            rule_families(false),
            None,
            false,
        );
        supervisor.publish_sandbox_pid();
        supervisor.wait_until_ready();

        let calls = supervisor.rule_log();
        assert_eq!(calls.len(), 1, "{calls:?}");
        assert!(calls[0].contains("iptables-restore"), "{calls:?}");
        assert!(!calls[0].contains("ip6tables-restore"), "{calls:?}");
        let lines = supervisor.payload_lines();
        assert!(
            lines.contains(&format!("iptables -A OUTPUT -j {TEST_CHAIN}")),
            "the IPv4 egress hook must still be installed: {lines:?}"
        );
        assert!(
            lines.iter().all(|line| line.starts_with("iptables ")),
            "{lines:?}"
        );
    }

    /// The IPv6 loop's tolerance of a missing payload must not reach IPv4: an
    /// absent IPv4 payload means the parent failed, not that the family is
    /// unnecessary, so the supervisor has to die instead of signalling ready.
    #[test]
    fn a_missing_ipv4_payload_still_kills_the_supervisor() {
        let mut supervisor = spawn_fake_supervisor_with_families(
            &EgressPlan::for_proxy(SLIRP_HOST_GATEWAY_IP, 3128),
            &denied_ingress(),
            &[RuleFamily::V6],
            None,
            false,
        );
        supervisor.publish_sandbox_pid();

        let status = supervisor.wait_for_exit();
        assert!(!status.success(), "{status}");
        assert!(
            !supervisor.signalled_ready(),
            "readiness must never follow a missing IPv4 payload"
        );
        assert!(
            !supervisor
                .rule_log()
                .iter()
                .any(|call| call.contains("ip6tables-restore")),
            "the supervisor must stop at the first failed family"
        );
    }

    /// The inbound chain has to survive the trip through the supervisor, not
    /// just the renderer: it is only real once iptables receives it.
    #[test]
    fn the_supervisor_installs_the_inbound_chain_alongside_the_outbound_one() {
        let mut supervisor = spawn_fake_supervisor(None, false);
        supervisor.publish_sandbox_pid();
        supervisor.wait_until_ready();

        for tool in ["iptables", "ip6tables"] {
            let lines: Vec<String> = supervisor
                .payload_lines()
                .into_iter()
                .filter_map(|line| line.strip_prefix(&format!("{tool} ")).map(str::to_owned))
                .collect();
            assert!(
                lines.contains(&format!(":{TEST_INGRESS_CHAIN} - [0:0]")),
                "{tool} must declare the inbound chain: {lines:?}"
            );
            assert!(
                lines
                    .iter()
                    .any(|line| line.contains("ESTABLISHED,RELATED -j ACCEPT")),
                "{tool} must keep replies flowing: {lines:?}"
            );
        }

        assert_eq!(
            supervisor.rule_log().len(),
            2,
            "the inbound chain must not cost an extra transaction"
        );
    }

    /// Executing the script also re-checks that the whole policy travels in
    /// the restore transactions the budget is sized for.
    #[test]
    fn the_supervisor_signals_readiness_only_after_every_rule_is_installed() {
        let mut supervisor = spawn_fake_supervisor(None, false);
        supervisor.publish_sandbox_pid();
        supervisor.wait_until_ready();

        assert_eq!(
            supervisor.rule_invocations(),
            2,
            "readiness was signalled after a different number of restores than the \
             startup budget is sized for; stderr: {}",
            supervisor.stderr()
        );
    }

    /// Batching is the point: an ordinary policy costs two transactions however
    /// many directional rules it carries.
    #[test]
    fn a_policy_plan_installs_a_fixed_number_of_commands() {
        for rule_count in [0, 1, 5, 50] {
            let plan = plan_with_rule_count(rule_count);
            let mut supervisor =
                spawn_fake_supervisor_with_plan(&plan, &denied_ingress(), None, false);
            supervisor.publish_sandbox_pid();
            supervisor.wait_until_ready();

            assert_eq!(
                supervisor.rule_invocations(),
                2,
                "a {rule_count}-rule policy installed the wrong number of commands; \
                 stderr: {}",
                supervisor.stderr()
            );
            assert_eq!(
                supervisor
                    .chain_rules()
                    .iter()
                    .filter(|rule| rule.contains(" -d "))
                    .count(),
                rule_count + 1,
                "a {rule_count}-rule policy plus the host-loopback drop reached iptables \
                 with the wrong rule count"
            );
        }
    }

    /// The regression the byte budget exists for. A policy too large for one
    /// netlink transaction must still arrive complete and in order, spread over
    /// as many restores as it takes -- the previous single-transaction renderer
    /// failed the whole table instead, and installed nothing.
    #[test]
    fn a_policy_too_large_for_one_transaction_is_split_and_still_arrives_whole() {
        let rule_count = 2000;
        let plan = plan_with_rule_count(rule_count);
        let mut supervisor = spawn_fake_supervisor_with_plan(&plan, &denied_ingress(), None, false);
        supervisor.publish_sandbox_pid();
        supervisor.wait_until_ready();

        assert!(
            supervisor.rule_invocations() > 2,
            "a {rule_count}-rule policy must not fit two transactions, or this test \
             is not exercising the split"
        );

        let installed: Vec<String> = supervisor
            .chain_rules()
            .into_iter()
            .filter(|rule| rule.contains(" -d ") && rule.ends_with(" -j ACCEPT"))
            .collect();
        assert_eq!(
            installed.len(),
            rule_count,
            "splitting dropped rules; stderr: {}",
            supervisor.stderr()
        );
        // Order is the policy, so the split must preserve it end to end.
        for (index, rule) in installed.iter().enumerate() {
            let expected = format!(
                "iptables -d 10.0.{}.{}/32 -j ACCEPT",
                index / 256,
                index % 256
            );
            assert_eq!(rule, &expected, "rule {index} arrived out of order");
        }
    }

    /// The fail-closed guarantee of the whole feature: a restore that does not
    /// apply must take the supervisor down *before* readiness, so the parent
    /// never releases a sandbox whose egress is unenforced.
    ///
    /// Asserting it for every position is the point. A future edit that moves
    /// one command into a pipeline, an `if` condition or a subshell escapes
    /// `set -e` and would start an unenforced sandbox while every text-matching
    /// test above stayed green.
    #[test]
    fn a_failed_rule_kills_the_supervisor_instead_of_signalling_readiness() {
        let plan = plan_with_rule_count(3);
        for rule in 1..=2 {
            let mut supervisor =
                spawn_fake_supervisor_with_plan(&plan, &denied_ingress(), Some(rule), false);
            supervisor.publish_sandbox_pid();
            let status = supervisor.wait_for_exit();

            assert!(
                !status.success(),
                "restore {rule} failed but the supervisor exited successfully; stderr: {}",
                supervisor.stderr()
            );
            assert!(
                !supervisor.signalled_ready(),
                "restore {rule} failed yet the sandbox was signalled ready -- it would \
                 have run with unenforced egress"
            );
            assert_eq!(
                supervisor.rule_invocations(),
                rule,
                "restore {rule} failed but the script carried on installing rules"
            );
        }
    }

    /// The chain the workload actually runs under, for a policy the reviewer
    /// can read off the config. Ordering is asserted as a whole sequence
    /// because in a first-match chain a correct set of rules in the wrong order
    /// is a different policy.
    #[test]
    fn a_deny_policy_accepts_only_its_allow_rules_and_closes_both_families() {
        let plan = directional_plan(
            crate::mxc_common::models::NetworkAction::Deny,
            &["203.0.113.7/32", "2001:db8::/32"],
            &[],
        );

        let mut supervisor = spawn_fake_supervisor_with_plan(&plan, &denied_ingress(), None, false);
        supervisor.publish_sandbox_pid();
        supervisor.wait_until_ready();

        assert_eq!(
            supervisor.chain_rules(),
            vec![
                "iptables -o lo -j ACCEPT".to_string(),
                "iptables -d 10.0.2.2/32 -j DROP".to_string(),
                "iptables -d 203.0.113.7/32 -j ACCEPT".to_string(),
                "iptables -j DROP".to_string(),
                "ip6tables -o lo -j ACCEPT".to_string(),
                "ip6tables -d 2001:db8::/32 -j ACCEPT".to_string(),
                "ip6tables -j DROP".to_string(),
            ],
            "stderr: {}",
            supervisor.stderr()
        );
    }

    /// D4: an explicit deny beats a broader allow. In an ordered chain that is
    /// purely a question of which rule is appended first, so it is asserted
    /// against what reached iptables rather than against the plan alone.
    #[test]
    fn an_allow_policy_denies_its_deny_rules_before_the_open_terminal() {
        let plan = directional_plan(
            crate::mxc_common::models::NetworkAction::Allow,
            &["198.51.100.9/32"],
            &["198.51.100.0/24"],
        );

        let mut supervisor = spawn_fake_supervisor_with_plan(&plan, &denied_ingress(), None, false);
        supervisor.publish_sandbox_pid();
        supervisor.wait_until_ready();

        let rules = supervisor.chain_rules();
        let deny = rules
            .iter()
            .position(|rule| rule == "iptables -d 198.51.100.0/24 -j DROP")
            .expect("the deny must be installed");
        let allow = rules
            .iter()
            .position(|rule| rule == "iptables -d 198.51.100.9/32 -j ACCEPT")
            .expect("the allow must be installed");
        let terminal = rules
            .iter()
            .position(|rule| rule == "iptables -j ACCEPT")
            .expect("an allow policy must end in ACCEPT");

        assert!(
            deny < allow,
            "the narrower deny must be evaluated first, or it never matches: {rules:?}"
        );
        assert!(
            allow < terminal,
            "the open terminal must come last: {rules:?}"
        );
    }

    /// The proxy posture must be byte-for-byte what it was before the rule list
    /// generalised it: this path is already reviewed and already shipping.
    #[test]
    fn the_proxy_posture_is_unchanged_by_the_rule_list() {
        let plan = EgressPlan::for_proxy(Ipv4Addr::new(10, 1, 2, 3), 3128);
        let mut supervisor = spawn_fake_supervisor_with_plan(&plan, &denied_ingress(), None, false);
        supervisor.publish_sandbox_pid();
        supervisor.wait_until_ready();

        assert_eq!(
            supervisor.chain_rules(),
            vec![
                "iptables -o lo -j ACCEPT".to_string(),
                "iptables -p tcp -d 10.1.2.3 --dport 3128 -j ACCEPT".to_string(),
                "iptables -j DROP".to_string(),
                "ip6tables -o lo -j ACCEPT".to_string(),
                "ip6tables -j DROP".to_string(),
            ],
            "stderr: {}",
            supervisor.stderr()
        );
    }

    /// An IPv4-only rule set must still close IPv6, or the sandbox keeps a
    /// silent v6 exit that no rule in the config mentions.
    #[test]
    fn a_v4_only_policy_still_closes_ipv6() {
        let plan = directional_plan(
            crate::mxc_common::models::NetworkAction::Deny,
            &["203.0.113.7/32"],
            &[],
        );

        let mut supervisor = spawn_fake_supervisor_with_plan(&plan, &denied_ingress(), None, false);
        supervisor.publish_sandbox_pid();
        supervisor.wait_until_ready();

        assert!(
            supervisor
                .chain_rules()
                .contains(&"ip6tables -j DROP".to_string()),
            "IPv6 was left open by a v4-only policy: {:?}",
            supervisor.chain_rules()
        );
    }

    #[test]
    fn the_supervisor_gives_up_when_slirp_dies_before_signalling_readiness() {
        let mut supervisor = spawn_fake_supervisor(None, true);
        supervisor.publish_sandbox_pid();
        let status = supervisor.wait_for_exit();

        assert!(!status.success(), "a dead slirp must fail the startup");
        assert!(!supervisor.signalled_ready());
        assert!(
            supervisor.stderr().contains("before signalling readiness"),
            "the failure must say slirp never came up: {}",
            supervisor.stderr()
        );
        assert_eq!(
            supervisor.rule_invocations(),
            0,
            "rules were installed against a namespace with no connectivity"
        );
    }

    /// The blocking read on the PID pipe exists so a supervisor whose parent
    /// died exits instead of spinning as an orphan holding a namespace.
    #[test]
    fn the_supervisor_exits_when_the_parent_never_publishes_the_sandbox_pid() {
        let mut supervisor = spawn_fake_supervisor(None, false);
        supervisor.abandon_without_publishing_pid();
        let status = supervisor.wait_for_exit();

        assert!(
            !status.success(),
            "an unpublished PID must fail the startup"
        );
        assert!(!supervisor.signalled_ready());
        assert!(
            supervisor.stderr().contains("before publishing"),
            "the failure must name the missing PID: {}",
            supervisor.stderr()
        );
        assert_eq!(supervisor.rule_invocations(), 0);
    }

    /// A namespace whose supervisor is `script`, every other field inert, for
    /// exercising the pre-gate liveness check on its own.
    fn namespace_running(script: &str) -> ProxyNetworkNamespace {
        let state_dir = tempfile::tempdir().expect("tempdir");
        let stderr = File::create(state_dir.path().join("supervisor.stderr")).expect("stderr");
        let supervisor = Command::new("sh")
            .args(["-c", script])
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::from(stderr))
            .spawn()
            .map(Supervisor::new)
            .expect("spawn supervisor");

        namespace_with(state_dir, supervisor)
    }

    fn namespace_with(state_dir: TempDir, supervisor: Supervisor) -> ProxyNetworkNamespace {
        ProxyNetworkNamespace {
            state_dir,
            supervisor,
            exit_writer: None,
            pid_writer: None,
            userns: None,
            hosts: None,
            resolver: None,
            liveness_reader: None,
            transactions: 0,
            script_timeout_ms: 0,
        }
    }

    /// `nsenter` stand-in that never returns, like a query stuck in a wedged
    /// namespace. It `exec`s, so the recorded PID is the blocked process itself.
    const BLOCKING_NSENTER: &str =
        "#!/bin/sh\necho $$ > \"$MXC_TEST_BLOCKED_PID\"\nexec sleep 300\n";

    fn process_is_gone(pid: u32) -> bool {
        match fs::read_to_string(format!("/proc/{pid}/stat")) {
            Err(_) => true,
            Ok(stat) => stat
                .rsplit(')')
                .next()
                .is_some_and(|rest| rest.trim_start().starts_with('Z')),
        }
    }

    /// Drives the real supervisor script and the production `attach` and
    /// `stop` through a loopback query that never returns: the deadline must
    /// apply, the workload gate must stay closed, and the blocked child -- not
    /// just the supervisor shell -- must be gone afterwards.
    #[test]
    fn a_blocked_loopback_query_fails_attach_without_opening_the_gate_or_leaking_children() {
        let state_dir = tempfile::tempdir().expect("tempdir");
        let bin = state_dir.path().join("bin");
        fs::create_dir_all(&bin).expect("bin dir");
        install_stub(&bin.join("nsenter"), BLOCKING_NSENTER);
        let tools = stub_tools(&bin);
        let blocked_pid_path = state_dir.path().join("blocked.pid");
        let stderr = File::create(state_dir.path().join("supervisor.stderr")).expect("stderr");
        let (exit_reader, exit_writer) = pipe2(OFlag::O_CLOEXEC).expect("exit pipe");
        let (pid_reader, pid_writer) = pipe2(OFlag::O_CLOEXEC).expect("pid pipe");

        let mut command = Command::new(&tools.sh);
        command
            .args(["-c", SUPERVISOR_SCRIPT, "mxc-test-supervisor"])
            .arg(state_dir.path())
            .arg("1")
            .args(tools.supervisor_arguments())
            .arg("no")
            .env("MXC_TEST_BLOCKED_PID", &blocked_pid_path)
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::from(stderr))
            .process_group(0);
        remap_descriptors(
            &mut command,
            [
                (pid_reader.as_raw_fd(), SUPERVISOR_PID_FD),
                (exit_reader.as_raw_fd(), SUPERVISOR_EXIT_FD),
            ],
        );
        let supervisor = Supervisor::new(command.spawn().expect("spawn supervisor"));
        drop(exit_reader);
        drop(pid_reader);

        let mut network = ProxyNetworkNamespace {
            state_dir,
            supervisor,
            exit_writer: Some(exit_writer),
            pid_writer: Some(pid_writer),
            userns: Some(File::open("/dev/null").expect("stand-in namespace handle")),
            hosts: None,
            resolver: None,
            liveness_reader: None,
            transactions: 0,
            script_timeout_ms: 0,
        };
        let mut logger = Logger::new(crate::mxc_common::logger::Mode::Buffer);
        let mut startup = network
            .configure_bwrap(&mut Vec::new(), &mut logger)
            .expect("startup descriptors");
        let gate = startup.gate_reader.take().expect("gate reader");
        set_nonblocking(gate.as_raw_fd()).expect("nonblocking gate");
        let mut gate = File::from(gate);

        let error = network
            .attach_within(4242, Duration::from_secs(3), &mut logger)
            .and_then(|()| startup.release())
            .expect_err("a blocked loopback query must fail the startup");
        assert!(
            error.contains(
                "timed out waiting for slirp4netns startup and network rule installation"
            ),
            "{error}"
        );

        let mut byte = [0_u8; 1];
        assert_eq!(
            gate.read(&mut byte)
                .expect_err("the gate is still held")
                .kind(),
            ErrorKind::WouldBlock,
            "nothing may open the workload gate after a failed attach"
        );

        let deadline = Instant::now() + Duration::from_secs(10);
        while !blocked_pid_path.exists() && Instant::now() < deadline {
            thread::sleep(Duration::from_millis(10));
        }
        let blocked_pid: u32 = fs::read_to_string(&blocked_pid_path)
            .unwrap_or_else(|error| {
                panic!(
                    "the loopback query must have started: {error}; supervisor stderr: {}",
                    stderr_detail(&network.state_dir.path().join("supervisor.stderr"))
                )
            })
            .trim()
            .parse()
            .expect("blocked pid");
        network.stop(&mut logger);
        assert!(
            network.supervisor.poll().expect("poll").is_some(),
            "the supervisor must be reaped"
        );
        let deadline = Instant::now() + Duration::from_secs(5);
        while !process_is_gone(blocked_pid) && Instant::now() < deadline {
            thread::sleep(Duration::from_millis(10));
        }
        assert!(
            process_is_gone(blocked_pid),
            "the blocked nsenter child {blocked_pid} outlived the supervisor"
        );
    }

    /// A supervisor that exits while a child of its group is still blocked
    /// must not leave that child behind, whichever path observes the exit.
    #[test]
    fn a_supervisor_that_exits_early_does_not_leave_its_group_running() {
        for observe in ["poll", "stop"] {
            let dir = tempfile::tempdir().expect("tempdir");
            let pid_path = dir.path().join("blocked.pid");
            let mut command = Command::new("sh");
            command
                .args(["-c", "sleep 300 & echo $! > \"$1\"", "mxc-test-supervisor"])
                .arg(&pid_path)
                .stdin(Stdio::null())
                .stdout(Stdio::null())
                .stderr(Stdio::null())
                .process_group(0);
            let mut supervisor = Supervisor::new(command.spawn().expect("spawn supervisor"));

            let deadline = Instant::now() + Duration::from_secs(20);
            let blocked_pid: u32 = loop {
                if let Ok(pid) = fs::read_to_string(&pid_path) {
                    if let Ok(pid) = pid.trim().parse() {
                        break pid;
                    }
                }
                assert!(Instant::now() < deadline, "the blocked child never started");
                thread::sleep(Duration::from_millis(10));
            };

            if observe == "poll" {
                let deadline = Instant::now() + Duration::from_secs(20);
                while supervisor.poll().expect("poll").is_none() {
                    assert!(Instant::now() < deadline, "supervisor did not exit");
                    thread::sleep(Duration::from_millis(10));
                }
            } else {
                let mut network =
                    namespace_with(tempfile::tempdir().expect("state dir"), supervisor);
                let mut logger = Logger::new(crate::mxc_common::logger::Mode::Buffer);
                network.stop(&mut logger);
            }

            let deadline = Instant::now() + Duration::from_secs(5);
            while !process_is_gone(blocked_pid) && Instant::now() < deadline {
                thread::sleep(Duration::from_millis(10));
            }
            assert!(
                process_is_gone(blocked_pid),
                "{observe}: the blocked child {blocked_pid} outlived the supervisor"
            );
        }
    }

    fn await_exit(namespace: &mut ProxyNetworkNamespace) {
        let deadline = Instant::now() + Duration::from_secs(20);
        while Instant::now() < deadline {
            if namespace.supervisor.poll().expect("poll").is_some() {
                return;
            }
            thread::sleep(Duration::from_millis(10));
        }
        panic!("supervisor did not exit");
    }

    #[test]
    fn the_gate_check_passes_while_the_supervisor_is_running() {
        let mut network = namespace_running("sleep 30");

        assert!(
            network.check_alive().is_ok(),
            "a running supervisor must not block the workload"
        );
    }

    #[test]
    fn the_gate_check_refuses_a_supervisor_that_died_after_signalling_readiness() {
        let mut network = namespace_running("echo 'slirp4netns: crashed' >&2; exit 1");
        await_exit(&mut network);

        let error = network
            .check_alive()
            .expect_err("a dead supervisor must not reach the workload");
        assert!(
            error.contains("no network provider"),
            "the failure must name the lost provider rather than read as a workload \
             error: {error}"
        );
        assert!(
            error.contains("slirp4netns: crashed"),
            "the failure must carry what the supervisor wrote: {error}"
        );
    }

    /// Slirp carries the sandbox's only route, so its exit code says nothing
    /// about whether the sandbox still has a network.
    #[test]
    fn the_gate_check_refuses_even_a_supervisor_that_exited_cleanly() {
        let mut network = namespace_running("exit 0");
        await_exit(&mut network);

        assert!(
            network.check_alive().is_err(),
            "a successful exit still leaves the sandbox with no route"
        );
    }
}